diff --git a/.github/workflows/githubAction.yml b/.github/workflows/githubAction.yml index e31d3d4c..894fd347 100644 --- a/.github/workflows/githubAction.yml +++ b/.github/workflows/githubAction.yml @@ -9,7 +9,7 @@ name: Java CI with Gradle on: push: - branches: [ "develop","Backend#105/https설정2", "1차데모" ] # develop 브랜치에 푸쉬하면 스크립트 실행 + branches: [ "develop","Backend#123/nodejs서버추가" ] # develop 브랜치에 푸쉬하면 스크립트 실행 pull_request: branches: [ "develop" ] # develop 브랜치에 풀리퀘되면 스크립트 실행 @@ -67,6 +67,13 @@ jobs: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} docker build -f ./frontend/dockerfile --platform linux/amd64 -t ${{ secrets.DOCKER_REPO }}:frontend ./frontend docker push ${{ secrets.DOCKER_REPO }}:frontend + + - name: Docker build nodejs & push to docker repo + run: | + docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + docker build -f ./nodejs/dockerfile --platform linux/amd64 -t ${{ secrets.DOCKER_REPO }}:nodejs ./nodejs + docker push ${{ secrets.DOCKER_REPO }}:nodejs + # appleboy/ssh-action@master 액션을 사용하여 지정한 서버에 ssh로 접속하고, script를 실행합니다. # script의 내용은 도커의 기존 프로세스들을 제거하고, docker repo로부터 방금 위에서 push한 내용을 pull 받아 실행하는 것입니다. diff --git a/backend/shareNote/docker-compose.yml b/backend/shareNote/docker-compose.yml index 99c1ac08..61a016bb 100644 --- a/backend/shareNote/docker-compose.yml +++ b/backend/shareNote/docker-compose.yml @@ -53,6 +53,13 @@ services: volumes: - ./rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf + nodejs: + container_name: nodejs + image: qmfdnjssk/share_repository:nodejslocal + ports: + - "4000:4000" + + restart: on-failure diff --git a/backend/shareNote/src/main/java/com/Backend/shareNote/domain/EmailService/EmailService.java b/backend/shareNote/src/main/java/com/Backend/shareNote/domain/EmailService/EmailService.java index ca349c70..1f0a463e 100644 --- a/backend/shareNote/src/main/java/com/Backend/shareNote/domain/EmailService/EmailService.java +++ b/backend/shareNote/src/main/java/com/Backend/shareNote/domain/EmailService/EmailService.java @@ -1,10 +1,12 @@ package com.Backend.shareNote.domain.EmailService; +import jakarta.mail.internet.MimeMessage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @@ -19,21 +21,54 @@ public class EmailService { private final JavaMailSender javaMailSender; @Async public boolean sendMail(EmailDTO emailDTO) { - boolean msg = false; - SimpleMailMessage message = new SimpleMailMessage(); - log.info("이메일 어디로 갔을까?? : " + emailDTO.getTargetMail()); - message.setTo(emailDTO.getTargetMail()); - message.setSubject("너 내 동료가 돼라"); - message.setFrom(mailProperties.getUsername()); - message.setText("너 이 링크를 누르고 내 동료가 돼라!! from " +emailDTO.getNickname() + " " + emailDTO.getLink()); - try { - javaMailSender.send(message); + MimeMessage mimeMessage = javaMailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8"); + + helper.setTo(emailDTO.getTargetMail()); + helper.setSubject("sharenote 초대장"); + helper.setFrom("your-email@example.com"); // 이메일 발신자 주소 + String htmlMsg = """ +
+

안녕하세요  """ + emailDTO.getNickname() + """ + 님으로부터 도착한 초대장입니다.

+

아래의 버튼을 눌러 노트를 작성해주세요!

+
+ 초대장 +
+ +

+
+ """; + + helper.setText(htmlMsg, true); // HTML 콘텐츠로 이메일 설정 + + + javaMailSender.send(mimeMessage); + return true; } catch (Exception e) { e.printStackTrace(); - return msg; + return false; } - return msg = true; - } } + +// boolean msg = false; +// SimpleMailMessage message = new SimpleMailMessage(); +// log.info("이메일 어디로 갔을까?? : " + emailDTO.getTargetMail()); +// message.setTo(emailDTO.getTargetMail()); +// message.setSubject("너 내 동료가 돼라"); +// message.setFrom(mailProperties.getUsername()); +// message.setText("너 이 링크를 누르고 내 동료가 돼라!! from " +emailDTO.getNickname() + " " + emailDTO.getLink()); +// +// try { +// javaMailSender.send(message); +// } catch (Exception e) { +// e.printStackTrace(); +// return msg; +// } +// return msg = true; + +// } +//} diff --git a/backend/shareNote/src/main/java/com/Backend/shareNote/domain/Oraganization/service/OrganizationService.java b/backend/shareNote/src/main/java/com/Backend/shareNote/domain/Oraganization/service/OrganizationService.java index f7a3effc..8fcacb6e 100644 --- a/backend/shareNote/src/main/java/com/Backend/shareNote/domain/Oraganization/service/OrganizationService.java +++ b/backend/shareNote/src/main/java/com/Backend/shareNote/domain/Oraganization/service/OrganizationService.java @@ -104,7 +104,8 @@ public ResponseEntity inviteOrganization(OrganizationInvitation invitati //쿼리 파라미터로 동작 //이 링크 클릭 시 토큰을 localStorage에 저장하고 //login 시 토큰을 가져와서 organization 초대 수락하기 - emailDTO.setLink("http://localhost:3000/organization/invitation/approve?token=" + Token); + //emailDTO.setLink("http://localhost:3000/organization/invitation/approve?token=" + Token); + emailDTO.setLink("http://sharenote.shop/organization/invitation/approve?token=" + Token); emailService.sendMail(emailDTO); return ResponseEntity.ok("초대장 전송 완료"); } diff --git a/frontend/src/Component/Page/Page.js b/frontend/src/Component/Page/Page.js index 659c5fd9..976fbc1a 100644 --- a/frontend/src/Component/Page/Page.js +++ b/frontend/src/Component/Page/Page.js @@ -77,7 +77,9 @@ function Page() { const roomId = noteId; const ydoc = getYDocInstance(roomId); const provider = new WebsocketProvider( - "wss://demos.yjs.dev/ws", // 웹소켓 서버 주소, // 웹소켓 서버 주소 + //"wss://demos.yjs.dev/ws", // 웹소켓 서버 주소, // 웹소켓 서버 주소 + "ws://localhost:4000", + //"ws://nodejs:4000", //배포용 roomId, // 방 이름 ydoc ); diff --git a/frontend/src/Component/imageToBackend.js b/frontend/src/Component/imageToBackend.js index 487c7ab9..9bd6b3d9 100644 --- a/frontend/src/Component/imageToBackend.js +++ b/frontend/src/Component/imageToBackend.js @@ -42,7 +42,8 @@ function ImagetoBackend({ onImageUpload }) { formData.append("multipartFile", selectedFile); $.ajax({ - url: "http://localhost:8080/api/image", + //url: "http://localhost:8080/api/image", + url: "http://sharenote.shop/api/image", type: "POST", data: formData, processData: false, diff --git a/nodejs/Dockerfile b/nodejs/Dockerfile new file mode 100644 index 00000000..c0ba7d2c --- /dev/null +++ b/nodejs/Dockerfile @@ -0,0 +1,20 @@ +# 베이스 이미지로 Node.js 16 버전 사용 +FROM node:16 + +# 작업 디렉토리 설정 (/app 내에서 모든 명령어 실행) +WORKDIR /app + +# package.json 및 package-lock.json (있는 경우) 복사 +COPY package*.json ./ + +# 패키지 의존성 설치 +RUN npm install + +# 나머지 서버 코드 복사 +COPY . . + +# 서버가 리스닝할 포트 번호 설정 +EXPOSE 4000 + +# 서버 시작 명령어 +CMD ["node", "server.js"] diff --git a/nodejs/node_modules/.bin/0ecdsa-generate-keypair b/nodejs/node_modules/.bin/0ecdsa-generate-keypair new file mode 120000 index 00000000..1a0e751c --- /dev/null +++ b/nodejs/node_modules/.bin/0ecdsa-generate-keypair @@ -0,0 +1 @@ +../lib0/bin/0ecdsa-generate-keypair.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/0gentesthtml b/nodejs/node_modules/.bin/0gentesthtml new file mode 120000 index 00000000..ab1259c0 --- /dev/null +++ b/nodejs/node_modules/.bin/0gentesthtml @@ -0,0 +1 @@ +../lib0/bin/gentesthtml.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/0serve b/nodejs/node_modules/.bin/0serve new file mode 120000 index 00000000..e0faa790 --- /dev/null +++ b/nodejs/node_modules/.bin/0serve @@ -0,0 +1 @@ +../lib0/bin/0serve.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/errno b/nodejs/node_modules/.bin/errno new file mode 120000 index 00000000..5a98e539 --- /dev/null +++ b/nodejs/node_modules/.bin/errno @@ -0,0 +1 @@ +../errno/cli.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/node-gyp-build b/nodejs/node_modules/.bin/node-gyp-build new file mode 120000 index 00000000..671c6ebc --- /dev/null +++ b/nodejs/node_modules/.bin/node-gyp-build @@ -0,0 +1 @@ +../node-gyp-build/bin.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/node-gyp-build-optional b/nodejs/node_modules/.bin/node-gyp-build-optional new file mode 120000 index 00000000..46d347e6 --- /dev/null +++ b/nodejs/node_modules/.bin/node-gyp-build-optional @@ -0,0 +1 @@ +../node-gyp-build/optional.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/node-gyp-build-test b/nodejs/node_modules/.bin/node-gyp-build-test new file mode 120000 index 00000000..d11de1be --- /dev/null +++ b/nodejs/node_modules/.bin/node-gyp-build-test @@ -0,0 +1 @@ +../node-gyp-build/build-test.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/y-websocket b/nodejs/node_modules/.bin/y-websocket new file mode 120000 index 00000000..2f267184 --- /dev/null +++ b/nodejs/node_modules/.bin/y-websocket @@ -0,0 +1 @@ +../y-websocket/bin/server.js \ No newline at end of file diff --git a/nodejs/node_modules/.bin/y-websocket-server b/nodejs/node_modules/.bin/y-websocket-server new file mode 120000 index 00000000..2f267184 --- /dev/null +++ b/nodejs/node_modules/.bin/y-websocket-server @@ -0,0 +1 @@ +../y-websocket/bin/server.js \ No newline at end of file diff --git a/nodejs/node_modules/.package-lock.json b/nodejs/node_modules/.package-lock.json new file mode 100644 index 00000000..982d9c9c --- /dev/null +++ b/nodejs/node_modules/.package-lock.json @@ -0,0 +1,866 @@ +{ + "name": "nodejs", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@colors/colors": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", + "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/@dabh/diagnostics": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz", + "integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==", + "dependencies": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + } + }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.5.tgz", + "integrity": "sha512-XLNOMH66KhJzUJNwT/qlMnS4WsNDWD5ASdyaSH3EtK+F4r/CFGa3jT4GNi4mfOitGvWXtdLgQJkQjxSVrio+jA==", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, + "node_modules/@types/triple-beam": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", + "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==" + }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.4", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.4.tgz", + "integrity": "sha512-lXCmTWSHJvf0TRSO58nm978b8HJ/EdsSsEKLd3ODHFjo+3VGAyyTp4v50nWvwtzBxSMQrVOK7tcuN0zGPLICMw==", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, + "node_modules/abstract-leveldown": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/abstract-leveldown/-/abstract-leveldown-6.2.3.tgz", + "integrity": "sha512-BsLm5vFMRUrrLeCcRc+G0t2qOaTzpoJQLOubq2XM72eNpjF5UdU5o/5NvlNhx95XHcAvcl8OMXr4mlg/fRgUXQ==", + "optional": true, + "dependencies": { + "buffer": "^5.5.0", + "immediate": "^3.2.3", + "level-concat-iterator": "~2.0.0", + "level-supports": "~1.0.0", + "xtend": "~4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/async": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==" + }, + "node_modules/async-limiter": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz", + "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==", + "optional": true + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "optional": true + }, + "node_modules/bson": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.5.0.tgz", + "integrity": "sha512-DXf1BTAS8vKyR90BO4x5v3rKVarmkdkzwOrnYDFdjAY694ILNDkmA3uRh1xXJEl+C1DAh8XCvAQ+Gh3kzubtpg==", + "engines": { + "node": ">=16.20.1" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "optional": true, + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/color": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz", + "integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==", + "dependencies": { + "color-convert": "^1.9.3", + "color-string": "^1.6.0" + } + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/colorspace": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz", + "integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==", + "dependencies": { + "color": "^3.1.3", + "text-hex": "1.0.x" + } + }, + "node_modules/console": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/console/-/console-0.7.2.tgz", + "integrity": "sha512-+JSDwGunA4MTEgAV/4VBKwUHonP8CzJ/6GIuwPi6acKFqFfHUdSGCm89ZxZ5FfGWdZfkdgAroy5bJ5FSeN/t4g==" + }, + "node_modules/deferred-leveldown": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/deferred-leveldown/-/deferred-leveldown-5.3.0.tgz", + "integrity": "sha512-a59VOT+oDy7vtAbLRCZwWgxu2BaCfd5Hk7wxJd48ei7I+nsg8Orlb9CLG0PMZienk9BSUKgeAqkO2+Lw+1+Ukw==", + "optional": true, + "dependencies": { + "abstract-leveldown": "~6.2.1", + "inherits": "^2.0.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/enabled": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" + }, + "node_modules/encoding-down": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/encoding-down/-/encoding-down-6.3.0.tgz", + "integrity": "sha512-QKrV0iKR6MZVJV08QY0wp1e7vF6QbhnbQhb07bwpEyuz4uZiZgPlEGdkCROuFkUwdxlFaiPIhjyarH1ee/3vhw==", + "optional": true, + "dependencies": { + "abstract-leveldown": "^6.2.1", + "inherits": "^2.0.3", + "level-codec": "^9.0.0", + "level-errors": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/errno": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", + "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", + "optional": true, + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "node_modules/fecha": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", + "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==" + }, + "node_modules/fn.name": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==" + }, + "node_modules/http": { + "version": "0.0.1-security", + "resolved": "https://registry.npmjs.org/http/-/http-0.0.1-security.tgz", + "integrity": "sha512-RnDvP10Ty9FxqOtPZuxtebw1j4L/WiqNMDtuc1YMH1XQm5TgDRaR1G9u8upL6KD1bXHSp9eSXo/ED+8Q7FAr+g==" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "optional": true + }, + "node_modules/immediate": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.3.0.tgz", + "integrity": "sha512-HR7EVodfFUdQCTIeySw+WDRFJlPcLOJbXfwwZ7Oom6tjsvZ3bOkCDJHehQC3nxJrv7+f9XecwazynjU8e4Vw3Q==", + "optional": true + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/kuler": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==" + }, + "node_modules/level": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/level/-/level-6.0.1.tgz", + "integrity": "sha512-psRSqJZCsC/irNhfHzrVZbmPYXDcEYhA5TVNwr+V92jF44rbf86hqGp8fiT702FyiArScYIlPSBTDUASCVNSpw==", + "optional": true, + "dependencies": { + "level-js": "^5.0.0", + "level-packager": "^5.1.0", + "leveldown": "^5.4.0" + }, + "engines": { + "node": ">=8.6.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/level" + } + }, + "node_modules/level-codec": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/level-codec/-/level-codec-9.0.2.tgz", + "integrity": "sha512-UyIwNb1lJBChJnGfjmO0OR+ezh2iVu1Kas3nvBS/BzGnx79dv6g7unpKIDNPMhfdTEGoc7mC8uAu51XEtX+FHQ==", + "optional": true, + "dependencies": { + "buffer": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/level-concat-iterator": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/level-concat-iterator/-/level-concat-iterator-2.0.1.tgz", + "integrity": "sha512-OTKKOqeav2QWcERMJR7IS9CUo1sHnke2C0gkSmcR7QuEtFNLLzHQAvnMw8ykvEcv0Qtkg0p7FOwP1v9e5Smdcw==", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/level-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/level-errors/-/level-errors-2.0.1.tgz", + "integrity": "sha512-UVprBJXite4gPS+3VznfgDSU8PTRuVX0NXwoWW50KLxd2yw4Y1t2JUR5In1itQnudZqRMT9DlAM3Q//9NCjCFw==", + "optional": true, + "dependencies": { + "errno": "~0.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/level-iterator-stream": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/level-iterator-stream/-/level-iterator-stream-4.0.2.tgz", + "integrity": "sha512-ZSthfEqzGSOMWoUGhTXdX9jv26d32XJuHz/5YnuHZzH6wldfWMOVwI9TBtKcya4BKTyTt3XVA0A3cF3q5CY30Q==", + "optional": true, + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "^3.4.0", + "xtend": "^4.0.2" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/level-js": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/level-js/-/level-js-5.0.2.tgz", + "integrity": "sha512-SnBIDo2pdO5VXh02ZmtAyPP6/+6YTJg2ibLtl9C34pWvmtMEmRTWpra+qO/hifkUtBTOtfx6S9vLDjBsBK4gRg==", + "optional": true, + "dependencies": { + "abstract-leveldown": "~6.2.3", + "buffer": "^5.5.0", + "inherits": "^2.0.3", + "ltgt": "^2.1.2" + } + }, + "node_modules/level-packager": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/level-packager/-/level-packager-5.1.1.tgz", + "integrity": "sha512-HMwMaQPlTC1IlcwT3+swhqf/NUO+ZhXVz6TY1zZIIZlIR0YSn8GtAAWmIvKjNY16ZkEg/JcpAuQskxsXqC0yOQ==", + "optional": true, + "dependencies": { + "encoding-down": "^6.3.0", + "levelup": "^4.3.2" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/level-supports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/level-supports/-/level-supports-1.0.1.tgz", + "integrity": "sha512-rXM7GYnW8gsl1vedTJIbzOrRv85c/2uCMpiiCzO2fndd06U/kUXEEU9evYn4zFggBOg36IsBW8LzqIpETwwQzg==", + "optional": true, + "dependencies": { + "xtend": "^4.0.2" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/leveldown": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/leveldown/-/leveldown-5.6.0.tgz", + "integrity": "sha512-iB8O/7Db9lPaITU1aA2txU/cBEXAt4vWwKQRrrWuS6XDgbP4QZGj9BL2aNbwb002atoQ/lIotJkfyzz+ygQnUQ==", + "hasInstallScript": true, + "optional": true, + "dependencies": { + "abstract-leveldown": "~6.2.1", + "napi-macros": "~2.0.0", + "node-gyp-build": "~4.1.0" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/levelup": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/levelup/-/levelup-4.4.0.tgz", + "integrity": "sha512-94++VFO3qN95cM/d6eBXvd894oJE0w3cInq9USsyQzzoJxmiYzPAocNcuGCPGGjoXqDVJcr3C1jzt1TSjyaiLQ==", + "optional": true, + "dependencies": { + "deferred-leveldown": "~5.3.0", + "level-errors": "~2.0.0", + "level-iterator-stream": "~4.0.0", + "level-supports": "~1.0.0", + "xtend": "~4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lib0": { + "version": "0.2.93", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.93.tgz", + "integrity": "sha512-M5IKsiFJYulS+8Eal8f+zAqf5ckm1vffW0fFDxfgxJ+uiVopvDdd3PxJmz0GsVi3YNO7QCFSq0nAsiDmNhLj9Q==", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==" + }, + "node_modules/logform": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/logform/-/logform-2.6.0.tgz", + "integrity": "sha512-1ulHeNPp6k/LD8H91o7VYFBng5i1BDE7HoKxVbZiGFidS1Rj65qcywLxX+pVfAPoQJEjRdvKcusKwOupHCVOVQ==", + "dependencies": { + "@colors/colors": "1.6.0", + "@types/triple-beam": "^1.3.2", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "safe-stable-stringify": "^2.3.1", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/ltgt": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ltgt/-/ltgt-2.2.1.tgz", + "integrity": "sha512-AI2r85+4MquTw9ZYqabu4nMwy9Oftlfa/e/52t9IjtfG+mGBbTNdAoZ3RQKLHR6r0wQnwZnPIEh/Ya6XTWAKNA==", + "optional": true + }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, + "node_modules/mongodb": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.5.0.tgz", + "integrity": "sha512-Fozq68InT+JKABGLqctgtb8P56pRrJFkbhW0ux+x1mdHeyinor8oNzJqwLjV/t5X5nJGfTlluxfyMnOXNggIUA==", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.4.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.0.tgz", + "integrity": "sha512-t1Vf+m1I5hC2M5RJx/7AtxgABy1cZmIPQRMXw+gEIPn/cZNF3Oiy+l0UIypUwVB5trcWHq3crg2g3uAR9aAwsQ==", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/napi-macros": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-macros/-/napi-macros-2.0.0.tgz", + "integrity": "sha512-A0xLykHtARfueITVDernsAWdtIMbOJgKgcluwENp3AlsKN/PloyO10HtmoqnFAQAcxPkgZN7wdfPfEd0zNGxbg==", + "optional": true + }, + "node_modules/node-gyp-build": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.1.1.tgz", + "integrity": "sha512-dSq1xmcPDKPZ2EED2S6zw/b9NKsqzXRE6dVr8TVQnI3FJOTteUMuqF3Qqs6LZg+mLGYJWqQzMbIjMtJqTv87nQ==", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/one-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "dependencies": { + "fn.name": "1.x.x" + } + }, + "node_modules/prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==", + "optional": true + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safe-stable-stringify": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.4.3.tgz", + "integrity": "sha512-e2bDA2WJT0wxseVd4lsDP4+3ONX6HpMXQa1ZhFQ7SU+GjvORCmShbCMltrtIDfkYhVHrOcPtj+KhmDBdPdZD1g==", + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, + "node_modules/stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==", + "engines": { + "node": "*" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/text-hex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==" + }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/triple-beam": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz", + "integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==", + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/winston": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.12.0.tgz", + "integrity": "sha512-OwbxKaOlESDi01mC9rkM0dQqQt2I8DAUMRLZ/HpbwvDXm85IryEHgoogy5fziQy38PntgZsLlhAYHz//UPHZ5w==", + "dependencies": { + "@colors/colors": "^1.6.0", + "@dabh/diagnostics": "^2.0.2", + "async": "^3.2.3", + "is-stream": "^2.0.0", + "logform": "^2.4.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.7.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.7.0.tgz", + "integrity": "sha512-ajBj65K5I7denzer2IYW6+2bNIVqLGDHqDw3Ow8Ohh+vdW+rv4MZ6eiDvHoKhfJFZ2auyN8byXieDDJ96ViONg==", + "dependencies": { + "logform": "^2.3.2", + "readable-stream": "^3.6.0", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/ws": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", + "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "optional": true, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y-leveldb": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/y-leveldb/-/y-leveldb-0.1.2.tgz", + "integrity": "sha512-6ulEn5AXfXJYi89rXPEg2mMHAyyw8+ZfeMMdOtBbV8FJpQ1NOrcgi6DTAcXof0dap84NjHPT2+9d0rb6cFsjEg==", + "optional": true, + "dependencies": { + "level": "^6.0.1", + "lib0": "^0.2.31" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/y-mongodb-provider": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/y-mongodb-provider/-/y-mongodb-provider-0.1.9.tgz", + "integrity": "sha512-WjBptwkkoK4jHqWveaqY6+enMxWMnWxKcbEOZVamf5aTarSBWHPPXk7ZnWYyONuyGtUqedqjZtyjWUAhW1YhLQ==", + "dependencies": { + "lib0": "^0.2.85", + "mongodb": "^6.1.0" + }, + "peerDependencies": { + "yjs": "^13.6.8" + } + }, + "node_modules/y-protocols": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.6.tgz", + "integrity": "sha512-vHRF2L6iT3rwj1jub/K5tYcTT/mEYDUppgNPXwp8fmLpui9f7Yeq3OEtTLVF012j39QnV+KEQpNqoN7CWU7Y9Q==", + "dependencies": { + "lib0": "^0.2.85" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/y-websocket": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/y-websocket/-/y-websocket-1.5.4.tgz", + "integrity": "sha512-Y3021uy0anOIHqAPyAZbNDoR05JuMEGjRNI8c+K9MHzVS8dWoImdJUjccljAznc8H2L7WkIXhRHZ1igWNRSgPw==", + "dependencies": { + "lib0": "^0.2.52", + "lodash.debounce": "^4.0.8", + "y-protocols": "^1.0.5" + }, + "bin": { + "y-websocket": "bin/server.js", + "y-websocket-server": "bin/server.js" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "optionalDependencies": { + "ws": "^6.2.1", + "y-leveldb": "^0.1.0" + }, + "peerDependencies": { + "yjs": "^13.5.6" + } + }, + "node_modules/y-websocket/node_modules/ws": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.2.tgz", + "integrity": "sha512-zmhltoSR8u1cnDsD43TX59mzoMZsLKqUweyYBAIvTngR3shc0W6aOZylZmq/7hqyVxPdi+5Ud2QInblgyE72fw==", + "optional": true, + "dependencies": { + "async-limiter": "~1.0.0" + } + }, + "node_modules/yjs": { + "version": "13.6.14", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.14.tgz", + "integrity": "sha512-D+7KcUr0j+vBCUSKXXEWfA+bG4UQBviAwP3gYBhkstkgwy5+8diOPMx0iqLIOxNo/HxaREUimZRxqHGAHCL2BQ==", + "dependencies": { + "lib0": "^0.2.86" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + } + } +} diff --git a/nodejs/node_modules/@colors/colors/LICENSE b/nodejs/node_modules/@colors/colors/LICENSE new file mode 100644 index 00000000..6b860561 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/LICENSE @@ -0,0 +1,26 @@ +MIT License + +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + - Copyright (c) DABH (https://github.com/DABH) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/@colors/colors/README.md b/nodejs/node_modules/@colors/colors/README.md new file mode 100644 index 00000000..e2479ce5 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/README.md @@ -0,0 +1,219 @@ +# @colors/colors ("colors.js") +[![Build Status](https://github.com/DABH/colors.js/actions/workflows/ci.yml/badge.svg)](https://github.com/DABH/colors.js/actions/workflows/ci.yml) +[![version](https://img.shields.io/npm/v/@colors/colors.svg)](https://www.npmjs.org/package/@colors/colors) + +Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback. + +## get color and style in your node.js console + +![Demo](https://raw.githubusercontent.com/DABH/colors.js/master/screenshots/colors.png) + +## Installation + + npm install @colors/colors + +## colors and styles! + +### text colors + + - black + - red + - green + - yellow + - blue + - magenta + - cyan + - white + - gray + - grey + +### bright text colors + + - brightRed + - brightGreen + - brightYellow + - brightBlue + - brightMagenta + - brightCyan + - brightWhite + +### background colors + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + - bgGray + - bgGrey + +### bright background colors + + - bgBrightRed + - bgBrightGreen + - bgBrightYellow + - bgBrightBlue + - bgBrightMagenta + - bgBrightCyan + - bgBrightWhite + +### styles + + - reset + - bold + - dim + - italic + - underline + - inverse + - hidden + - strikethrough + +### extras + + - rainbow + - zebra + - america + - trap + - random + + +## Usage + +By popular demand, `@colors/colors` now ships with two types of usages! + +The super nifty way + +```js +var colors = require('@colors/colors'); + +console.log('hello'.green); // outputs green text +console.log('i like cake and pies'.underline.red); // outputs red underlined text +console.log('inverse the color'.inverse); // inverses the color +console.log('OMG Rainbows!'.rainbow); // rainbow +console.log('Run the trap'.trap); // Drops the bass + +``` + +or a slightly less nifty way which doesn't extend `String.prototype` + +```js +var colors = require('@colors/colors/safe'); + +console.log(colors.green('hello')); // outputs green text +console.log(colors.red.underline('i like cake and pies')); // outputs red underlined text +console.log(colors.inverse('inverse the color')); // inverses the color +console.log(colors.rainbow('OMG Rainbows!')); // rainbow +console.log(colors.trap('Run the trap')); // Drops the bass + +``` + +I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way. + +If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object. + +## Enabling/Disabling Colors + +The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag: + +```bash +node myapp.js --no-color +node myapp.js --color=false + +node myapp.js --color +node myapp.js --color=true +node myapp.js --color=always + +FORCE_COLOR=1 node myapp.js +``` + +Or in code: + +```javascript +var colors = require('@colors/colors'); +colors.enable(); +colors.disable(); +``` + +## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data) + +```js +var name = 'Beowulf'; +console.log(colors.green('Hello %s'), name); +// outputs -> 'Hello Beowulf' +``` + +## Custom themes + +### Using standard API + +```js + +var colors = require('@colors/colors'); + +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); +``` + +### Using string safe API + +```js +var colors = require('@colors/colors/safe'); + +// set single property +var error = colors.red; +error('this is red'); + +// set theme +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +``` + +### Combining Colors + +```javascript +var colors = require('@colors/colors'); + +colors.setTheme({ + custom: ['red', 'underline'] +}); + +console.log('test'.custom); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.* diff --git a/nodejs/node_modules/@colors/colors/examples/normal-usage.js b/nodejs/node_modules/@colors/colors/examples/normal-usage.js new file mode 100644 index 00000000..a4bfe7b7 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/examples/normal-usage.js @@ -0,0 +1,83 @@ +var colors = require('../lib/index'); + +console.log('First some yellow text'.yellow); + +console.log('Underline that text'.yellow.underline); + +console.log('Make it bold and red'.red.bold); + +console.log(('Double Raindows All Day Long').rainbow); + +console.log('Drop the bass'.trap); + +console.log('DROP THE RAINBOW BASS'.trap.rainbow); + +// styles not widely supported +console.log('Chains are also cool.'.bold.italic.underline.red); + +// styles not widely supported +console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + + ' styles! '.yellow.bold); +console.log('Zebras are so fun!'.zebra); + +// +// Remark: .strikethrough may not work with Mac OS Terminal App +// +console.log('This is ' + 'not'.strikethrough + ' fun.'); + +console.log('Background color attack!'.black.bgWhite); +console.log('Use random styles on everything!'.random); +console.log('America, Heck Yeah!'.america); + +// eslint-disable-next-line max-len +console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen); + +console.log('Setting themes is useful'); + +// +// Custom themes +// +console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}); + +// outputs red text +console.log('this is an error'.error); + +// outputs yellow text +console.log('this is a warning'.warn); + +// outputs grey text +console.log('this is an input'.input); + +console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +try { + colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); +} catch (err) { + console.log(err); +} + +// outputs red text +console.log('this is an error'.error); + +// outputs yellow text +console.log('this is a warning'.warn); + +// outputs grey text +console.log('this is an input'.input); + +// console.log("Don't summon".zalgo) + diff --git a/nodejs/node_modules/@colors/colors/examples/safe-string.js b/nodejs/node_modules/@colors/colors/examples/safe-string.js new file mode 100644 index 00000000..fc664745 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/examples/safe-string.js @@ -0,0 +1,80 @@ +var colors = require('../safe'); + +console.log(colors.yellow('First some yellow text')); + +console.log(colors.yellow.underline('Underline that text')); + +console.log(colors.red.bold('Make it bold and red')); + +console.log(colors.rainbow('Double Raindows All Day Long')); + +console.log(colors.trap('Drop the bass')); + +console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS'))); + +// styles not widely supported +console.log(colors.bold.italic.underline.red('Chains are also cool.')); + +// styles not widely supported +console.log(colors.green('So ') + colors.underline('are') + ' ' + + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); + +console.log(colors.zebra('Zebras are so fun!')); + +console.log('This is ' + colors.strikethrough('not') + ' fun.'); + + +console.log(colors.black.bgWhite('Background color attack!')); +console.log(colors.random('Use random styles on everything!')); +console.log(colors.america('America, Heck Yeah!')); + +// eslint-disable-next-line max-len +console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!')); + +console.log('Setting themes is useful'); + +// +// Custom themes +// +// console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'blue', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}); + +// outputs red text +console.log(colors.error('this is an error')); + +// outputs yellow text +console.log(colors.warn('this is a warning')); + +// outputs blue text +console.log(colors.input('this is an input')); + + +// console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); + +// outputs red text +console.log(colors.error('this is an error')); + +// outputs yellow text +console.log(colors.warn('this is a warning')); + +// outputs grey text +console.log(colors.input('this is an input')); + +// console.log(colors.zalgo("Don't summon him")) + + diff --git a/nodejs/node_modules/@colors/colors/index.d.ts b/nodejs/node_modules/@colors/colors/index.d.ts new file mode 100644 index 00000000..7a7a3203 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/index.d.ts @@ -0,0 +1,184 @@ +// Type definitions for @colors/colors 1.4+ +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor , Staffan Eketorp +// Definitions: https://github.com/DABH/colors.js + +export interface Color { + (text: string): string; + + strip: Color; + stripColors: Color; + + black: Color; + red: Color; + green: Color; + yellow: Color; + blue: Color; + magenta: Color; + cyan: Color; + white: Color; + gray: Color; + grey: Color; + + brightRed: Color; + brightGreen: Color; + brightYellow: Color; + brightBlue: Color; + brightMagenta: Color; + brightCyan: Color; + brightWhite: Color; + + bgBlack: Color; + bgRed: Color; + bgGreen: Color; + bgYellow: Color; + bgBlue: Color; + bgMagenta: Color; + bgCyan: Color; + bgWhite: Color; + + bgBrightRed: Color; + bgBrightGreen: Color; + bgBrightYellow: Color; + bgBrightBlue: Color; + bgBrightMagenta: Color; + bgBrightCyan: Color; + bgBrightWhite: Color; + + reset: Color; + bold: Color; + dim: Color; + italic: Color; + underline: Color; + inverse: Color; + hidden: Color; + strikethrough: Color; + + rainbow: Color; + zebra: Color; + america: Color; + trap: Color; + random: Color; + zalgo: Color; +} + +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export let enabled: boolean; + +export const strip: Color; +export const stripColors: Color; + +export const black: Color; +export const red: Color; +export const green: Color; +export const yellow: Color; +export const blue: Color; +export const magenta: Color; +export const cyan: Color; +export const white: Color; +export const gray: Color; +export const grey: Color; + +export const brightRed: Color; +export const brightGreen: Color; +export const brightYellow: Color; +export const brightBlue: Color; +export const brightMagenta: Color; +export const brightCyan: Color; +export const brightWhite: Color; + +export const bgBlack: Color; +export const bgRed: Color; +export const bgGreen: Color; +export const bgYellow: Color; +export const bgBlue: Color; +export const bgMagenta: Color; +export const bgCyan: Color; +export const bgWhite: Color; + +export const bgBrightRed: Color; +export const bgBrightGreen: Color; +export const bgBrightYellow: Color; +export const bgBrightBlue: Color; +export const bgBrightMagenta: Color; +export const bgBrightCyan: Color; +export const bgBrightWhite: Color; + +export const reset: Color; +export const bold: Color; +export const dim: Color; +export const italic: Color; +export const underline: Color; +export const inverse: Color; +export const hidden: Color; +export const strikethrough: Color; + +export const rainbow: Color; +export const zebra: Color; +export const america: Color; +export const trap: Color; +export const random: Color; +export const zalgo: Color; + +declare global { + interface String { + strip: string; + stripColors: string; + + black: string; + red: string; + green: string; + yellow: string; + blue: string; + magenta: string; + cyan: string; + white: string; + gray: string; + grey: string; + + brightRed: string; + brightGreen: string; + brightYellow: string; + brightBlue: string; + brightMagenta: string; + brightCyan: string; + brightWhite: string; + + bgBlack: string; + bgRed: string; + bgGreen: string; + bgYellow: string; + bgBlue: string; + bgMagenta: string; + bgCyan: string; + bgWhite: string; + + bgBrightRed: string; + bgBrightGreen: string; + bgBrightYellow: string; + bgBrightBlue: string; + bgBrightMagenta: string; + bgBrightCyan: string; + bgBrightWhite: string; + + reset: string; + // @ts-ignore + bold: string; + dim: string; + italic: string; + underline: string; + inverse: string; + hidden: string; + strikethrough: string; + + rainbow: string; + zebra: string; + america: string; + trap: string; + random: string; + zalgo: string; + } +} diff --git a/nodejs/node_modules/@colors/colors/lib/colors.js b/nodejs/node_modules/@colors/colors/lib/colors.js new file mode 100644 index 00000000..d9fb0876 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/colors.js @@ -0,0 +1,211 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var util = require('util'); +var ansiStyles = colors.styles = require('./styles'); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); + +colors.supportsColor = require('./system/supports-colors').supportsColor; + +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} + +colors.enable = function() { + colors.enabled = true; +}; + +colors.disable = function() { + colors.enabled = false; +}; + +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; + +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } + + var styleMap = ansiStyles[style]; + + // Stylize should work for non-ANSI styles, too + if (!styleMap && style in colors) { + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } + + return styleMap.open + str + styleMap.close; +}; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = + new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + }, + }; + }); + return ret; +})(); + +var proto = defineProps(function colors() {}, styles); + +function applyStyle() { + var args = Array.prototype.slice.call(arguments); + + var str = args.map(function(arg) { + // Use weak equality check so we can colorize null/undefined in safe mode + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util.inspect(arg); + } + }).join(' '); + + if (!colors.enabled || !str) { + return str; + } + + var newLinesPresent = str.indexOf('\n') != -1; + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); + } + } + + return str; +} + +colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + for (var style in theme) { + (function(style) { + colors[style] = function(str) { + if (typeof theme[style] === 'object') { + var out = str; + for (var i in theme[style]) { + out = colors[theme[style][i]](out); + } + return out; + } + return colors[theme[style]](str); + }; + })(style); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + }, + }; + }); + return ret; +} + +var sequencer = function sequencer(map, str) { + var exploded = str.split(''); + exploded = exploded.map(map); + return exploded.join(''); +}; + +// custom formatter methods +colors.trap = require('./custom/trap'); +colors.zalgo = require('./custom/zalgo'); + +// maps +colors.maps = {}; +colors.maps.america = require('./maps/america')(colors); +colors.maps.zebra = require('./maps/zebra')(colors); +colors.maps.rainbow = require('./maps/rainbow')(colors); +colors.maps.random = require('./maps/random')(colors); + +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} + +defineProps(colors, init()); diff --git a/nodejs/node_modules/@colors/colors/lib/custom/trap.js b/nodejs/node_modules/@colors/colors/lib/custom/trap.js new file mode 100644 index 00000000..fbccf88d --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/custom/trap.js @@ -0,0 +1,46 @@ +module['exports'] = function runTheTrap(text, options) { + var result = ''; + text = text || 'Run the trap, drop the bass'; + text = text.split(''); + var trap = { + a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], + b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], + c: ['\u00a9', '\u023b', '\u03fe'], + d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], + e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', + '\u0a6c'], + f: ['\u04fa'], + g: ['\u0262'], + h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], + i: ['\u0f0f'], + j: ['\u0134'], + k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], + l: ['\u0139'], + m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], + n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], + o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', + '\u06dd', '\u0e4f'], + p: ['\u01f7', '\u048e'], + q: ['\u09cd'], + r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], + s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], + t: ['\u0141', '\u0166', '\u0373'], + u: ['\u01b1', '\u054d'], + v: ['\u05d8'], + w: ['\u0428', '\u0460', '\u047c', '\u0d70'], + x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], + y: ['\u00a5', '\u04b0', '\u04cb'], + z: ['\u01b5', '\u0240'], + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [' ']; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== 'undefined') { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; +}; diff --git a/nodejs/node_modules/@colors/colors/lib/custom/zalgo.js b/nodejs/node_modules/@colors/colors/lib/custom/zalgo.js new file mode 100644 index 00000000..0ef2b011 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/custom/zalgo.js @@ -0,0 +1,110 @@ +// please no +module['exports'] = function zalgo(text, options) { + text = text || ' he is here '; + var soul = { + 'up': [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚', + ], + 'down': [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣', + ], + 'mid': [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉', + ], + }; + var all = [].concat(soul.up, soul.down, soul.mid); + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = ''; + var counts; + var l; + options = options || {}; + options['up'] = + typeof options['up'] !== 'undefined' ? options['up'] : true; + options['mid'] = + typeof options['mid'] !== 'undefined' ? options['mid'] : true; + options['down'] = + typeof options['down'] !== 'undefined' ? options['down'] : true; + options['size'] = + typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; + text = text.split(''); + for (l in text) { + if (isChar(l)) { + continue; + } + result = result + text[l]; + counts = {'up': 0, 'down': 0, 'mid': 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + var arr = ['up', 'mid', 'down']; + for (var d in arr) { + var index = arr[d]; + for (var i = 0; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text, options); +}; + diff --git a/nodejs/node_modules/@colors/colors/lib/extendStringPrototype.js b/nodejs/node_modules/@colors/colors/lib/extendStringPrototype.js new file mode 100644 index 00000000..46fd386a --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/extendStringPrototype.js @@ -0,0 +1,110 @@ +var colors = require('./colors'); + +module['exports'] = function() { + // + // Extends prototype of native string object to allow for "foo".red syntax + // + var addProperty = function(color, func) { + String.prototype.__defineGetter__(color, func); + }; + + addProperty('strip', function() { + return colors.strip(this); + }); + + addProperty('stripColors', function() { + return colors.strip(this); + }); + + addProperty('trap', function() { + return colors.trap(this); + }); + + addProperty('zalgo', function() { + return colors.zalgo(this); + }); + + addProperty('zebra', function() { + return colors.zebra(this); + }); + + addProperty('rainbow', function() { + return colors.rainbow(this); + }); + + addProperty('random', function() { + return colors.random(this); + }); + + addProperty('america', function() { + return colors.america(this); + }); + + // + // Iterate through all default styles and colors + // + var x = Object.keys(colors.styles); + x.forEach(function(style) { + addProperty(style, function() { + return colors.stylize(this, style); + }); + }); + + function applyTheme(theme) { + // + // Remark: This is a list of methods that exist + // on String that you should not overwrite. + // + var stringPrototypeBlacklist = [ + '__defineGetter__', '__defineSetter__', '__lookupGetter__', + '__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty', + 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', + 'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length', + 'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice', + 'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase', + 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight', + ]; + + Object.keys(theme).forEach(function(prop) { + if (stringPrototypeBlacklist.indexOf(prop) !== -1) { + console.log('warn: '.red + ('String.prototype' + prop).magenta + + ' is probably something you don\'t want to override. ' + + 'Ignoring style name'); + } else { + if (typeof(theme[prop]) === 'string') { + colors[prop] = colors[theme[prop]]; + addProperty(prop, function() { + return colors[prop](this); + }); + } else { + var themePropApplicator = function(str) { + var ret = str || this; + for (var t = 0; t < theme[prop].length; t++) { + ret = colors[theme[prop][t]](ret); + } + return ret; + }; + addProperty(prop, themePropApplicator); + colors[prop] = function(str) { + return themePropApplicator(str); + }; + } + } + }); + } + + colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } else { + applyTheme(theme); + } + }; +}; diff --git a/nodejs/node_modules/@colors/colors/lib/index.js b/nodejs/node_modules/@colors/colors/lib/index.js new file mode 100644 index 00000000..8cdc29fd --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/index.js @@ -0,0 +1,13 @@ +var colors = require('./colors'); +module['exports'] = colors; + +// Remark: By default, colors will add style properties to String.prototype. +// +// If you don't wish to extend String.prototype, you can do this instead and +// native String will not be touched: +// +// var colors = require('@colors/colors/safe'); +// colors.red("foo") +// +// +require('./extendStringPrototype')(); diff --git a/nodejs/node_modules/@colors/colors/lib/maps/america.js b/nodejs/node_modules/@colors/colors/lib/maps/america.js new file mode 100644 index 00000000..dc969033 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/maps/america.js @@ -0,0 +1,10 @@ +module['exports'] = function(colors) { + return function(letter, i, exploded) { + if (letter === ' ') return letter; + switch (i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter); + case 2: return colors.blue(letter); + } + }; +}; diff --git a/nodejs/node_modules/@colors/colors/lib/maps/rainbow.js b/nodejs/node_modules/@colors/colors/lib/maps/rainbow.js new file mode 100644 index 00000000..2b00ac0a --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/maps/rainbow.js @@ -0,0 +1,12 @@ +module['exports'] = function(colors) { + // RoY G BiV + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + return function(letter, i, exploded) { + if (letter === ' ') { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; +}; + diff --git a/nodejs/node_modules/@colors/colors/lib/maps/random.js b/nodejs/node_modules/@colors/colors/lib/maps/random.js new file mode 100644 index 00000000..3d82a39e --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/maps/random.js @@ -0,0 +1,11 @@ +module['exports'] = function(colors) { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; + return function(letter, i, exploded) { + return letter === ' ' ? letter : + colors[ + available[Math.round(Math.random() * (available.length - 2))] + ](letter); + }; +}; diff --git a/nodejs/node_modules/@colors/colors/lib/maps/zebra.js b/nodejs/node_modules/@colors/colors/lib/maps/zebra.js new file mode 100644 index 00000000..fa736235 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/maps/zebra.js @@ -0,0 +1,5 @@ +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; +}; diff --git a/nodejs/node_modules/@colors/colors/lib/styles.js b/nodejs/node_modules/@colors/colors/lib/styles.js new file mode 100644 index 00000000..011dafd8 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/styles.js @@ -0,0 +1,95 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var styles = {}; +module['exports'] = styles; + +var codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49], + +}; + +Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); diff --git a/nodejs/node_modules/@colors/colors/lib/system/has-flag.js b/nodejs/node_modules/@colors/colors/lib/system/has-flag.js new file mode 100644 index 00000000..85f176ad --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/system/has-flag.js @@ -0,0 +1,35 @@ +/* +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +'use strict'; + +module.exports = function(flag, argv) { + argv = argv || process.argv || []; + + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); + + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; diff --git a/nodejs/node_modules/@colors/colors/lib/system/supports-colors.js b/nodejs/node_modules/@colors/colors/lib/system/supports-colors.js new file mode 100644 index 00000000..f1f9c8ff --- /dev/null +++ b/nodejs/node_modules/@colors/colors/lib/system/supports-colors.js @@ -0,0 +1,151 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +'use strict'; + +var os = require('os'); +var hasFlag = require('./has-flag.js'); + +var env = process.env; + +var forceColor = void 0; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') + || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 + || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + var min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first + // Windows release that supports 256 colors. Windows 10 build 14931 is the + // first release that supports 16m/TrueColor. + var osRelease = os.release().split('.'); + if (Number(process.versions.node.split('.')[0]) >= 8 + && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } + + if ('TERM_PROGRAM' in env) { + var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), +}; diff --git a/nodejs/node_modules/@colors/colors/package.json b/nodejs/node_modules/@colors/colors/package.json new file mode 100644 index 00000000..01d5f9fb --- /dev/null +++ b/nodejs/node_modules/@colors/colors/package.json @@ -0,0 +1,45 @@ +{ + "name": "@colors/colors", + "description": "get colors in your node.js console", + "version": "1.6.0", + "author": "DABH", + "contributors": [ + { + "name": "DABH", + "url": "https://github.com/DABH" + } + ], + "homepage": "https://github.com/DABH/colors.js", + "bugs": "https://github.com/DABH/colors.js/issues", + "keywords": [ + "ansi", + "terminal", + "colors" + ], + "repository": { + "type": "git", + "url": "http://github.com/DABH/colors.js.git" + }, + "license": "MIT", + "scripts": { + "lint": "eslint . --fix", + "test": "export FORCE_COLOR=1 && node tests/basic-test.js && node tests/safe-test.js" + }, + "engines": { + "node": ">=0.1.90" + }, + "main": "lib/index.js", + "files": [ + "examples", + "lib", + "LICENSE", + "safe.js", + "themes", + "index.d.ts", + "safe.d.ts" + ], + "devDependencies": { + "eslint": "^8.9.0", + "eslint-config-google": "^0.14.0" + } +} diff --git a/nodejs/node_modules/@colors/colors/safe.d.ts b/nodejs/node_modules/@colors/colors/safe.d.ts new file mode 100644 index 00000000..69589153 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/safe.d.ts @@ -0,0 +1,64 @@ +// Type definitions for Colors.js 1.2 +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor , Staffan Eketorp +// Definitions: https://github.com/Marak/colors.js + +export const enabled: boolean; +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export function strip(str: string): string; +export function stripColors(str: string): string; + +export function black(str: string): string; +export function red(str: string): string; +export function green(str: string): string; +export function yellow(str: string): string; +export function blue(str: string): string; +export function magenta(str: string): string; +export function cyan(str: string): string; +export function white(str: string): string; +export function gray(str: string): string; +export function grey(str: string): string; + +export function brightRed(str: string): string; +export function brightGreen(str: string): string; +export function brightYellow(str: string): string; +export function brightBlue(str: string): string; +export function brightMagenta(str: string): string; +export function brightCyan(str: string): string; +export function brightWhite(str: string): string; + +export function bgBlack(str: string): string; +export function bgRed(str: string): string; +export function bgGreen(str: string): string; +export function bgYellow(str: string): string; +export function bgBlue(str: string): string; +export function bgMagenta(str: string): string; +export function bgCyan(str: string): string; +export function bgWhite(str: string): string; + +export function bgBrightRed(str: string): string; +export function bgBrightGreen(str: string): string; +export function bgBrightYellow(str: string): string; +export function bgBrightBlue(str: string): string; +export function bgBrightMagenta(str: string): string; +export function bgBrightCyan(str: string): string; +export function bgBrightWhite(str: string): string; + +export function reset(str: string): string; +export function bold(str: string): string; +export function dim(str: string): string; +export function italic(str: string): string; +export function underline(str: string): string; +export function inverse(str: string): string; +export function hidden(str: string): string; +export function strikethrough(str: string): string; + +export function rainbow(str: string): string; +export function zebra(str: string): string; +export function america(str: string): string; +export function trap(str: string): string; +export function random(str: string): string; +export function zalgo(str: string): string; diff --git a/nodejs/node_modules/@colors/colors/safe.js b/nodejs/node_modules/@colors/colors/safe.js new file mode 100644 index 00000000..a013d542 --- /dev/null +++ b/nodejs/node_modules/@colors/colors/safe.js @@ -0,0 +1,10 @@ +// +// Remark: Requiring this file will use the "safe" colors API, +// which will not touch String.prototype. +// +// var colors = require('colors/safe'); +// colors.red("foo") +// +// +var colors = require('./lib/colors'); +module['exports'] = colors; diff --git a/nodejs/node_modules/@colors/colors/themes/generic-logging.js b/nodejs/node_modules/@colors/colors/themes/generic-logging.js new file mode 100644 index 00000000..63adfe4a --- /dev/null +++ b/nodejs/node_modules/@colors/colors/themes/generic-logging.js @@ -0,0 +1,12 @@ +module['exports'] = { + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}; diff --git a/nodejs/node_modules/@dabh/diagnostics/CHANGELOG.md b/nodejs/node_modules/@dabh/diagnostics/CHANGELOG.md new file mode 100644 index 00000000..b04af38b --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/CHANGELOG.md @@ -0,0 +1,26 @@ +# CHANGELOG + +### 2.0.2 + +- Bump to kuler 2.0, which removes colornames as dependency, which we + never used. So smaller install size, less dependencies for all. + +### 2.0.1 + +- Use `storag-engine@3.0` which will automatically detect the correct + AsyncStorage implementation. +- The upgrade also fixes a bug where it the `debug` and `diagnostics` values + to be JSON encoded instead of regular plain text. + +### 2.0.0 + +- Documentation improvements. +- Fixed a issue where async adapters were incorrectly detected. +- Correctly inherit colors after applying colors the browser's console. + +### 2.0.0-alpha + +- Complete rewrite of all internals, now comes with separate builds for `browser` + `node` and `react-native` as well as dedicated builds for `production` and + `development` environments. Various utility methods and properties have + been added to the returned logger to make your lives even easier. diff --git a/nodejs/node_modules/@dabh/diagnostics/LICENSE b/nodejs/node_modules/@dabh/diagnostics/LICENSE new file mode 100644 index 00000000..9beaab11 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the Contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/@dabh/diagnostics/README.md b/nodejs/node_modules/@dabh/diagnostics/README.md new file mode 100644 index 00000000..0cd25195 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/README.md @@ -0,0 +1,473 @@ +# `diagnostics` + +Diagnostics in the evolution of debug pattern that is used in the Node.js core, +this extremely small but powerful technique can best be compared as feature +flags for loggers. The created debug logger is disabled by default but can be +enabled without changing a line of code, using flags. + +- Allows debugging in multiple JavaScript environments such as Node.js, browsers + and React-Native. +- Separated development and production builds to minimize impact on your + application when bundled. +- Allows for customization of logger, messages, and much more. + +![Output Example](example.png) + +## Installation + +The module is released in the public npm registry and can be installed by +running: + +``` +npm install --save @dabh/diagnostics +``` + +## Usage + +- [Introduction](#introduction) +- [Advanced usage](#advanced-usage) + - [Production and development builds](#production-and-development-builds) + - [WebPack](#webpack) + - [Node.js](#nodejs) +- [API](#api) + - [.enabled](#enabled) + - [.namespace](#namespace) + - [.dev/prod](#devprod) + - [set](#set) + - [modify](#modify) + - [use](#use) +- [Modifiers](#modifiers) + - [namespace](#namespace-1) +- [Adapters](#adapters) + - [process.env](#process-env) + - [hash](#hash) + - [localStorage](#localstorage) + - [AsyncStorage](#asyncstorage) +- [Loggers](#loggers) + +### Introduction + +To create a new logger simply `require` the `@dabh/diagnostics` module and call +the returned function. It accepts 2 arguments: + +1. `namespace` **Required** This is the namespace of your logger so we know if we need to + enable your logger when a debug flag is used. Generally you use the name of + your library or application as first root namespace. For example if you're + building a parser in a library (example) you would set namespace + `example:parser`. +2. `options` An object with additional configuration for the logger. + following keys are recognized: + - `force` Force the logger to be enabled. + - `colors` Colors are enabled by default for the logs, but you can set this + option to `false` to disable it. + +```js +const debug = require('@dabh/diagnostics')('foo:bar:baz'); +const debug = require('@dabh/diagnostics')('foo:bar:baz', { options }); + +debug('this is a log message %s', 'that will only show up when enabled'); +debug('that is pretty neat', { log: 'more', data: 1337 }); +``` + +Unlike `console.log` statements that add and remove during your development +lifecycle you create meaningful log statements that will give you insight in +the library or application that you're developing. + +The created debugger uses different "adapters" to extract the debug flag +out of the JavaScript environment. To learn more about enabling the debug flag +in your specific environment click on one of the enabled adapters below. + +- **browser**: [localStorage](#localstorage), [hash](#hash) +- **node.js**: [environment variables](#processenv) +- **react-native**: [AsyncStorage](#asyncstorage) + +Please note that the returned logger is fully configured out of the box, you +do not need to set any of the adapters/modifiers your self, they are there +for when you want more advanced control over the process. But if you want to +learn more about that, read the next section. + +### Advanced usage + +There are 2 specific usage patterns for `diagnostic`, library developers who +implement it as part of their modules and applications developers who either +use it in their application or are searching for ways to consume the messages. + +With the simple log interface as discussed in the [introduction](#introduction) +section we make it easy for developers to add it as part of their libraries +and applications, and with powerful [API](#api) we allow infinite customization +by allowing custom adapters, loggers and modifiers to ensure that this library +maintains relevant. These methods not only allow introduction of new loggers, +but allow you think outside the box. For example you can maintain a history +of past log messages, and output those when an uncaught exception happens in +your application so you have additional context + +```js +const diagnostics = require('@dabh/diagnostics'); + +let index = 0; +const limit = 200; +const history = new Array(limit); + +// +// Force all `diagnostic` loggers to be enabled. +// +diagnostics.force = process.env.NODE_ENV === 'prod'; +diagnostics.set(function customLogger(meta, message) { + history[index]= { meta, message, now: Date.now() }; + if (index++ === limit) index = 0; + + // + // We're running a development build, so output. + // + if (meta.dev) console.log.apply(console, message); +}); + +process.on('uncaughtException', async function (err) { + await saveErrorToDisk(err, history); + process.exit(1); +}); +``` + +The small snippet above will maintain a 200 limited FIFO (First In First Out) +queue of all debug messages that can be referenced when your application crashes + +#### Production and development builds + +When you `require` the `@dabh/diagnostics` module you will be given a logger that is +optimized for `development` so it can provide the best developer experience +possible. + +The development logger enables all the [adapters](#adapters) for your +JavaScript environment, adds a logger that outputs the messages to `console.log` +and registers our message modifiers so log messages will be prefixed with the +supplied namespace so you know where the log messages originates from. + +The development logger does not have any adapter, modifier and logger enabled +by default. This ensures that your log messages never accidentally show up in +production. However this does not mean that it's not possible to get debug +messages in production. You can `force` the debugger to be enabled, and +supply a [custom logger](#loggers). + +```js +const diagnostics = require('@dabh/diagnostics'); +const debug = debug('foo:bar', { force: true }); + +// +// Or enable _every_ diagnostic instance: +// +diagnostics.force = true; +``` + +##### WebPack + +WebPack has the concept of [mode](https://webpack.js.org/concepts/mode/#usage)'s +which creates different + +```js +module.exports = { + mode: 'development' // 'production' +} +``` + +When you are building your app using the WebPack CLI you can use the `--mode` +flag: + +``` +webpack --mode=production app.js -o /dist/bundle.js +``` + +##### Node.js + +When you are running your app using `Node.js` you should the `NODE_ENV` +environment variable to `production` to ensure that you libraries that you +import are optimized for production. + +``` +NODE_ENV=production node app.js +``` + +### API + +The returned logger exposes some addition properties that can be used used in +your application or library: + +#### .enabled + +The returned logger will have a `.enabled` property assigned to it. This boolean +can be used to check if the logger was enabled: + +```js +const debug = require('@dabh/diagnostics')('foo:bar'); + +if (debug.enabled) { + // + // Do something special + // +} +``` + +This property is exposed as: + +- Property on the logger. +- Property on the meta/options object. + +#### .namespace + +This is the namespace that you originally provided to the function. + +```js +const debug = require('@dabh/diagnostics')('foo:bar'); + +console.log(debug.namespace); // foo:bar +``` + +This property is exposed as: + +- Property on the logger. +- Property on the meta/options object. + +#### .dev/prod + +There are different builds available of `diagnostics`, when you create a +production build of your application using `NODE_ENV=production` you will be +given an optimized, smaller build of `diagnostics` to reduce your bundle size. +The `dev` and `prod` booleans on the returned logger indicate if you have a +production or development version of the logger. + +```js +const debug = require('@dabh/diagnostics')('foo:bar'); + +if (debug.prod) { + // do stuff +} +``` + +This property is exposed as: + +- Property on the logger. +- Property on the meta/options object. + +#### set + +Sets a new logger as default for **all** `diagnostic` instances. The passed +argument should be a function that write the log messages to where ever you +want. It receives 2 arguments: + +1. `meta` An object with all the options that was provided to the original + logger that wants to write the log message as well as properties of the + debugger such as `prod`, `dev`, `namespace`, `enabled`. See [API](#api) for + all exposed properties. +2. `args` An array of the log messages that needs to be written. + +```js +const debug = require('@dabh/diagnostics')('foo:more:namespaces'); + +debug.use(function logger(meta, args) { + console.log(meta); + console.debug(...args); +}); +``` + +This method is exposed as: + +- Method on the logger. +- Method on the meta/options object. +- Method on `diagnostics` module. + +#### modify + +The modify method allows you add a new message modifier to **all** `diagnostic` +instances. The passed argument should be a function that returns the passed +message after modification. The function receives 2 arguments: + +1. `message`, Array, the log message. +2. `options`, Object, the options that were passed into the logger when it was + initially created. + +```js +const debug = require('@dabh/diagnostics')('example:modifiers'); + +debug.modify(function (message, options) { + return messages; +}); +``` + +This method is exposed as: + +- Method on the logger. +- Method on the meta/options object. +- Method on `diagnostics` module. + +See [modifiers](#modifiers) for more information. + +#### use + +Adds a new `adapter` to **all** `diagnostic` instances. The passed argument +should be a function returns a boolean that indicates if the passed in +`namespace` is allowed to write log messages. + +```js +const diagnostics = require('@dabh/diagnostics'); +const debug = diagnostics('foo:bar'); + +debug.use(function (namespace) { + return namespace === 'foo:bar'; +}); +``` + +This method is exposed as: + +- Method on the logger. +- Method on the meta/options object. +- Method on `diagnostics` module. + +See [adapters](#adapters) for more information. + +### Modifiers + +To be as flexible as possible when it comes to transforming messages we've +come up with the concept of `modifiers` which can enhance the debug messages. +This allows you to introduce functionality or details that you find important +for debug messages, and doesn't require us to add additional bloat to the +`diagnostic` core. + +For example, you want the messages to be prefixed with the date-time of when +the log message occured: + +```js +const diagnostics = require('@dabh/diagnostics'); + +diagnostics.modify(function datetime(args, options) { + args.unshift(new Date()); + return args; +}); +``` + +Now all messages will be prefixed with date that is outputted by `new Date()`. +The following modifiers are shipped with `diagnostics` and are enabled in +**development** mode only: + +- [namespace](#namespace) + +#### namespace + +This modifier is enabled for all debug instances and prefixes the messages +with the name of namespace under which it is logged. The namespace is colored +using the `colorspace` module which groups similar namespaces under the same +colorspace. You can have multiple namespaces for the debuggers where each +namespace should be separated by a `:` + +``` +foo +foo:bar +foo:bar:baz +``` + +For console based output the `namespace-ansi` is used. + +### Adapters + +Adapters allows `diagnostics` to pull the `DEBUG` and `DIAGNOSTICS` environment +variables from different sources. Not every JavaScript environment has a +`process.env` that we can leverage. Adapters allows us to have different +adapters for different environments. It means you can write your own custom +adapter if needed as well. + +The `adapter` function should be passed a function as argument, this function +will receive the `namespace` of a logger as argument and it should return a +boolean that indicates if that logger should be enabled or not. + +```js +const debug = require('@dabh/diagnostics')('example:namespace'); + +debug.adapter(require('@dabh/diagnostics/adapters/localstorage')); +``` + +The modifiers are only enabled for `development`. The following adapters are +available are available: + +#### process.env + +This adapter is enabled for `node.js`. + +Uses the `DEBUG` or `DIAGNOSTICS` (both are recognized) environment variables to +pass in debug flag: + +**UNIX/Linux/Mac** +``` +DEBUG=foo* node index.js +``` + +Using environment variables on Windows is a bit different, and also depends on +toolchain you are using: + +**Windows** +``` +set DEBUG=foo* & node index.js +``` + +**Powershell** +``` +$env:DEBUG='foo*';node index.js +``` + +#### hash + +This adapter is enabled for `browsers`. + +This adapter uses the `window.location.hash` of as source for the environment +variables. It assumes that hash is formatted using the same syntax as query +strings: + +```js +http://example.com/foo/bar#debug=foo* +``` + +It triggers on both the `debug=` and `diagnostics=` names. + +#### localStorage + +This adapter is enabled for `browsers`. + +This adapter uses the `localStorage` of the browser to store the debug flags. +You can set the debug flag your self in your application code, but you can +also open browser WebInspector and enable it through the console. + +```js +localStorage.setItem('debug', 'foo*'); +``` + +It triggers on both the `debug` and `diagnostics` storage items. (Please note +that these keys should be entered in lowercase) + +#### AsyncStorage + +This adapter is enabled for `react-native`. + +This adapter uses the `AsyncStorage` API that is exposed by the `react-native` +library to store and read the `debug` or `diagnostics` storage items. + +```js +import { AsyncStorage } from 'react-native'; + +AsyncStorage.setItem('debug', 'foo*'); +``` + +Unlike other adapters, this is the only adapter that is `async` so that means +that we're not able to instantly determine if a created logger should be +enabled or disabled. So when a logger is created in `react-native` we initially +assume it's disabled, any message that send during period will be queued +internally. + +Once we've received the data from the `AsyncStorage` API we will determine +if the logger should be enabled, flush the queued messages if needed and set +all `enabled` properties accordingly on the returned logger. + +### Loggers + +By default it will log all messages to `console.log` in when the logger is +enabled using the debug flag that is set using one of the adapters. + +## License + +[MIT](LICENSE) diff --git a/nodejs/node_modules/@dabh/diagnostics/adapters/hash.js b/nodejs/node_modules/@dabh/diagnostics/adapters/hash.js new file mode 100644 index 00000000..a41aae5c --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/adapters/hash.js @@ -0,0 +1,11 @@ +var adapter = require('./'); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function hash() { + return /(debug|diagnostics)=([^&]+)/i.exec(window.location.hash)[2]; +}); diff --git a/nodejs/node_modules/@dabh/diagnostics/adapters/index.js b/nodejs/node_modules/@dabh/diagnostics/adapters/index.js new file mode 100644 index 00000000..d60aaea5 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/adapters/index.js @@ -0,0 +1,18 @@ +var enabled = require('enabled'); + +/** + * Creates a new Adapter. + * + * @param {Function} fn Function that returns the value. + * @returns {Function} The adapter logic. + * @public + */ +module.exports = function create(fn) { + return function adapter(namespace) { + try { + return enabled(namespace, fn()); + } catch (e) { /* Any failure means that we found nothing */ } + + return false; + }; +} diff --git a/nodejs/node_modules/@dabh/diagnostics/adapters/localstorage.js b/nodejs/node_modules/@dabh/diagnostics/adapters/localstorage.js new file mode 100644 index 00000000..bb889875 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/adapters/localstorage.js @@ -0,0 +1,11 @@ +var adapter = require('./'); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function storage() { + return localStorage.getItem('debug') || localStorage.getItem('diagnostics'); +}); diff --git a/nodejs/node_modules/@dabh/diagnostics/adapters/process.env.js b/nodejs/node_modules/@dabh/diagnostics/adapters/process.env.js new file mode 100644 index 00000000..5ab166a4 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/adapters/process.env.js @@ -0,0 +1,11 @@ +var adapter = require('./'); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function processenv() { + return process.env.DEBUG || process.env.DIAGNOSTICS; +}); diff --git a/nodejs/node_modules/@dabh/diagnostics/browser/development.js b/nodejs/node_modules/@dabh/diagnostics/browser/development.js new file mode 100644 index 00000000..e36dfaa5 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/browser/development.js @@ -0,0 +1,35 @@ +var create = require('../diagnostics'); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = false; + options.dev = true; + + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); + } + + return dev.yep(options); +}); + +// +// Configure the logger for the given environment. +// +diagnostics.modify(require('../modifiers/namespace')); +diagnostics.use(require('../adapters/localstorage')); +diagnostics.use(require('../adapters/hash')); +diagnostics.set(require('../logger/console')); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/nodejs/node_modules/@dabh/diagnostics/browser/index.js b/nodejs/node_modules/@dabh/diagnostics/browser/index.js new file mode 100644 index 00000000..ae0f2f80 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/browser/index.js @@ -0,0 +1,8 @@ +// +// Select the correct build version depending on the environment. +// +if (process.env.NODE_ENV === 'production') { + module.exports = require('./production.js'); +} else { + module.exports = require('./development.js'); +} diff --git a/nodejs/node_modules/@dabh/diagnostics/browser/override.js b/nodejs/node_modules/@dabh/diagnostics/browser/override.js new file mode 100644 index 00000000..8f363772 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/browser/override.js @@ -0,0 +1,6 @@ +var diagnostics = require('./'); + +// +// No way to override `debug` with `diagnostics` in the browser. +// +module.exports = diagnostics; diff --git a/nodejs/node_modules/@dabh/diagnostics/browser/production.js b/nodejs/node_modules/@dabh/diagnostics/browser/production.js new file mode 100644 index 00000000..1a19ce39 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/browser/production.js @@ -0,0 +1,24 @@ +var create = require('../diagnostics'); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function prod(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = true; + options.dev = false; + + if (!(options.force || prod.force)) return prod.nope(options); + return prod.yep(options); +}); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/nodejs/node_modules/@dabh/diagnostics/diagnostics.js b/nodejs/node_modules/@dabh/diagnostics/diagnostics.js new file mode 100644 index 00000000..12dc1f35 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/diagnostics.js @@ -0,0 +1,212 @@ +/** + * Contains all configured adapters for the given environment. + * + * @type {Array} + * @public + */ +var adapters = []; + +/** + * Contains all modifier functions. + * + * @typs {Array} + * @public + */ +var modifiers = []; + +/** + * Our default logger. + * + * @public + */ +var logger = function devnull() {}; + +/** + * Register a new adapter that will used to find environments. + * + * @param {Function} adapter A function that will return the possible env. + * @returns {Boolean} Indication of a successful add. + * @public + */ +function use(adapter) { + if (~adapters.indexOf(adapter)) return false; + + adapters.push(adapter); + return true; +} + +/** + * Assign a new log method. + * + * @param {Function} custom The log method. + * @public + */ +function set(custom) { + logger = custom; +} + +/** + * Check if the namespace is allowed by any of our adapters. + * + * @param {String} namespace The namespace that needs to be enabled + * @returns {Boolean|Promise} Indication if the namespace is enabled by our adapters. + * @public + */ +function enabled(namespace) { + var async = []; + + for (var i = 0; i < adapters.length; i++) { + if (adapters[i].async) { + async.push(adapters[i]); + continue; + } + + if (adapters[i](namespace)) return true; + } + + if (!async.length) return false; + + // + // Now that we know that we Async functions, we know we run in an ES6 + // environment and can use all the API's that they offer, in this case + // we want to return a Promise so that we can `await` in React-Native + // for an async adapter. + // + return new Promise(function pinky(resolve) { + Promise.all( + async.map(function prebind(fn) { + return fn(namespace); + }) + ).then(function resolved(values) { + resolve(values.some(Boolean)); + }); + }); +} + +/** + * Add a new message modifier to the debugger. + * + * @param {Function} fn Modification function. + * @returns {Boolean} Indication of a successful add. + * @public + */ +function modify(fn) { + if (~modifiers.indexOf(fn)) return false; + + modifiers.push(fn); + return true; +} + +/** + * Write data to the supplied logger. + * + * @param {Object} meta Meta information about the log. + * @param {Array} args Arguments for console.log. + * @public + */ +function write() { + logger.apply(logger, arguments); +} + +/** + * Process the message with the modifiers. + * + * @param {Mixed} message The message to be transformed by modifers. + * @returns {String} Transformed message. + * @public + */ +function process(message) { + for (var i = 0; i < modifiers.length; i++) { + message = modifiers[i].apply(modifiers[i], arguments); + } + + return message; +} + +/** + * Introduce options to the logger function. + * + * @param {Function} fn Calback function. + * @param {Object} options Properties to introduce on fn. + * @returns {Function} The passed function + * @public + */ +function introduce(fn, options) { + var has = Object.prototype.hasOwnProperty; + + for (var key in options) { + if (has.call(options, key)) { + fn[key] = options[key]; + } + } + + return fn; +} + +/** + * Nope, we're not allowed to write messages. + * + * @returns {Boolean} false + * @public + */ +function nope(options) { + options.enabled = false; + options.modify = modify; + options.set = set; + options.use = use; + + return introduce(function diagnopes() { + return false; + }, options); +} + +/** + * Yep, we're allowed to write debug messages. + * + * @param {Object} options The options for the process. + * @returns {Function} The function that does the logging. + * @public + */ +function yep(options) { + /** + * The function that receives the actual debug information. + * + * @returns {Boolean} indication that we're logging. + * @public + */ + function diagnostics() { + var args = Array.prototype.slice.call(arguments, 0); + + write.call(write, options, process(args, options)); + return true; + } + + options.enabled = true; + options.modify = modify; + options.set = set; + options.use = use; + + return introduce(diagnostics, options); +} + +/** + * Simple helper function to introduce various of helper methods to our given + * diagnostics function. + * + * @param {Function} diagnostics The diagnostics function. + * @returns {Function} diagnostics + * @public + */ +module.exports = function create(diagnostics) { + diagnostics.introduce = introduce; + diagnostics.enabled = enabled; + diagnostics.process = process; + diagnostics.modify = modify; + diagnostics.write = write; + diagnostics.nope = nope; + diagnostics.yep = yep; + diagnostics.set = set; + diagnostics.use = use; + + return diagnostics; +} diff --git a/nodejs/node_modules/@dabh/diagnostics/logger/console.js b/nodejs/node_modules/@dabh/diagnostics/logger/console.js new file mode 100644 index 00000000..7423eff9 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/logger/console.js @@ -0,0 +1,19 @@ +/** + * An idiot proof logger to be used as default. We've wrapped it in a try/catch + * statement to ensure the environments without the `console` API do not crash + * as well as an additional fix for ancient browsers like IE8 where the + * `console.log` API doesn't have an `apply`, so we need to use the Function's + * apply functionality to apply the arguments. + * + * @param {Object} meta Options of the logger. + * @param {Array} messages The actuall message that needs to be logged. + * @public + */ +module.exports = function (meta, messages) { + // + // So yea. IE8 doesn't have an apply so we need a work around to puke the + // arguments in place. + // + try { Function.prototype.apply.call(console.log, console, messages); } + catch (e) {} +} diff --git a/nodejs/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js b/nodejs/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js new file mode 100644 index 00000000..e3d1ec69 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js @@ -0,0 +1,20 @@ +var colorspace = require('colorspace'); +var kuler = require('kuler'); + +/** + * Prefix the messages with a colored namespace. + * + * @param {Array} args The messages array that is getting written. + * @param {Object} options Options for diagnostics. + * @returns {Array} Altered messages array. + * @public + */ +module.exports = function ansiModifier(args, options) { + var namespace = options.namespace; + var ansi = options.colors !== false + ? kuler(namespace +':', colorspace(namespace)) + : namespace +':'; + + args[0] = ansi +' '+ args[0]; + return args; +}; diff --git a/nodejs/node_modules/@dabh/diagnostics/modifiers/namespace.js b/nodejs/node_modules/@dabh/diagnostics/modifiers/namespace.js new file mode 100644 index 00000000..ac190773 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/modifiers/namespace.js @@ -0,0 +1,32 @@ +var colorspace = require('colorspace'); + +/** + * Prefix the messages with a colored namespace. + * + * @param {Array} messages The messages array that is getting written. + * @param {Object} options Options for diagnostics. + * @returns {Array} Altered messages array. + * @public + */ +module.exports = function colorNamespace(args, options) { + var namespace = options.namespace; + + if (options.colors === false) { + args[0] = namespace +': '+ args[0]; + return args; + } + + var color = colorspace(namespace); + + // + // The console API supports a special %c formatter in browsers. This is used + // to style console messages with any CSS styling, in our case we want to + // use colorize the namespace for clarity. As these are formatters, and + // we need to inject our CSS string as second messages argument so it + // gets picked up correctly. + // + args[0] = '%c'+ namespace +':%c '+ args[0]; + args.splice(1, 0, 'color:'+ color, 'color:inherit'); + + return args; +}; diff --git a/nodejs/node_modules/@dabh/diagnostics/node/development.js b/nodejs/node_modules/@dabh/diagnostics/node/development.js new file mode 100644 index 00000000..51dc51b6 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/node/development.js @@ -0,0 +1,36 @@ +var create = require('../diagnostics'); +var tty = require('tty').isatty(1); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.colors = 'colors' in options ? options.colors : tty; + options.namespace = namespace; + options.prod = false; + options.dev = true; + + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); + } + + return dev.yep(options); +}); + +// +// Configure the logger for the given environment. +// +diagnostics.modify(require('../modifiers/namespace-ansi')); +diagnostics.use(require('../adapters/process.env')); +diagnostics.set(require('../logger/console')); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/nodejs/node_modules/@dabh/diagnostics/node/index.js b/nodejs/node_modules/@dabh/diagnostics/node/index.js new file mode 100644 index 00000000..ae0f2f80 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/node/index.js @@ -0,0 +1,8 @@ +// +// Select the correct build version depending on the environment. +// +if (process.env.NODE_ENV === 'production') { + module.exports = require('./production.js'); +} else { + module.exports = require('./development.js'); +} diff --git a/nodejs/node_modules/@dabh/diagnostics/node/override.js b/nodejs/node_modules/@dabh/diagnostics/node/override.js new file mode 100644 index 00000000..936e28be --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/node/override.js @@ -0,0 +1,21 @@ +const diagnostics = require('./'); + +// +// Override the existing `debug` call so it will use `diagnostics` instead +// of the `debug` module. +// +try { + var key = require.resolve('debug'); + + require.cache[key] = { + exports: diagnostics, + filename: key, + loaded: true, + id: key + }; +} catch (e) { /* We don't really care if it fails */ } + +// +// Export the default import as exports again. +// +module.exports = diagnostics; diff --git a/nodejs/node_modules/@dabh/diagnostics/node/production.js b/nodejs/node_modules/@dabh/diagnostics/node/production.js new file mode 100644 index 00000000..1a19ce39 --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/node/production.js @@ -0,0 +1,24 @@ +var create = require('../diagnostics'); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function prod(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = true; + options.dev = false; + + if (!(options.force || prod.force)) return prod.nope(options); + return prod.yep(options); +}); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/nodejs/node_modules/@dabh/diagnostics/package.json b/nodejs/node_modules/@dabh/diagnostics/package.json new file mode 100644 index 00000000..7e1efd9f --- /dev/null +++ b/nodejs/node_modules/@dabh/diagnostics/package.json @@ -0,0 +1,64 @@ +{ + "name": "@dabh/diagnostics", + "version": "2.0.3", + "description": "Tools for debugging your node.js modules and event loop", + "main": "./node", + "browser": "./browser", + "scripts": { + "test:basic": "mocha --require test/mock.js test/*.test.js", + "test:node": "mocha --require test/mock test/node.js", + "test:browser": "mocha --require test/mock test/browser.js", + "test:runner": "npm run test:basic && npm run test:node && npm run test:browser", + "webpack:node:prod": "webpack --mode=production node/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "webpack:node:dev": "webpack --mode=development node/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "webpack:browser:prod": "webpack --mode=production browser/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "webpack:browser:dev": "webpack --mode=development browser/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "test": "nyc --reporter=text --reporter=lcov npm run test:runner" + }, + "repository": { + "type": "git", + "url": "git://github.com/3rd-Eden/diagnostics.git" + }, + "keywords": [ + "debug", + "debugger", + "debugging", + "diagnostic", + "diagnostics", + "event", + "loop", + "metrics", + "stats" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "bugs": { + "url": "https://github.com/3rd-Eden/diagnostics/issues" + }, + "homepage": "https://github.com/3rd-Eden/diagnostics", + "devDependencies": { + "assume": "2.3.x", + "asyncstorageapi": "^1.0.2", + "mocha": "9.2.x", + "nyc": "^15.1.0", + "objstorage": "^1.0.0", + "pre-commit": "1.2.x", + "require-poisoning": "^2.0.0", + "webpack": "4.x", + "webpack-bundle-size-analyzer": "^3.0.0", + "webpack-cli": "3.x" + }, + "dependencies": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + }, + "contributors": [ + "Martijn Swaagman (https://github.com/swaagie)", + "Jarrett Cruger (https://github.com/jcrugzz)", + "Sevastos (https://github.com/sevastos)" + ], + "directories": { + "test": "test" + } +} diff --git a/nodejs/node_modules/@mongodb-js/saslprep/LICENSE b/nodejs/node_modules/@mongodb-js/saslprep/LICENSE new file mode 100644 index 00000000..481c7a50 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dmitry Tsvettsikh + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/.esm-wrapper.mjs b/nodejs/node_modules/@mongodb-js/saslprep/dist/.esm-wrapper.mjs new file mode 100644 index 00000000..0b46bfa6 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/.esm-wrapper.mjs @@ -0,0 +1,4 @@ +import mod from "./node.js"; + +export default mod; +export const saslprep = mod.saslprep; diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.d.ts new file mode 100644 index 00000000..70a71a5a --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.d.ts @@ -0,0 +1,5 @@ +declare const saslprep: (args_0: string, args_1?: { + allowUnassigned?: boolean | undefined; +} | undefined) => string; +export = saslprep; +//# sourceMappingURL=browser.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.d.ts.map new file mode 100644 index 00000000..669fc643 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAMA,QAAA,MAAM,QAAQ;;wBAAmC,CAAC;AAIlD,SAAS,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.js new file mode 100644 index 00000000..1bedd860 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.js @@ -0,0 +1,12 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const index_1 = __importDefault(require("./index")); +const memory_code_points_1 = require("./memory-code-points"); +const code_points_data_browser_1 = __importDefault(require("./code-points-data-browser")); +const codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_browser_1.default); +const saslprep = index_1.default.bind(null, codePoints); +Object.assign(saslprep, { saslprep, default: saslprep }); +module.exports = saslprep; +//# sourceMappingURL=browser.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.js.map new file mode 100644 index 00000000..40edf44b --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":";;;;AAAA,oDAAgC;AAChC,6DAA8D;AAC9D,0FAA8C;AAE9C,MAAM,UAAU,GAAG,IAAA,2CAAsB,EAAC,kCAAI,CAAC,CAAC;AAEhD,MAAM,QAAQ,GAAG,eAAS,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;AAEzD,iBAAS,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts new file mode 100644 index 00000000..f85af5b8 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts @@ -0,0 +1,4 @@ +/// +declare const data: Buffer; +export default data; +//# sourceMappingURL=code-points-data-browser.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts.map new file mode 100644 index 00000000..617b217b --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"code-points-data-browser.d.ts","sourceRoot":"","sources":["../src/code-points-data-browser.ts"],"names":[],"mappings":";AAAA,QAAA,MAAM,IAAI,QAGT,CAAC;AACF,eAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js new file mode 100644 index 00000000..5ea96355 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const data = Buffer.from('AAHgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAP////AAAAAAAAAAAAAAADAAAAAAAAAAH//wAAAAAAAAAAAAD//wAA893wFAAAIAAAAAABAAAAAAH/AAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAEAAAAAAz8AAP////+AAAAAAYCAAAAAAJ+AACAAACAH/wAAAB8H///3/+6AAAAfAAAD/wAAAAAAAAAAAAAAAAAAAAAAAwABAAIAAAAHAAAAH////////wAAAAAAAD///////////////////////////////////////////////////////4gAAAAAAAAwAAMHAAAAf/+IBmAAAEBcNAZj/vIMAAAf2B5gAABASTQeY/+F/AAH/4gKIAAAQEgwAiN//3wA//+IBmAAAEBMMA5j/PI8AH//yBxDlOccAjwcQ/7//gAf/4gEQAAAQAg8BEP5/zwA///IBEAAAEAIPARD+f08AP//yARAAABAADwMQ/7/PAD//8gAAcAAACALAd4FAP//x/+AAAAAAAAAHgAAAA//////llvwgIrIACMFAwAz/////wAAAAAAAAAAAIAAAAAfgAAADwCAAAAABAAG////////AAAAACCQHD8AAAA///////////8AAAAAA/8AAAAAAG8AAAAAAAAAAAAAAD4AAAAAAAAAAB8AAAAAAAAAAAAAPwEAAAAAAAAAAUMBQwAAAAABQwAAAAFDAUMBAQAAAQAAAAFDAQAAAAABAAAfgAAAB/////8AAAAAAAAAAAAAB/+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/wAAAAcAAAAAAAAAAAAAf/8ABAf/AAAB/wAAD/8ABE//AAAAAAAAAAAAAAAHAD///wABAD8AAAAAAAAAAAAAAP8AAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAA/AAADAwAAAAADAwCqAAAAAwAAAAAAAAQABAAMCAAAxAEAAAAAAAAAAAAAHv4PwDAAAAH//wAAP////wAAAB///wAAAAAAAAAYAA/gAAAAAAAP/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf///////wAAAAAB////AB///wAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAAAAAAAAAAAAAAAADAD///////////////////4QwAAAAgAAAAAodAYAAAAAAAAcAAACAAf//AAAADwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wAAACAAAAAAAAAAAAAAD/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///8ADwAAAAAAAAAAgAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAA+AAAAAAHgAAAAAAAAAAAAAABAAAAAAD/////////AAAAAAAHAAAAAA//gAAAAAAOAAAAAAAAAAAADwAAAAAAAQAAAAAAAAAAAAAAAAAAAeAAAAAAAAAAAAAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA///////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAB////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAB////////////////////////8B/+D4AAABBSQAAAAAAAAAAAAAAAAAP////+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAwAAAAAAAAP8AAAAAAAcAAP//D/8AAAGAEAABDwQAAAAAAAAAAAAAAAAAAAAABoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcDAwMcBAf+A////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAQ//AAAAH/////////////////////////////8AAAAAAwAAAAAD//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/wAAAAABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////////////////////////////////////////////////////////////////////////////////wAAAAAAAAAAAAAEAAAAAAAAAAAE2YQAKEgAAAAAAAAAAhgEBAAAACEFwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAA//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////P/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////z//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////P/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////z//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////P/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////z//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////P/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////y/////AAAAAAAAAAAAAAAA/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////P//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKQAP///+D4AAAAABF////g/+AAAAAHf////////////////AQGAAA+//y////4AAAAAAAAAAAAAP/////8AEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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7/////////////////////////////////////////////////v//wAAAA///////////////8/5/AAMAA+AIAAAAAAAAAAAAAAAAAAAAAACAC6///3//////+//////wA/////////////////////+A///////////7//////MD//wAAAAB//////n9//////0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABf////////HgHiA/8//gAA3+Z///7+jw4GYAQ3D/8/gB+Gf//+/tsOAAAB6A/84ABf13///v7fHgFiAAIP/AAA3+Z///7+zxoGYAQ3D/4AAF+O8axjj/cNjuAEAAf/gAHf7v///v/fAeAAAAMP/AAA3+7///7/3wvmwBgLD/wAAN/u///+//8ODuAEAw/8AADf//j///9/0/gHA/wAAOAB///////+wAP4B//AAAAAAaaQPf3U3sAT6AP/MAAAAAP///z////qD/3/////gAAEE8AAAAAAAA/35AAAAAAAA/////99oQID///8AAAAAAAAAAAD//////AD//////5D//////////////8H//////////+D/////////////wP7//////////rz+vP/////+vP////68/rz+/v///v////68/v/////+///gf///+AAAAAD/////////////+AB////////////////////////////////////////////////////////////////////////////////////////////////////////+AH///+D/////////////gAD/+8AA///GAP//wAD/+4AA/////////gP9gA/o/8AAAAAA/8D//////////////wD//////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/////////////////////////w///////////////A///8/P/////8/P9V/////P////////v6O/jz8P/4O/gAAgAAAAAAAAAAAAAAAEABAAAAAAAAAAAAAAAAAAAAACE/9HwKvd/HB8AAAP/////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////gAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAB/wHz4f/////////////4Hf//////////////vB//////4f//////////////+//////8AAAAAAAAA///////4//////AAAAD////x////////gAD/8P///////v///////////////////h////////////////z////+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAP///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAP/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8/////////+A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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////w=', 'base64'); +exports.default = data; +//# sourceMappingURL=code-points-data-browser.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js.map new file mode 100644 index 00000000..feba4779 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"code-points-data-browser.js","sourceRoot":"","sources":["../src/code-points-data-browser.ts"],"names":[],"mappings":";;AAAA,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CACtB,8sliBAA8sliB,EAC9sliB,QAAQ,CACT,CAAC;AACF,kBAAe,IAAI,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts new file mode 100644 index 00000000..cc908ec5 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts @@ -0,0 +1,4 @@ +/// +declare const _default: Buffer; +export default _default; +//# sourceMappingURL=code-points-data.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts.map new file mode 100644 index 00000000..772442e0 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"code-points-data.d.ts","sourceRoot":"","sources":["../src/code-points-data.ts"],"names":[],"mappings":";;AAEA,wBAKE"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.js new file mode 100644 index 00000000..36e458cf --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const zlib_1 = require("zlib"); +exports.default = (0, zlib_1.gunzipSync)(Buffer.from('H4sIAAAAAAACA+3dTYgcWR0A8FfTnekQ47aCkBxiZpYV8RhwYQM7bA/ksoLgSRD0IOSiePAkLrowvWSF4CkHEW856MlTQHA9RKZ1ZJODsEcVcTOyhxUEbXdXtpPp1PNVV39Uz4czEyaTVOb3G6a7XtWrr/devX49/+qekG2Go7Aa2jHGyozG+Dmrzi2mP/xb/zMhLI+WlRm2byubm2h0ivVi7BYzusVjuNkt1l9uFWsutWL8OP4rzV9KeXdsKx1HFhbSc6vIG0fKBZ14UNfLFS6FRrGRtXh98ZvphL/x4uLV/IOzaat/vlikv/TixavxR8PQitfPpKNbffXSwgtr8fV07GX+L1967urwg5W0/t0LV37y/oWFlQtX8ping7reXE3LT680r9yPKyn/3Vn64SwdVs6m/KN0yHrp9D+RvXsqpe6MSia5mH6LSog//Xq/++O74YVTjfDFWK2VIuNSemiPppphcVYeyzcudKqFMiq6cs3vVkrzlcnE0mxeZ1Jf2ZXsSvk8TmRZWYdpalydxd5bc8eUkt1wlEb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appingURL=code-points-data.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.js.map new file mode 100644 index 00000000..89b5e528 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"code-points-data.js","sourceRoot":"","sources":["../src/code-points-data.ts"],"names":[],"mappings":";;AAAA,+BAAkC;AAElC,kBAAe,IAAA,iBAAU,EACvB,MAAM,CAAC,IAAI,CACT,0nFAA0nF,EAC1nF,QAAQ,CACT,CACF,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts new file mode 100644 index 00000000..36b6c565 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts @@ -0,0 +1,7 @@ +export declare const unassigned_code_points: Set; +export declare const commonly_mapped_to_nothing: Set; +export declare const non_ASCII_space_characters: Set; +export declare const prohibited_characters: Set; +export declare const bidirectional_r_al: Set; +export declare const bidirectional_l: Set; +//# sourceMappingURL=code-points-src.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts.map new file mode 100644 index 00000000..ef0e6947 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"code-points-src.d.ts","sourceRoot":"","sources":["../src/code-points-src.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,sBAAsB,aA6YjC,CAAC;AAMH,eAAO,MAAM,0BAA0B,aAIrC,CAAC;AAMH,eAAO,MAAM,0BAA0B,aASrC,CAAC;AAMH,eAAO,MAAM,qBAAqB,aA6GhC,CAAC;AAMH,eAAO,MAAM,kBAAkB,aAmC7B,CAAC;AAMH,eAAO,MAAM,eAAe,aAyW1B,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.js new file mode 100644 index 00000000..2caa6297 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.js @@ -0,0 +1,881 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bidirectional_l = exports.bidirectional_r_al = exports.prohibited_characters = exports.non_ASCII_space_characters = exports.commonly_mapped_to_nothing = exports.unassigned_code_points = void 0; +const util_1 = require("./util"); +exports.unassigned_code_points = new Set([ + 0x0221, + ...(0, util_1.range)(0x0234, 0x024f), + ...(0, util_1.range)(0x02ae, 0x02af), + ...(0, util_1.range)(0x02ef, 0x02ff), + ...(0, util_1.range)(0x0350, 0x035f), + ...(0, util_1.range)(0x0370, 0x0373), + ...(0, util_1.range)(0x0376, 0x0379), + ...(0, util_1.range)(0x037b, 0x037d), + ...(0, util_1.range)(0x037f, 0x0383), + 0x038b, + 0x038d, + 0x03a2, + 0x03cf, + ...(0, util_1.range)(0x03f7, 0x03ff), + 0x0487, + 0x04cf, + ...(0, util_1.range)(0x04f6, 0x04f7), + ...(0, util_1.range)(0x04fa, 0x04ff), + ...(0, util_1.range)(0x0510, 0x0530), + ...(0, util_1.range)(0x0557, 0x0558), + 0x0560, + 0x0588, + ...(0, util_1.range)(0x058b, 0x0590), + 0x05a2, + 0x05ba, + ...(0, util_1.range)(0x05c5, 0x05cf), + ...(0, util_1.range)(0x05eb, 0x05ef), + ...(0, util_1.range)(0x05f5, 0x060b), + ...(0, util_1.range)(0x060d, 0x061a), + ...(0, util_1.range)(0x061c, 0x061e), + 0x0620, + ...(0, util_1.range)(0x063b, 0x063f), + ...(0, util_1.range)(0x0656, 0x065f), + ...(0, util_1.range)(0x06ee, 0x06ef), + 0x06ff, + 0x070e, + ...(0, util_1.range)(0x072d, 0x072f), + ...(0, util_1.range)(0x074b, 0x077f), + ...(0, util_1.range)(0x07b2, 0x0900), + 0x0904, + ...(0, util_1.range)(0x093a, 0x093b), + ...(0, util_1.range)(0x094e, 0x094f), + ...(0, util_1.range)(0x0955, 0x0957), + ...(0, util_1.range)(0x0971, 0x0980), + 0x0984, + ...(0, util_1.range)(0x098d, 0x098e), + ...(0, util_1.range)(0x0991, 0x0992), + 0x09a9, + 0x09b1, + ...(0, util_1.range)(0x09b3, 0x09b5), + ...(0, util_1.range)(0x09ba, 0x09bb), + 0x09bd, + ...(0, util_1.range)(0x09c5, 0x09c6), + ...(0, util_1.range)(0x09c9, 0x09ca), + ...(0, util_1.range)(0x09ce, 0x09d6), + ...(0, util_1.range)(0x09d8, 0x09db), + 0x09de, + ...(0, util_1.range)(0x09e4, 0x09e5), + ...(0, util_1.range)(0x09fb, 0x0a01), + ...(0, util_1.range)(0x0a03, 0x0a04), + ...(0, util_1.range)(0x0a0b, 0x0a0e), + ...(0, util_1.range)(0x0a11, 0x0a12), + 0x0a29, + 0x0a31, + 0x0a34, + 0x0a37, + ...(0, util_1.range)(0x0a3a, 0x0a3b), + 0x0a3d, + ...(0, util_1.range)(0x0a43, 0x0a46), + ...(0, util_1.range)(0x0a49, 0x0a4a), + ...(0, util_1.range)(0x0a4e, 0x0a58), + 0x0a5d, + ...(0, util_1.range)(0x0a5f, 0x0a65), + ...(0, util_1.range)(0x0a75, 0x0a80), + 0x0a84, + 0x0a8c, + 0x0a8e, + 0x0a92, + 0x0aa9, + 0x0ab1, + 0x0ab4, + ...(0, util_1.range)(0x0aba, 0x0abb), + 0x0ac6, + 0x0aca, + ...(0, util_1.range)(0x0ace, 0x0acf), + ...(0, util_1.range)(0x0ad1, 0x0adf), + ...(0, util_1.range)(0x0ae1, 0x0ae5), + ...(0, util_1.range)(0x0af0, 0x0b00), + 0x0b04, + ...(0, util_1.range)(0x0b0d, 0x0b0e), + ...(0, util_1.range)(0x0b11, 0x0b12), + 0x0b29, + 0x0b31, + ...(0, util_1.range)(0x0b34, 0x0b35), + ...(0, util_1.range)(0x0b3a, 0x0b3b), + ...(0, util_1.range)(0x0b44, 0x0b46), + ...(0, util_1.range)(0x0b49, 0x0b4a), + ...(0, util_1.range)(0x0b4e, 0x0b55), + ...(0, util_1.range)(0x0b58, 0x0b5b), + 0x0b5e, + ...(0, util_1.range)(0x0b62, 0x0b65), + ...(0, util_1.range)(0x0b71, 0x0b81), + 0x0b84, + ...(0, util_1.range)(0x0b8b, 0x0b8d), + 0x0b91, + ...(0, util_1.range)(0x0b96, 0x0b98), + 0x0b9b, + 0x0b9d, + ...(0, util_1.range)(0x0ba0, 0x0ba2), + ...(0, util_1.range)(0x0ba5, 0x0ba7), + ...(0, util_1.range)(0x0bab, 0x0bad), + 0x0bb6, + ...(0, util_1.range)(0x0bba, 0x0bbd), + ...(0, util_1.range)(0x0bc3, 0x0bc5), + 0x0bc9, + ...(0, util_1.range)(0x0bce, 0x0bd6), + ...(0, util_1.range)(0x0bd8, 0x0be6), + ...(0, util_1.range)(0x0bf3, 0x0c00), + 0x0c04, + 0x0c0d, + 0x0c11, + 0x0c29, + 0x0c34, + ...(0, util_1.range)(0x0c3a, 0x0c3d), + 0x0c45, + 0x0c49, + ...(0, util_1.range)(0x0c4e, 0x0c54), + ...(0, util_1.range)(0x0c57, 0x0c5f), + ...(0, util_1.range)(0x0c62, 0x0c65), + ...(0, util_1.range)(0x0c70, 0x0c81), + 0x0c84, + 0x0c8d, + 0x0c91, + 0x0ca9, + 0x0cb4, + ...(0, util_1.range)(0x0cba, 0x0cbd), + 0x0cc5, + 0x0cc9, + ...(0, util_1.range)(0x0cce, 0x0cd4), + ...(0, util_1.range)(0x0cd7, 0x0cdd), + 0x0cdf, + ...(0, util_1.range)(0x0ce2, 0x0ce5), + ...(0, util_1.range)(0x0cf0, 0x0d01), + 0x0d04, + 0x0d0d, + 0x0d11, + 0x0d29, + ...(0, util_1.range)(0x0d3a, 0x0d3d), + ...(0, util_1.range)(0x0d44, 0x0d45), + 0x0d49, + ...(0, util_1.range)(0x0d4e, 0x0d56), + ...(0, util_1.range)(0x0d58, 0x0d5f), + ...(0, util_1.range)(0x0d62, 0x0d65), + ...(0, util_1.range)(0x0d70, 0x0d81), + 0x0d84, + ...(0, util_1.range)(0x0d97, 0x0d99), + 0x0db2, + 0x0dbc, + ...(0, util_1.range)(0x0dbe, 0x0dbf), + ...(0, util_1.range)(0x0dc7, 0x0dc9), + ...(0, util_1.range)(0x0dcb, 0x0dce), + 0x0dd5, + 0x0dd7, + ...(0, util_1.range)(0x0de0, 0x0df1), + ...(0, util_1.range)(0x0df5, 0x0e00), + ...(0, util_1.range)(0x0e3b, 0x0e3e), + ...(0, util_1.range)(0x0e5c, 0x0e80), + 0x0e83, + ...(0, util_1.range)(0x0e85, 0x0e86), + 0x0e89, + ...(0, util_1.range)(0x0e8b, 0x0e8c), + ...(0, util_1.range)(0x0e8e, 0x0e93), + 0x0e98, + 0x0ea0, + 0x0ea4, + 0x0ea6, + ...(0, util_1.range)(0x0ea8, 0x0ea9), + 0x0eac, + 0x0eba, + ...(0, util_1.range)(0x0ebe, 0x0ebf), + 0x0ec5, + 0x0ec7, + ...(0, util_1.range)(0x0ece, 0x0ecf), + ...(0, util_1.range)(0x0eda, 0x0edb), + ...(0, util_1.range)(0x0ede, 0x0eff), + 0x0f48, + ...(0, util_1.range)(0x0f6b, 0x0f70), + ...(0, util_1.range)(0x0f8c, 0x0f8f), + 0x0f98, + 0x0fbd, + ...(0, util_1.range)(0x0fcd, 0x0fce), + ...(0, util_1.range)(0x0fd0, 0x0fff), + 0x1022, + 0x1028, + 0x102b, + ...(0, util_1.range)(0x1033, 0x1035), + ...(0, util_1.range)(0x103a, 0x103f), + ...(0, util_1.range)(0x105a, 0x109f), + ...(0, util_1.range)(0x10c6, 0x10cf), + ...(0, util_1.range)(0x10f9, 0x10fa), + ...(0, util_1.range)(0x10fc, 0x10ff), + ...(0, util_1.range)(0x115a, 0x115e), + ...(0, util_1.range)(0x11a3, 0x11a7), + ...(0, util_1.range)(0x11fa, 0x11ff), + 0x1207, + 0x1247, + 0x1249, + ...(0, util_1.range)(0x124e, 0x124f), + 0x1257, + 0x1259, + ...(0, util_1.range)(0x125e, 0x125f), + 0x1287, + 0x1289, + ...(0, util_1.range)(0x128e, 0x128f), + 0x12af, + 0x12b1, + ...(0, util_1.range)(0x12b6, 0x12b7), + 0x12bf, + 0x12c1, + ...(0, util_1.range)(0x12c6, 0x12c7), + 0x12cf, + 0x12d7, + 0x12ef, + 0x130f, + 0x1311, + ...(0, util_1.range)(0x1316, 0x1317), + 0x131f, + 0x1347, + ...(0, util_1.range)(0x135b, 0x1360), + ...(0, util_1.range)(0x137d, 0x139f), + ...(0, util_1.range)(0x13f5, 0x1400), + ...(0, util_1.range)(0x1677, 0x167f), + ...(0, util_1.range)(0x169d, 0x169f), + ...(0, util_1.range)(0x16f1, 0x16ff), + 0x170d, + ...(0, util_1.range)(0x1715, 0x171f), + ...(0, util_1.range)(0x1737, 0x173f), + ...(0, util_1.range)(0x1754, 0x175f), + 0x176d, + 0x1771, + ...(0, util_1.range)(0x1774, 0x177f), + ...(0, util_1.range)(0x17dd, 0x17df), + ...(0, util_1.range)(0x17ea, 0x17ff), + 0x180f, + ...(0, util_1.range)(0x181a, 0x181f), + ...(0, util_1.range)(0x1878, 0x187f), + ...(0, util_1.range)(0x18aa, 0x1dff), + ...(0, util_1.range)(0x1e9c, 0x1e9f), + ...(0, util_1.range)(0x1efa, 0x1eff), + ...(0, util_1.range)(0x1f16, 0x1f17), + ...(0, util_1.range)(0x1f1e, 0x1f1f), + ...(0, util_1.range)(0x1f46, 0x1f47), + ...(0, util_1.range)(0x1f4e, 0x1f4f), + 0x1f58, + 0x1f5a, + 0x1f5c, + 0x1f5e, + ...(0, util_1.range)(0x1f7e, 0x1f7f), + 0x1fb5, + 0x1fc5, + ...(0, util_1.range)(0x1fd4, 0x1fd5), + 0x1fdc, + ...(0, util_1.range)(0x1ff0, 0x1ff1), + 0x1ff5, + 0x1fff, + ...(0, util_1.range)(0x2053, 0x2056), + ...(0, util_1.range)(0x2058, 0x205e), + ...(0, util_1.range)(0x2064, 0x2069), + ...(0, util_1.range)(0x2072, 0x2073), + ...(0, util_1.range)(0x208f, 0x209f), + ...(0, util_1.range)(0x20b2, 0x20cf), + ...(0, util_1.range)(0x20eb, 0x20ff), + ...(0, util_1.range)(0x213b, 0x213c), + ...(0, util_1.range)(0x214c, 0x2152), + ...(0, util_1.range)(0x2184, 0x218f), + ...(0, util_1.range)(0x23cf, 0x23ff), + ...(0, util_1.range)(0x2427, 0x243f), + ...(0, util_1.range)(0x244b, 0x245f), + 0x24ff, + ...(0, util_1.range)(0x2614, 0x2615), + 0x2618, + ...(0, util_1.range)(0x267e, 0x267f), + ...(0, util_1.range)(0x268a, 0x2700), + 0x2705, + ...(0, util_1.range)(0x270a, 0x270b), + 0x2728, + 0x274c, + 0x274e, + ...(0, util_1.range)(0x2753, 0x2755), + 0x2757, + ...(0, util_1.range)(0x275f, 0x2760), + ...(0, util_1.range)(0x2795, 0x2797), + 0x27b0, + ...(0, util_1.range)(0x27bf, 0x27cf), + ...(0, util_1.range)(0x27ec, 0x27ef), + ...(0, util_1.range)(0x2b00, 0x2e7f), + 0x2e9a, + ...(0, util_1.range)(0x2ef4, 0x2eff), + ...(0, util_1.range)(0x2fd6, 0x2fef), + ...(0, util_1.range)(0x2ffc, 0x2fff), + 0x3040, + ...(0, util_1.range)(0x3097, 0x3098), + ...(0, util_1.range)(0x3100, 0x3104), + ...(0, util_1.range)(0x312d, 0x3130), + 0x318f, + ...(0, util_1.range)(0x31b8, 0x31ef), + ...(0, util_1.range)(0x321d, 0x321f), + ...(0, util_1.range)(0x3244, 0x3250), + ...(0, util_1.range)(0x327c, 0x327e), + ...(0, util_1.range)(0x32cc, 0x32cf), + 0x32ff, + ...(0, util_1.range)(0x3377, 0x337a), + ...(0, util_1.range)(0x33de, 0x33df), + 0x33ff, + ...(0, util_1.range)(0x4db6, 0x4dff), + ...(0, util_1.range)(0x9fa6, 0x9fff), + ...(0, util_1.range)(0xa48d, 0xa48f), + ...(0, util_1.range)(0xa4c7, 0xabff), + ...(0, util_1.range)(0xd7a4, 0xd7ff), + ...(0, util_1.range)(0xfa2e, 0xfa2f), + ...(0, util_1.range)(0xfa6b, 0xfaff), + ...(0, util_1.range)(0xfb07, 0xfb12), + ...(0, util_1.range)(0xfb18, 0xfb1c), + 0xfb37, + 0xfb3d, + 0xfb3f, + 0xfb42, + 0xfb45, + ...(0, util_1.range)(0xfbb2, 0xfbd2), + ...(0, util_1.range)(0xfd40, 0xfd4f), + ...(0, util_1.range)(0xfd90, 0xfd91), + ...(0, util_1.range)(0xfdc8, 0xfdcf), + ...(0, util_1.range)(0xfdfd, 0xfdff), + ...(0, util_1.range)(0xfe10, 0xfe1f), + ...(0, util_1.range)(0xfe24, 0xfe2f), + ...(0, util_1.range)(0xfe47, 0xfe48), + 0xfe53, + 0xfe67, + ...(0, util_1.range)(0xfe6c, 0xfe6f), + 0xfe75, + ...(0, util_1.range)(0xfefd, 0xfefe), + 0xff00, + ...(0, util_1.range)(0xffbf, 0xffc1), + ...(0, util_1.range)(0xffc8, 0xffc9), + ...(0, util_1.range)(0xffd0, 0xffd1), + ...(0, util_1.range)(0xffd8, 0xffd9), + ...(0, util_1.range)(0xffdd, 0xffdf), + 0xffe7, + ...(0, util_1.range)(0xffef, 0xfff8), + ...(0, util_1.range)(0x10000, 0x102ff), + 0x1031f, + ...(0, util_1.range)(0x10324, 0x1032f), + ...(0, util_1.range)(0x1034b, 0x103ff), + ...(0, util_1.range)(0x10426, 0x10427), + ...(0, util_1.range)(0x1044e, 0x1cfff), + ...(0, util_1.range)(0x1d0f6, 0x1d0ff), + ...(0, util_1.range)(0x1d127, 0x1d129), + ...(0, util_1.range)(0x1d1de, 0x1d3ff), + 0x1d455, + 0x1d49d, + ...(0, util_1.range)(0x1d4a0, 0x1d4a1), + ...(0, util_1.range)(0x1d4a3, 0x1d4a4), + ...(0, util_1.range)(0x1d4a7, 0x1d4a8), + 0x1d4ad, + 0x1d4ba, + 0x1d4bc, + 0x1d4c1, + 0x1d4c4, + 0x1d506, + ...(0, util_1.range)(0x1d50b, 0x1d50c), + 0x1d515, + 0x1d51d, + 0x1d53a, + 0x1d53f, + 0x1d545, + ...(0, util_1.range)(0x1d547, 0x1d549), + 0x1d551, + ...(0, util_1.range)(0x1d6a4, 0x1d6a7), + ...(0, util_1.range)(0x1d7ca, 0x1d7cd), + ...(0, util_1.range)(0x1d800, 0x1fffd), + ...(0, util_1.range)(0x2a6d7, 0x2f7ff), + ...(0, util_1.range)(0x2fa1e, 0x2fffd), + ...(0, util_1.range)(0x30000, 0x3fffd), + ...(0, util_1.range)(0x40000, 0x4fffd), + ...(0, util_1.range)(0x50000, 0x5fffd), + ...(0, util_1.range)(0x60000, 0x6fffd), + ...(0, util_1.range)(0x70000, 0x7fffd), + ...(0, util_1.range)(0x80000, 0x8fffd), + ...(0, util_1.range)(0x90000, 0x9fffd), + ...(0, util_1.range)(0xa0000, 0xafffd), + ...(0, util_1.range)(0xb0000, 0xbfffd), + ...(0, util_1.range)(0xc0000, 0xcfffd), + ...(0, util_1.range)(0xd0000, 0xdfffd), + 0xe0000, + ...(0, util_1.range)(0xe0002, 0xe001f), + ...(0, util_1.range)(0xe0080, 0xefffd), +]); +exports.commonly_mapped_to_nothing = new Set([ + 0x00ad, 0x034f, 0x1806, 0x180b, 0x180c, 0x180d, 0x200b, 0x200c, 0x200d, + 0x2060, 0xfe00, 0xfe01, 0xfe02, 0xfe03, 0xfe04, 0xfe05, 0xfe06, 0xfe07, + 0xfe08, 0xfe09, 0xfe0a, 0xfe0b, 0xfe0c, 0xfe0d, 0xfe0e, 0xfe0f, 0xfeff, +]); +exports.non_ASCII_space_characters = new Set([ + 0x00a0, 0x1680, + 0x2000, 0x2001, 0x2002, + 0x2003, 0x2004, + 0x2005, 0x2006, + 0x2007, 0x2008, + 0x2009, 0x200a, + 0x200b, 0x202f, + 0x205f, 0x3000, +]); +exports.prohibited_characters = new Set([ + ...exports.non_ASCII_space_characters, + ...(0, util_1.range)(0, 0x001f), + 0x007f, + ...(0, util_1.range)(0x0080, 0x009f), + 0x06dd, + 0x070f, + 0x180e, + 0x200c, + 0x200d, + 0x2028, + 0x2029, + 0x2060, + 0x2061, + 0x2062, + 0x2063, + ...(0, util_1.range)(0x206a, 0x206f), + 0xfeff, + ...(0, util_1.range)(0xfff9, 0xfffc), + ...(0, util_1.range)(0x1d173, 0x1d17a), + ...(0, util_1.range)(0xe000, 0xf8ff), + ...(0, util_1.range)(0xf0000, 0xffffd), + ...(0, util_1.range)(0x100000, 0x10fffd), + ...(0, util_1.range)(0xfdd0, 0xfdef), + ...(0, util_1.range)(0xfffe, 0xffff), + ...(0, util_1.range)(0x1fffe, 0x1ffff), + ...(0, util_1.range)(0x2fffe, 0x2ffff), + ...(0, util_1.range)(0x3fffe, 0x3ffff), + ...(0, util_1.range)(0x4fffe, 0x4ffff), + ...(0, util_1.range)(0x5fffe, 0x5ffff), + ...(0, util_1.range)(0x6fffe, 0x6ffff), + ...(0, util_1.range)(0x7fffe, 0x7ffff), + ...(0, util_1.range)(0x8fffe, 0x8ffff), + ...(0, util_1.range)(0x9fffe, 0x9ffff), + ...(0, util_1.range)(0xafffe, 0xaffff), + ...(0, util_1.range)(0xbfffe, 0xbffff), + ...(0, util_1.range)(0xcfffe, 0xcffff), + ...(0, util_1.range)(0xdfffe, 0xdffff), + ...(0, util_1.range)(0xefffe, 0xeffff), + ...(0, util_1.range)(0x10fffe, 0x10ffff), + ...(0, util_1.range)(0xd800, 0xdfff), + 0xfff9, + 0xfffa, + 0xfffb, + 0xfffc, + 0xfffd, + ...(0, util_1.range)(0x2ff0, 0x2ffb), + 0x0340, + 0x0341, + 0x200e, + 0x200f, + 0x202a, + 0x202b, + 0x202c, + 0x202d, + 0x202e, + 0x206a, + 0x206b, + 0x206c, + 0x206d, + 0x206e, + 0x206f, + 0xe0001, + ...(0, util_1.range)(0xe0020, 0xe007f), +]); +exports.bidirectional_r_al = new Set([ + 0x05be, + 0x05c0, + 0x05c3, + ...(0, util_1.range)(0x05d0, 0x05ea), + ...(0, util_1.range)(0x05f0, 0x05f4), + 0x061b, + 0x061f, + ...(0, util_1.range)(0x0621, 0x063a), + ...(0, util_1.range)(0x0640, 0x064a), + ...(0, util_1.range)(0x066d, 0x066f), + ...(0, util_1.range)(0x0671, 0x06d5), + 0x06dd, + ...(0, util_1.range)(0x06e5, 0x06e6), + ...(0, util_1.range)(0x06fa, 0x06fe), + ...(0, util_1.range)(0x0700, 0x070d), + 0x0710, + ...(0, util_1.range)(0x0712, 0x072c), + ...(0, util_1.range)(0x0780, 0x07a5), + 0x07b1, + 0x200f, + 0xfb1d, + ...(0, util_1.range)(0xfb1f, 0xfb28), + ...(0, util_1.range)(0xfb2a, 0xfb36), + ...(0, util_1.range)(0xfb38, 0xfb3c), + 0xfb3e, + ...(0, util_1.range)(0xfb40, 0xfb41), + ...(0, util_1.range)(0xfb43, 0xfb44), + ...(0, util_1.range)(0xfb46, 0xfbb1), + ...(0, util_1.range)(0xfbd3, 0xfd3d), + ...(0, util_1.range)(0xfd50, 0xfd8f), + ...(0, util_1.range)(0xfd92, 0xfdc7), + ...(0, util_1.range)(0xfdf0, 0xfdfc), + ...(0, util_1.range)(0xfe70, 0xfe74), + ...(0, util_1.range)(0xfe76, 0xfefc), +]); +exports.bidirectional_l = new Set([ + ...(0, util_1.range)(0x0041, 0x005a), + ...(0, util_1.range)(0x0061, 0x007a), + 0x00aa, + 0x00b5, + 0x00ba, + ...(0, util_1.range)(0x00c0, 0x00d6), + ...(0, util_1.range)(0x00d8, 0x00f6), + ...(0, util_1.range)(0x00f8, 0x0220), + ...(0, util_1.range)(0x0222, 0x0233), + ...(0, util_1.range)(0x0250, 0x02ad), + ...(0, util_1.range)(0x02b0, 0x02b8), + ...(0, util_1.range)(0x02bb, 0x02c1), + ...(0, util_1.range)(0x02d0, 0x02d1), + ...(0, util_1.range)(0x02e0, 0x02e4), + 0x02ee, + 0x037a, + 0x0386, + ...(0, util_1.range)(0x0388, 0x038a), + 0x038c, + ...(0, util_1.range)(0x038e, 0x03a1), + ...(0, util_1.range)(0x03a3, 0x03ce), + ...(0, util_1.range)(0x03d0, 0x03f5), + ...(0, util_1.range)(0x0400, 0x0482), + ...(0, util_1.range)(0x048a, 0x04ce), + ...(0, util_1.range)(0x04d0, 0x04f5), + ...(0, util_1.range)(0x04f8, 0x04f9), + ...(0, util_1.range)(0x0500, 0x050f), + ...(0, util_1.range)(0x0531, 0x0556), + ...(0, util_1.range)(0x0559, 0x055f), + ...(0, util_1.range)(0x0561, 0x0587), + 0x0589, + 0x0903, + ...(0, util_1.range)(0x0905, 0x0939), + ...(0, util_1.range)(0x093d, 0x0940), + ...(0, util_1.range)(0x0949, 0x094c), + 0x0950, + ...(0, util_1.range)(0x0958, 0x0961), + ...(0, util_1.range)(0x0964, 0x0970), + ...(0, util_1.range)(0x0982, 0x0983), + ...(0, util_1.range)(0x0985, 0x098c), + ...(0, util_1.range)(0x098f, 0x0990), + ...(0, util_1.range)(0x0993, 0x09a8), + ...(0, util_1.range)(0x09aa, 0x09b0), + 0x09b2, + ...(0, util_1.range)(0x09b6, 0x09b9), + ...(0, util_1.range)(0x09be, 0x09c0), + ...(0, util_1.range)(0x09c7, 0x09c8), + ...(0, util_1.range)(0x09cb, 0x09cc), + 0x09d7, + ...(0, util_1.range)(0x09dc, 0x09dd), + ...(0, util_1.range)(0x09df, 0x09e1), + ...(0, util_1.range)(0x09e6, 0x09f1), + ...(0, util_1.range)(0x09f4, 0x09fa), + ...(0, util_1.range)(0x0a05, 0x0a0a), + ...(0, util_1.range)(0x0a0f, 0x0a10), + ...(0, util_1.range)(0x0a13, 0x0a28), + ...(0, util_1.range)(0x0a2a, 0x0a30), + ...(0, util_1.range)(0x0a32, 0x0a33), + ...(0, util_1.range)(0x0a35, 0x0a36), + ...(0, util_1.range)(0x0a38, 0x0a39), + ...(0, util_1.range)(0x0a3e, 0x0a40), + ...(0, util_1.range)(0x0a59, 0x0a5c), + 0x0a5e, + ...(0, util_1.range)(0x0a66, 0x0a6f), + ...(0, util_1.range)(0x0a72, 0x0a74), + 0x0a83, + ...(0, util_1.range)(0x0a85, 0x0a8b), + 0x0a8d, + ...(0, util_1.range)(0x0a8f, 0x0a91), + ...(0, util_1.range)(0x0a93, 0x0aa8), + ...(0, util_1.range)(0x0aaa, 0x0ab0), + ...(0, util_1.range)(0x0ab2, 0x0ab3), + ...(0, util_1.range)(0x0ab5, 0x0ab9), + ...(0, util_1.range)(0x0abd, 0x0ac0), + 0x0ac9, + ...(0, util_1.range)(0x0acb, 0x0acc), + 0x0ad0, + 0x0ae0, + ...(0, util_1.range)(0x0ae6, 0x0aef), + ...(0, util_1.range)(0x0b02, 0x0b03), + ...(0, util_1.range)(0x0b05, 0x0b0c), + ...(0, util_1.range)(0x0b0f, 0x0b10), + ...(0, util_1.range)(0x0b13, 0x0b28), + ...(0, util_1.range)(0x0b2a, 0x0b30), + ...(0, util_1.range)(0x0b32, 0x0b33), + ...(0, util_1.range)(0x0b36, 0x0b39), + ...(0, util_1.range)(0x0b3d, 0x0b3e), + 0x0b40, + ...(0, util_1.range)(0x0b47, 0x0b48), + ...(0, util_1.range)(0x0b4b, 0x0b4c), + 0x0b57, + ...(0, util_1.range)(0x0b5c, 0x0b5d), + ...(0, util_1.range)(0x0b5f, 0x0b61), + ...(0, util_1.range)(0x0b66, 0x0b70), + 0x0b83, + ...(0, util_1.range)(0x0b85, 0x0b8a), + ...(0, util_1.range)(0x0b8e, 0x0b90), + ...(0, util_1.range)(0x0b92, 0x0b95), + ...(0, util_1.range)(0x0b99, 0x0b9a), + 0x0b9c, + ...(0, util_1.range)(0x0b9e, 0x0b9f), + ...(0, util_1.range)(0x0ba3, 0x0ba4), + ...(0, util_1.range)(0x0ba8, 0x0baa), + ...(0, util_1.range)(0x0bae, 0x0bb5), + ...(0, util_1.range)(0x0bb7, 0x0bb9), + ...(0, util_1.range)(0x0bbe, 0x0bbf), + ...(0, util_1.range)(0x0bc1, 0x0bc2), + ...(0, util_1.range)(0x0bc6, 0x0bc8), + ...(0, util_1.range)(0x0bca, 0x0bcc), + 0x0bd7, + ...(0, util_1.range)(0x0be7, 0x0bf2), + ...(0, util_1.range)(0x0c01, 0x0c03), + ...(0, util_1.range)(0x0c05, 0x0c0c), + ...(0, util_1.range)(0x0c0e, 0x0c10), + ...(0, util_1.range)(0x0c12, 0x0c28), + ...(0, util_1.range)(0x0c2a, 0x0c33), + ...(0, util_1.range)(0x0c35, 0x0c39), + ...(0, util_1.range)(0x0c41, 0x0c44), + ...(0, util_1.range)(0x0c60, 0x0c61), + ...(0, util_1.range)(0x0c66, 0x0c6f), + ...(0, util_1.range)(0x0c82, 0x0c83), + ...(0, util_1.range)(0x0c85, 0x0c8c), + ...(0, util_1.range)(0x0c8e, 0x0c90), + ...(0, util_1.range)(0x0c92, 0x0ca8), + ...(0, util_1.range)(0x0caa, 0x0cb3), + ...(0, util_1.range)(0x0cb5, 0x0cb9), + 0x0cbe, + ...(0, util_1.range)(0x0cc0, 0x0cc4), + ...(0, util_1.range)(0x0cc7, 0x0cc8), + ...(0, util_1.range)(0x0cca, 0x0ccb), + ...(0, util_1.range)(0x0cd5, 0x0cd6), + 0x0cde, + ...(0, util_1.range)(0x0ce0, 0x0ce1), + ...(0, util_1.range)(0x0ce6, 0x0cef), + ...(0, util_1.range)(0x0d02, 0x0d03), + ...(0, util_1.range)(0x0d05, 0x0d0c), + ...(0, util_1.range)(0x0d0e, 0x0d10), + ...(0, util_1.range)(0x0d12, 0x0d28), + ...(0, util_1.range)(0x0d2a, 0x0d39), + ...(0, util_1.range)(0x0d3e, 0x0d40), + ...(0, util_1.range)(0x0d46, 0x0d48), + ...(0, util_1.range)(0x0d4a, 0x0d4c), + 0x0d57, + ...(0, util_1.range)(0x0d60, 0x0d61), + ...(0, util_1.range)(0x0d66, 0x0d6f), + ...(0, util_1.range)(0x0d82, 0x0d83), + ...(0, util_1.range)(0x0d85, 0x0d96), + ...(0, util_1.range)(0x0d9a, 0x0db1), + ...(0, util_1.range)(0x0db3, 0x0dbb), + 0x0dbd, + ...(0, util_1.range)(0x0dc0, 0x0dc6), + ...(0, util_1.range)(0x0dcf, 0x0dd1), + ...(0, util_1.range)(0x0dd8, 0x0ddf), + ...(0, util_1.range)(0x0df2, 0x0df4), + ...(0, util_1.range)(0x0e01, 0x0e30), + ...(0, util_1.range)(0x0e32, 0x0e33), + ...(0, util_1.range)(0x0e40, 0x0e46), + ...(0, util_1.range)(0x0e4f, 0x0e5b), + ...(0, util_1.range)(0x0e81, 0x0e82), + 0x0e84, + ...(0, util_1.range)(0x0e87, 0x0e88), + 0x0e8a, + 0x0e8d, + ...(0, util_1.range)(0x0e94, 0x0e97), + ...(0, util_1.range)(0x0e99, 0x0e9f), + ...(0, util_1.range)(0x0ea1, 0x0ea3), + 0x0ea5, + 0x0ea7, + ...(0, util_1.range)(0x0eaa, 0x0eab), + ...(0, util_1.range)(0x0ead, 0x0eb0), + ...(0, util_1.range)(0x0eb2, 0x0eb3), + 0x0ebd, + ...(0, util_1.range)(0x0ec0, 0x0ec4), + 0x0ec6, + ...(0, util_1.range)(0x0ed0, 0x0ed9), + ...(0, util_1.range)(0x0edc, 0x0edd), + ...(0, util_1.range)(0x0f00, 0x0f17), + ...(0, util_1.range)(0x0f1a, 0x0f34), + 0x0f36, + 0x0f38, + ...(0, util_1.range)(0x0f3e, 0x0f47), + ...(0, util_1.range)(0x0f49, 0x0f6a), + 0x0f7f, + 0x0f85, + ...(0, util_1.range)(0x0f88, 0x0f8b), + ...(0, util_1.range)(0x0fbe, 0x0fc5), + ...(0, util_1.range)(0x0fc7, 0x0fcc), + 0x0fcf, + ...(0, util_1.range)(0x1000, 0x1021), + ...(0, util_1.range)(0x1023, 0x1027), + ...(0, util_1.range)(0x1029, 0x102a), + 0x102c, + 0x1031, + 0x1038, + ...(0, util_1.range)(0x1040, 0x1057), + ...(0, util_1.range)(0x10a0, 0x10c5), + ...(0, util_1.range)(0x10d0, 0x10f8), + 0x10fb, + ...(0, util_1.range)(0x1100, 0x1159), + ...(0, util_1.range)(0x115f, 0x11a2), + ...(0, util_1.range)(0x11a8, 0x11f9), + ...(0, util_1.range)(0x1200, 0x1206), + ...(0, util_1.range)(0x1208, 0x1246), + 0x1248, + ...(0, util_1.range)(0x124a, 0x124d), + ...(0, util_1.range)(0x1250, 0x1256), + 0x1258, + ...(0, util_1.range)(0x125a, 0x125d), + ...(0, util_1.range)(0x1260, 0x1286), + 0x1288, + ...(0, util_1.range)(0x128a, 0x128d), + ...(0, util_1.range)(0x1290, 0x12ae), + 0x12b0, + ...(0, util_1.range)(0x12b2, 0x12b5), + ...(0, util_1.range)(0x12b8, 0x12be), + 0x12c0, + ...(0, util_1.range)(0x12c2, 0x12c5), + ...(0, util_1.range)(0x12c8, 0x12ce), + ...(0, util_1.range)(0x12d0, 0x12d6), + ...(0, util_1.range)(0x12d8, 0x12ee), + ...(0, util_1.range)(0x12f0, 0x130e), + 0x1310, + ...(0, util_1.range)(0x1312, 0x1315), + ...(0, util_1.range)(0x1318, 0x131e), + ...(0, util_1.range)(0x1320, 0x1346), + ...(0, util_1.range)(0x1348, 0x135a), + ...(0, util_1.range)(0x1361, 0x137c), + ...(0, util_1.range)(0x13a0, 0x13f4), + ...(0, util_1.range)(0x1401, 0x1676), + ...(0, util_1.range)(0x1681, 0x169a), + ...(0, util_1.range)(0x16a0, 0x16f0), + ...(0, util_1.range)(0x1700, 0x170c), + ...(0, util_1.range)(0x170e, 0x1711), + ...(0, util_1.range)(0x1720, 0x1731), + ...(0, util_1.range)(0x1735, 0x1736), + ...(0, util_1.range)(0x1740, 0x1751), + ...(0, util_1.range)(0x1760, 0x176c), + ...(0, util_1.range)(0x176e, 0x1770), + ...(0, util_1.range)(0x1780, 0x17b6), + ...(0, util_1.range)(0x17be, 0x17c5), + ...(0, util_1.range)(0x17c7, 0x17c8), + ...(0, util_1.range)(0x17d4, 0x17da), + 0x17dc, + ...(0, util_1.range)(0x17e0, 0x17e9), + ...(0, util_1.range)(0x1810, 0x1819), + ...(0, util_1.range)(0x1820, 0x1877), + ...(0, util_1.range)(0x1880, 0x18a8), + ...(0, util_1.range)(0x1e00, 0x1e9b), + ...(0, util_1.range)(0x1ea0, 0x1ef9), + ...(0, util_1.range)(0x1f00, 0x1f15), + ...(0, util_1.range)(0x1f18, 0x1f1d), + ...(0, util_1.range)(0x1f20, 0x1f45), + ...(0, util_1.range)(0x1f48, 0x1f4d), + ...(0, util_1.range)(0x1f50, 0x1f57), + 0x1f59, + 0x1f5b, + 0x1f5d, + ...(0, util_1.range)(0x1f5f, 0x1f7d), + ...(0, util_1.range)(0x1f80, 0x1fb4), + ...(0, util_1.range)(0x1fb6, 0x1fbc), + 0x1fbe, + ...(0, util_1.range)(0x1fc2, 0x1fc4), + ...(0, util_1.range)(0x1fc6, 0x1fcc), + ...(0, util_1.range)(0x1fd0, 0x1fd3), + ...(0, util_1.range)(0x1fd6, 0x1fdb), + ...(0, util_1.range)(0x1fe0, 0x1fec), + ...(0, util_1.range)(0x1ff2, 0x1ff4), + ...(0, util_1.range)(0x1ff6, 0x1ffc), + 0x200e, + 0x2071, + 0x207f, + 0x2102, + 0x2107, + ...(0, util_1.range)(0x210a, 0x2113), + 0x2115, + ...(0, util_1.range)(0x2119, 0x211d), + 0x2124, + 0x2126, + 0x2128, + ...(0, util_1.range)(0x212a, 0x212d), + ...(0, util_1.range)(0x212f, 0x2131), + ...(0, util_1.range)(0x2133, 0x2139), + ...(0, util_1.range)(0x213d, 0x213f), + ...(0, util_1.range)(0x2145, 0x2149), + ...(0, util_1.range)(0x2160, 0x2183), + ...(0, util_1.range)(0x2336, 0x237a), + 0x2395, + ...(0, util_1.range)(0x249c, 0x24e9), + ...(0, util_1.range)(0x3005, 0x3007), + ...(0, util_1.range)(0x3021, 0x3029), + ...(0, util_1.range)(0x3031, 0x3035), + ...(0, util_1.range)(0x3038, 0x303c), + ...(0, util_1.range)(0x3041, 0x3096), + ...(0, util_1.range)(0x309d, 0x309f), + ...(0, util_1.range)(0x30a1, 0x30fa), + ...(0, util_1.range)(0x30fc, 0x30ff), + ...(0, util_1.range)(0x3105, 0x312c), + ...(0, util_1.range)(0x3131, 0x318e), + ...(0, util_1.range)(0x3190, 0x31b7), + ...(0, util_1.range)(0x31f0, 0x321c), + ...(0, util_1.range)(0x3220, 0x3243), + ...(0, util_1.range)(0x3260, 0x327b), + ...(0, util_1.range)(0x327f, 0x32b0), + ...(0, util_1.range)(0x32c0, 0x32cb), + ...(0, util_1.range)(0x32d0, 0x32fe), + ...(0, util_1.range)(0x3300, 0x3376), + ...(0, util_1.range)(0x337b, 0x33dd), + ...(0, util_1.range)(0x33e0, 0x33fe), + ...(0, util_1.range)(0x3400, 0x4db5), + ...(0, util_1.range)(0x4e00, 0x9fa5), + ...(0, util_1.range)(0xa000, 0xa48c), + ...(0, util_1.range)(0xac00, 0xd7a3), + ...(0, util_1.range)(0xd800, 0xfa2d), + ...(0, util_1.range)(0xfa30, 0xfa6a), + ...(0, util_1.range)(0xfb00, 0xfb06), + ...(0, util_1.range)(0xfb13, 0xfb17), + ...(0, util_1.range)(0xff21, 0xff3a), + ...(0, util_1.range)(0xff41, 0xff5a), + ...(0, util_1.range)(0xff66, 0xffbe), + ...(0, util_1.range)(0xffc2, 0xffc7), + ...(0, util_1.range)(0xffca, 0xffcf), + ...(0, util_1.range)(0xffd2, 0xffd7), + ...(0, util_1.range)(0xffda, 0xffdc), + ...(0, util_1.range)(0x10300, 0x1031e), + ...(0, util_1.range)(0x10320, 0x10323), + ...(0, util_1.range)(0x10330, 0x1034a), + ...(0, util_1.range)(0x10400, 0x10425), + ...(0, util_1.range)(0x10428, 0x1044d), + ...(0, util_1.range)(0x1d000, 0x1d0f5), + ...(0, util_1.range)(0x1d100, 0x1d126), + ...(0, util_1.range)(0x1d12a, 0x1d166), + ...(0, util_1.range)(0x1d16a, 0x1d172), + ...(0, util_1.range)(0x1d183, 0x1d184), + ...(0, util_1.range)(0x1d18c, 0x1d1a9), + ...(0, util_1.range)(0x1d1ae, 0x1d1dd), + ...(0, util_1.range)(0x1d400, 0x1d454), + ...(0, util_1.range)(0x1d456, 0x1d49c), + ...(0, util_1.range)(0x1d49e, 0x1d49f), + 0x1d4a2, + ...(0, util_1.range)(0x1d4a5, 0x1d4a6), + ...(0, util_1.range)(0x1d4a9, 0x1d4ac), + ...(0, util_1.range)(0x1d4ae, 0x1d4b9), + 0x1d4bb, + ...(0, util_1.range)(0x1d4bd, 0x1d4c0), + ...(0, util_1.range)(0x1d4c2, 0x1d4c3), + ...(0, util_1.range)(0x1d4c5, 0x1d505), + ...(0, util_1.range)(0x1d507, 0x1d50a), + ...(0, util_1.range)(0x1d50d, 0x1d514), + ...(0, util_1.range)(0x1d516, 0x1d51c), + ...(0, util_1.range)(0x1d51e, 0x1d539), + ...(0, util_1.range)(0x1d53b, 0x1d53e), + ...(0, util_1.range)(0x1d540, 0x1d544), + 0x1d546, + ...(0, util_1.range)(0x1d54a, 0x1d550), + ...(0, util_1.range)(0x1d552, 0x1d6a3), + ...(0, util_1.range)(0x1d6a8, 0x1d7c9), + ...(0, util_1.range)(0x20000, 0x2a6d6), + ...(0, util_1.range)(0x2f800, 0x2fa1d), + ...(0, util_1.range)(0xf0000, 0xffffd), + ...(0, util_1.range)(0x100000, 0x10fffd), +]); +//# sourceMappingURL=code-points-src.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.js.map new file mode 100644 index 00000000..dfb14ea8 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/code-points-src.js.map @@ -0,0 +1 @@ +{"version":3,"file":"code-points-src.js","sourceRoot":"","sources":["../src/code-points-src.ts"],"names":[],"mappings":";;;AAAA,iCAA+B;AAMlB,QAAA,sBAAsB,GAAG,IAAI,GAA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AC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,OAAO;IACP,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,OAAO;IACP,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,GAAG,IAAA,YAAK,EAAC,QAAQ,EAAE,QAAQ,CAAC;CAC7B,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts new file mode 100644 index 00000000..5a83ab24 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=generate-code-points.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts.map new file mode 100644 index 00000000..b102903e --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"generate-code-points.d.ts","sourceRoot":"","sources":["../src/generate-code-points.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.js new file mode 100644 index 00000000..c0b56ca5 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.js @@ -0,0 +1,69 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const zlib_1 = require("zlib"); +const sparse_bitfield_1 = __importDefault(require("sparse-bitfield")); +const codePoints = __importStar(require("./code-points-src")); +const fs_1 = require("fs"); +if (!process.env.GENERATE_CODE_POINTS) { + process.exitCode = 0; + process.exit(); +} +const unassigned_code_points = (0, sparse_bitfield_1.default)(); +const commonly_mapped_to_nothing = (0, sparse_bitfield_1.default)(); +const non_ascii_space_characters = (0, sparse_bitfield_1.default)(); +const prohibited_characters = (0, sparse_bitfield_1.default)(); +const bidirectional_r_al = (0, sparse_bitfield_1.default)(); +const bidirectional_l = (0, sparse_bitfield_1.default)(); +function traverse(bits, src) { + for (const code of src.keys()) { + bits.set(code, true); + } + const buffer = bits.toBuffer(); + return Buffer.concat([createSize(buffer), buffer]); +} +function createSize(buffer) { + const buf = Buffer.alloc(4); + buf.writeUInt32BE(buffer.length); + return buf; +} +const memory = []; +memory.push(traverse(unassigned_code_points, codePoints.unassigned_code_points), traverse(commonly_mapped_to_nothing, codePoints.commonly_mapped_to_nothing), traverse(non_ascii_space_characters, codePoints.non_ASCII_space_characters), traverse(prohibited_characters, codePoints.prohibited_characters), traverse(bidirectional_r_al, codePoints.bidirectional_r_al), traverse(bidirectional_l, codePoints.bidirectional_l)); +const fsStream = (0, fs_1.createWriteStream)(process.argv[2]); +fsStream.write(`import { gunzipSync } from 'zlib'; + +export default gunzipSync( + Buffer.from( + '${(0, zlib_1.gzipSync)(Buffer.concat(memory), { level: 9 }).toString('base64')}', + 'base64' + ) +); +`); +const fsStreamUncompressedData = (0, fs_1.createWriteStream)(process.argv[3]); +fsStreamUncompressedData.write(`const data = Buffer.from('${Buffer.concat(memory).toString('base64')}', 'base64');\nexport default data;\n`); +//# sourceMappingURL=generate-code-points.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.js.map new file mode 100644 index 00000000..dde7a259 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/generate-code-points.js.map @@ -0,0 +1 @@ +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AsB,EAAE,UAAU,CAAC,sBAAsB,CAAC,EACnE,QAAQ,CAAC,0BAA0B,EAAE,UAAU,CAAC,0BAA0B,CAAC,EAC3E,QAAQ,CAAC,0BAA0B,EAAE,UAAU,CAAC,0BAA0B,CAAC,EAC3E,QAAQ,CAAC,qBAAqB,EAAE,UAAU,CAAC,qBAAqB,CAAC,EACjE,QAAQ,CAAC,kBAAkB,EAAE,UAAU,CAAC,kBAAkB,CAAC,EAC3D,QAAQ,CAAC,eAAe,EAAE,UAAU,CAAC,eAAe,CAAC,CACtD,CAAC;AAEF,MAAM,QAAQ,GAAG,IAAA,sBAAiB,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACpD,QAAQ,CAAC,KAAK,CACZ;;;;OAIK,IAAA,eAAQ,EAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;;CAItE,CACA,CAAC;AAEF,MAAM,wBAAwB,GAAG,IAAA,sBAAiB,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAEpE,wBAAwB,CAAC,KAAK,CAC5B,6BAA6B,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CACzD,QAAQ,CACT,uCAAuC,CACzC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/index.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.d.ts new file mode 100644 index 00000000..24d575c5 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.d.ts @@ -0,0 +1,11 @@ +import type { createMemoryCodePoints } from './memory-code-points'; +declare function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l, }: ReturnType, input: string, opts?: { + allowUnassigned?: boolean; +}): string; +declare namespace saslprep { + export var saslprep: typeof import("."); + var _a: typeof import("."); + export { _a as default }; +} +export = saslprep; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/index.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.d.ts.map new file mode 100644 index 00000000..e53e3946 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAsCnE,iBAAS,QAAQ,CACf,EACE,sBAAsB,EACtB,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,GAChB,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,EAC5C,KAAK,EAAE,MAAM,EACb,IAAI,GAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAA;CAAO,GACvC,MAAM,CAqGR;kBAhHQ,QAAQ;;;;;AAoHjB,SAAS,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/index.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.js new file mode 100644 index 00000000..07d87bc5 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.js @@ -0,0 +1,65 @@ +"use strict"; +const getCodePoint = (character) => character.codePointAt(0); +const first = (x) => x[0]; +const last = (x) => x[x.length - 1]; +function toCodePoints(input) { + const codepoints = []; + const size = input.length; + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + codepoints.push(before); + } + return codepoints; +} +function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l, }, input, opts = {}) { + const mapping2space = non_ASCII_space_characters; + const mapping2nothing = commonly_mapped_to_nothing; + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + if (input.length === 0) { + return ''; + } + const mapped_input = toCodePoints(input) + .map((character) => (mapping2space.get(character) ? 0x20 : character)) + .filter((character) => !mapping2nothing.get(character)); + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + const normalized_map = toCodePoints(normalized_input); + const hasProhibited = normalized_map.some((character) => prohibited_characters.get(character)); + if (hasProhibited) { + throw new Error('Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3'); + } + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some((character) => unassigned_code_points.get(character)); + if (hasUnassigned) { + throw new Error('Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5'); + } + } + const hasBidiRAL = normalized_map.some((character) => bidirectional_r_al.get(character)); + const hasBidiL = normalized_map.some((character) => bidirectional_l.get(character)); + if (hasBidiRAL && hasBidiL) { + throw new Error('String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6'); + } + const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input))); + const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input))); + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + 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 normalized_input; +} +saslprep.saslprep = saslprep; +saslprep.default = saslprep; +module.exports = saslprep; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/index.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/index.js.map new file mode 100644 index 00000000..5b2b276d --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/index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,CACb,4EAA4E,CAC7E,CAAC;SACH;KACF;IAID,MAAM,UAAU,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CACnD,kBAAkB,CAAC,GAAG,CAAC,SAAS,CAAC,CAClC,CAAC;IAEF,MAAM,QAAQ,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CACjD,eAAe,CAAC,GAAG,CAAC,SAAS,CAAC,CAC/B,CAAC;IAIF,IAAI,UAAU,IAAI,QAAQ,EAAE;QAC1B,MAAM,IAAI,KAAK,CACb,8DAA8D;YAC5D,oDAAoD,CACvD,CAAC;KACH;IAQD,MAAM,cAAc,GAAG,kBAAkB,CAAC,GAAG,CAC3C,YAAY,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAE,CACvC,CAAC;IACF,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,CAC1C,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAE,CACtC,CAAC;IAEF,IAAI,UAAU,IAAI,CAAC,CAAC,cAAc,IAAI,aAAa,CAAC,EAAE;QACpD,MAAM,IAAI,KAAK,CACb,kEAAkE;YAChE,6EAA6E,CAChF,CAAC;KACH;IAED,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC7B,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;AAC5B,iBAAS,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts new file mode 100644 index 00000000..8c675a00 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts @@ -0,0 +1,11 @@ +/// +import bitfield from 'sparse-bitfield'; +export declare function createMemoryCodePoints(data: Buffer): { + unassigned_code_points: bitfield.BitFieldInstance; + commonly_mapped_to_nothing: bitfield.BitFieldInstance; + non_ASCII_space_characters: bitfield.BitFieldInstance; + prohibited_characters: bitfield.BitFieldInstance; + bidirectional_r_al: bitfield.BitFieldInstance; + bidirectional_l: bitfield.BitFieldInstance; +}; +//# sourceMappingURL=memory-code-points.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts.map new file mode 100644 index 00000000..83b7b57d --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-code-points.d.ts","sourceRoot":"","sources":["../src/memory-code-points.ts"],"names":[],"mappings":";AAAA,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AAEvC,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;;;;;;EA+BlD"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js new file mode 100644 index 00000000..05133de9 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js @@ -0,0 +1,33 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createMemoryCodePoints = void 0; +const sparse_bitfield_1 = __importDefault(require("sparse-bitfield")); +function createMemoryCodePoints(data) { + let offset = 0; + function read() { + const size = data.readUInt32BE(offset); + offset += 4; + const codepoints = data.slice(offset, offset + size); + offset += size; + return (0, sparse_bitfield_1.default)({ buffer: codepoints }); + } + const unassigned_code_points = read(); + const commonly_mapped_to_nothing = read(); + const non_ASCII_space_characters = read(); + const prohibited_characters = read(); + const bidirectional_r_al = read(); + const bidirectional_l = read(); + return { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, + }; +} +exports.createMemoryCodePoints = createMemoryCodePoints; +//# sourceMappingURL=memory-code-points.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js.map new file mode 100644 index 00000000..0bb5a144 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/memory-code-points.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-code-points.js","sourceRoot":"","sources":["../src/memory-code-points.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAuC;AAEvC,SAAgB,sBAAsB,CAAC,IAAY;IACjD,IAAI,MAAM,GAAG,CAAC,CAAC;IAKf,SAAS,IAAI;QACX,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QACvC,MAAM,IAAI,CAAC,CAAC;QAEZ,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;QACrD,MAAM,IAAI,IAAI,CAAC;QAEf,OAAO,IAAA,yBAAQ,EAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;IAC1C,CAAC;IAED,MAAM,sBAAsB,GAAG,IAAI,EAAE,CAAC;IACtC,MAAM,0BAA0B,GAAG,IAAI,EAAE,CAAC;IAC1C,MAAM,0BAA0B,GAAG,IAAI,EAAE,CAAC;IAC1C,MAAM,qBAAqB,GAAG,IAAI,EAAE,CAAC;IACrC,MAAM,kBAAkB,GAAG,IAAI,EAAE,CAAC;IAClC,MAAM,eAAe,GAAG,IAAI,EAAE,CAAC;IAE/B,OAAO;QACL,sBAAsB;QACtB,0BAA0B;QAC1B,0BAA0B;QAC1B,qBAAqB;QACrB,kBAAkB;QAClB,eAAe;KAChB,CAAC;AACJ,CAAC;AA/BD,wDA+BC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/node.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.d.ts new file mode 100644 index 00000000..0208c8ed --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.d.ts @@ -0,0 +1,10 @@ +declare function saslprep(input: string, opts?: { + allowUnassigned?: boolean; +}): string; +declare namespace saslprep { + export var saslprep: typeof import("./node"); + var _a: typeof import("./node"); + export { _a as default }; +} +export = saslprep; +//# sourceMappingURL=node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/node.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.d.ts.map new file mode 100644 index 00000000..3032ff99 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAMA,iBAAS,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAE7E;kBAFQ,QAAQ;;;;;AAOjB,SAAS,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/node.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.js new file mode 100644 index 00000000..1007f86b --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.js @@ -0,0 +1,15 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const index_1 = __importDefault(require("./index")); +const memory_code_points_1 = require("./memory-code-points"); +const code_points_data_1 = __importDefault(require("./code-points-data")); +const codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_1.default); +function saslprep(input, opts) { + return (0, index_1.default)(codePoints, input, opts); +} +saslprep.saslprep = saslprep; +saslprep.default = saslprep; +module.exports = saslprep; +//# sourceMappingURL=node.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/node.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.js.map new file mode 100644 index 00000000..107ee648 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";;;;AAAA,oDAAgC;AAChC,6DAA8D;AAC9D,0EAAsC;AAEtC,MAAM,UAAU,GAAG,IAAA,2CAAsB,EAAC,0BAAI,CAAC,CAAC;AAEhD,SAAS,QAAQ,CAAC,KAAa,EAAE,IAAoC;IACnE,OAAO,IAAA,eAAS,EAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC7B,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;AAE5B,iBAAS,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/util.d.ts b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.d.ts new file mode 100644 index 00000000..3a0466ec --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.d.ts @@ -0,0 +1,2 @@ +export declare function range(from: number, to: number): number[]; +//# sourceMappingURL=util.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/util.d.ts.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.d.ts.map new file mode 100644 index 00000000..50c71678 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAGA,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,CAQxD"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/util.js b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.js new file mode 100644 index 00000000..f679cab0 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.range = void 0; +function range(from, to) { + const list = new Array(to - from + 1); + for (let i = 0; i < list.length; i += 1) { + list[i] = from + i; + } + return list; +} +exports.range = range; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/dist/util.js.map b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.js.map new file mode 100644 index 00000000..1bab6813 --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/dist/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;AAGA,SAAgB,KAAK,CAAC,IAAY,EAAE,EAAU;IAE5C,MAAM,IAAI,GAAG,IAAI,KAAK,CAAC,EAAE,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QACvC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC;KACpB;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AARD,sBAQC"} \ No newline at end of file diff --git a/nodejs/node_modules/@mongodb-js/saslprep/package.json b/nodejs/node_modules/@mongodb-js/saslprep/package.json new file mode 100644 index 00000000..f99928fe --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/package.json @@ -0,0 +1,87 @@ +{ + "name": "@mongodb-js/saslprep", + "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013", + "keywords": [ + "sasl", + "saslprep", + "stringprep", + "rfc4013", + "4013" + ], + "author": "Dmitry Tsvettsikh ", + "publishConfig": { + "access": "public" + }, + "main": "dist/node.js", + "bugs": { + "url": "https://jira.mongodb.org/projects/COMPASS/issues", + "email": "compass@mongodb.com" + }, + "homepage": "https://github.com/mongodb-js/devtools-shared/tree/main/packages/saslprep", + "version": "1.1.5", + "repository": { + "type": "git", + "url": "https://github.com/mongodb-js/devtools-shared.git" + }, + "files": [ + "dist" + ], + "license": "MIT", + "exports": { + "browser": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + }, + "import": { + "types": "./dist/node.d.ts", + "default": "./dist/.esm-wrapper.mjs" + }, + "require": { + "types": "./dist/node.d.ts", + "default": "./dist/node.js" + } + }, + "types": "./dist/node.d.ts", + "scripts": { + "gen-code-points": "ts-node src/generate-code-points.ts src/code-points-data.ts src/code-points-data-browser.ts", + "bootstrap": "npm run compile", + "prepublishOnly": "npm run compile", + "compile": "npm run gen-code-points && tsc -p tsconfig.json && gen-esm-wrapper . ./dist/.esm-wrapper.mjs", + "typecheck": "tsc --noEmit", + "eslint": "eslint", + "prettier": "prettier", + "lint": "npm run eslint . && npm run prettier -- --check .", + "depcheck": "depcheck", + "check": "npm run typecheck && npm run lint && npm run depcheck", + "check-ci": "npm run check", + "test": "mocha", + "test-cov": "nyc -x \"**/*.spec.*\" --reporter=lcov --reporter=text --reporter=html npm run test", + "test-watch": "npm run test -- --watch", + "test-ci": "npm run test-cov", + "reformat": "npm run prettier -- --write ." + }, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "devDependencies": { + "@mongodb-js/eslint-config-devtools": "0.9.10", + "@mongodb-js/mocha-config-devtools": "^1.0.3", + "@mongodb-js/prettier-config-devtools": "^1.0.1", + "@mongodb-js/tsconfig-devtools": "^1.0.1", + "@types/chai": "^4.2.21", + "@types/mocha": "^9.0.0", + "@types/node": "^17.0.35", + "@types/sinon-chai": "^3.2.5", + "@types/sparse-bitfield": "^3.0.1", + "chai": "^4.3.6", + "depcheck": "^1.4.1", + "eslint": "^7.25.0", + "gen-esm-wrapper": "^1.1.0", + "mocha": "^8.4.0", + "nyc": "^15.1.0", + "prettier": "^2.3.2", + "sinon": "^9.2.3", + "typescript": "^5.0.4" + }, + "gitHead": "b6736f06dcac6a3891093586a554beec598997b0" +} diff --git a/nodejs/node_modules/@mongodb-js/saslprep/readme.md b/nodejs/node_modules/@mongodb-js/saslprep/readme.md new file mode 100644 index 00000000..28539eda --- /dev/null +++ b/nodejs/node_modules/@mongodb-js/saslprep/readme.md @@ -0,0 +1,29 @@ +# saslprep + +_Note: This is a fork of the original [`saslprep`](https://www.npmjs.com/package/saslprep) npm package +and provides equivalent functionality._ + +Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) + +### Usage + +```js +const saslprep = require('@mongodb-js/saslprep'); + +saslprep('password\u00AD'); // password +saslprep('password\u0007'); // Error: prohibited character +``` + +### API + +##### `saslprep(input: String, opts: Options): String` + +Normalize user name or password. + +##### `Options.allowUnassigned: bool` + +A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. + +## License + +MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/nodejs/node_modules/@types/triple-beam/LICENSE b/nodejs/node_modules/@types/triple-beam/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/nodejs/node_modules/@types/triple-beam/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/nodejs/node_modules/@types/triple-beam/README.md b/nodejs/node_modules/@types/triple-beam/README.md new file mode 100644 index 00000000..c64e6a9c --- /dev/null +++ b/nodejs/node_modules/@types/triple-beam/README.md @@ -0,0 +1,36 @@ +# Installation +> `npm install --save @types/triple-beam` + +# Summary +This package contains type definitions for triple-beam (https://github.com/winstonjs/triple-beam). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/triple-beam. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/triple-beam/index.d.ts) +````ts +export as namespace TripleBeam; + +export const LEVEL: unique symbol; +export const MESSAGE: unique symbol; +export const SPLAT: unique symbol; +export const configs: Configs; + +export interface Config { + readonly levels: { [k: string]: number }; + readonly colors: { [k: string]: string }; +} + +export interface Configs { + readonly cli: Config; + readonly npm: Config; + readonly syslog: Config; +} + +```` + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [Daniel Byrne](https://github.com/danwbyrne). diff --git a/nodejs/node_modules/@types/triple-beam/index.d.ts b/nodejs/node_modules/@types/triple-beam/index.d.ts new file mode 100644 index 00000000..3aca8b26 --- /dev/null +++ b/nodejs/node_modules/@types/triple-beam/index.d.ts @@ -0,0 +1,17 @@ +export as namespace TripleBeam; + +export const LEVEL: unique symbol; +export const MESSAGE: unique symbol; +export const SPLAT: unique symbol; +export const configs: Configs; + +export interface Config { + readonly levels: { [k: string]: number }; + readonly colors: { [k: string]: string }; +} + +export interface Configs { + readonly cli: Config; + readonly npm: Config; + readonly syslog: Config; +} diff --git a/nodejs/node_modules/@types/triple-beam/package.json b/nodejs/node_modules/@types/triple-beam/package.json new file mode 100644 index 00000000..06acdebf --- /dev/null +++ b/nodejs/node_modules/@types/triple-beam/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/triple-beam", + "version": "1.3.5", + "description": "TypeScript definitions for triple-beam", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/triple-beam", + "license": "MIT", + "contributors": [ + { + "name": "Daniel Byrne", + "githubUsername": "danwbyrne", + "url": "https://github.com/danwbyrne" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/triple-beam" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "aba808a8cd292b633d60f24f8ed117bf7f4f83771da677fe4d557c4e1ad3211b", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/nodejs/node_modules/@types/webidl-conversions/LICENSE b/nodejs/node_modules/@types/webidl-conversions/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/nodejs/node_modules/@types/webidl-conversions/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/nodejs/node_modules/@types/webidl-conversions/README.md b/nodejs/node_modules/@types/webidl-conversions/README.md new file mode 100644 index 00000000..7cd5c9d6 --- /dev/null +++ b/nodejs/node_modules/@types/webidl-conversions/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/webidl-conversions` + +# Summary +This package contains type definitions for webidl-conversions (https://github.com/jsdom/webidl-conversions#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions. + +### Additional Details + * Last updated: Tue, 07 Nov 2023 15:11:36 GMT + * Dependencies: none + +# Credits +These definitions were written by [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender). diff --git a/nodejs/node_modules/@types/webidl-conversions/index.d.ts b/nodejs/node_modules/@types/webidl-conversions/index.d.ts new file mode 100644 index 00000000..bcf395ab --- /dev/null +++ b/nodejs/node_modules/@types/webidl-conversions/index.d.ts @@ -0,0 +1,91 @@ +declare namespace WebIDLConversions { + interface Globals { + [key: string]: unknown; + + Number: (value?: unknown) => number; + String: (value?: unknown) => string; + TypeError: new(message?: string) => TypeError; + } + + interface Options { + context?: string | undefined; + globals?: Globals | undefined; + } + + interface IntegerOptions extends Options { + enforceRange?: boolean | undefined; + clamp?: boolean | undefined; + } + + interface StringOptions extends Options { + treatNullAsEmptyString?: boolean | undefined; + } + + interface BufferSourceOptions extends Options { + allowShared?: boolean | undefined; + } + + type IntegerConversion = (V: unknown, opts?: IntegerOptions) => number; + type StringConversion = (V: unknown, opts?: StringOptions) => string; + type NumberConversion = (V: unknown, opts?: Options) => number; +} + +declare const WebIDLConversions: { + any(V: V, opts?: WebIDLConversions.Options): V; + undefined(V?: unknown, opts?: WebIDLConversions.Options): void; + boolean(V: unknown, opts?: WebIDLConversions.Options): boolean; + + byte(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + octet(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + short(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + ["unsigned short"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + long(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + ["unsigned long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + ["long long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + ["unsigned long long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + double(V: unknown, opts?: WebIDLConversions.Options): number; + ["unrestricted double"](V: unknown, opts?: WebIDLConversions.Options): number; + + float(V: unknown, opts?: WebIDLConversions.Options): number; + ["unrestricted float"](V: unknown, opts?: WebIDLConversions.Options): number; + + DOMString(V: unknown, opts?: WebIDLConversions.StringOptions): string; + ByteString(V: unknown, opts?: WebIDLConversions.StringOptions): string; + USVString(V: unknown, opts?: WebIDLConversions.StringOptions): string; + + object(V: V, opts?: WebIDLConversions.Options): V extends object ? V : V & object; + ArrayBuffer( + V: unknown, + opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined }, + ): ArrayBuffer; + ArrayBuffer(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike; + DataView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): DataView; + + Int8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int8Array; + Int16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int16Array; + Int32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int32Array; + + Uint8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8Array; + Uint16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint16Array; + Uint32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint32Array; + Uint8ClampedArray(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8ClampedArray; + + Float32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float32Array; + Float64Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float64Array; + + ArrayBufferView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferView; + BufferSource( + V: unknown, + opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined }, + ): ArrayBuffer | ArrayBufferView; + BufferSource(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike | ArrayBufferView; + + DOMTimeStamp(V: unknown, opts?: WebIDLConversions.Options): number; +}; + +// This can't use ES6 style exports, as those can't have spaces in export names. +export = WebIDLConversions; diff --git a/nodejs/node_modules/@types/webidl-conversions/package.json b/nodejs/node_modules/@types/webidl-conversions/package.json new file mode 100644 index 00000000..21fdb958 --- /dev/null +++ b/nodejs/node_modules/@types/webidl-conversions/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/webidl-conversions", + "version": "7.0.3", + "description": "TypeScript definitions for webidl-conversions", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions", + "license": "MIT", + "contributors": [ + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "BendingBender", + "githubUsername": "BendingBender", + "url": "https://github.com/BendingBender" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/webidl-conversions" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "ff1514e10869784e8b7cca9c4099a4213d3f14b48c198b1bf116300df94bf608", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/nodejs/node_modules/@types/whatwg-url/LICENSE b/nodejs/node_modules/@types/whatwg-url/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/nodejs/node_modules/@types/whatwg-url/README.md b/nodejs/node_modules/@types/whatwg-url/README.md new file mode 100644 index 00000000..afba80c5 --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/whatwg-url` + +# Summary +This package contains type definitions for whatwg-url (https://github.com/jsdom/whatwg-url#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url. + +### Additional Details + * Last updated: Tue, 09 Jan 2024 19:06:33 GMT + * Dependencies: [@types/webidl-conversions](https://npmjs.com/package/@types/webidl-conversions) + +# Credits +These definitions were written by [Alexander Marks](https://github.com/aomarks), [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender). diff --git a/nodejs/node_modules/@types/whatwg-url/index.d.ts b/nodejs/node_modules/@types/whatwg-url/index.d.ts new file mode 100644 index 00000000..2922d87f --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/index.d.ts @@ -0,0 +1,169 @@ +/// +/** https://url.spec.whatwg.org/#url-representation */ +export interface URLRecord { + scheme: string; + username: string; + password: string; + host: string | number | IPv6Address | null; + port: number | null; + path: string | string[]; + query: string | null; + fragment: string | null; +} + +/** https://url.spec.whatwg.org/#concept-ipv6 */ +export type IPv6Address = [number, number, number, number, number, number, number, number]; + +/** https://url.spec.whatwg.org/#url-class */ +export class URL { + constructor(url: string, base?: string | URL); + + get href(): string; + set href(V: string); + + get origin(): string; + + get protocol(): string; + set protocol(V: string); + + get username(): string; + set username(V: string); + + get password(): string; + set password(V: string); + + get host(): string; + set host(V: string); + + get hostname(): string; + set hostname(V: string); + + get port(): string; + set port(V: string); + + get pathname(): string; + set pathname(V: string); + + get search(): string; + set search(V: string); + + get searchParams(): URLSearchParams; + + get hash(): string; + set hash(V: string); + + toJSON(): string; + + readonly [Symbol.toStringTag]: "URL"; +} + +/** https://url.spec.whatwg.org/#interface-urlsearchparams */ +export class URLSearchParams { + constructor( + init?: + | ReadonlyArray + | Iterable + | { readonly [name: string]: string } + | string, + ); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[name: string, value: string]>; + forEach( + callback: (this: THIS_ARG, value: string, name: string, searchParams: this) => void, + thisArg?: THIS_ARG, + ): void; + + readonly [Symbol.toStringTag]: "URLSearchParams"; + [Symbol.iterator](): IterableIterator<[name: string, value: string]>; +} + +/** https://url.spec.whatwg.org/#concept-url-parser */ +export function parseURL(input: string, options?: { readonly baseURL?: URLRecord | undefined }): URLRecord | null; + +/** https://url.spec.whatwg.org/#concept-basic-url-parser */ +export function basicURLParse( + input: string, + options?: { + baseURL?: URLRecord | undefined; + url?: URLRecord | undefined; + stateOverride?: StateOverride | undefined; + }, +): URLRecord | null; + +/** https://url.spec.whatwg.org/#scheme-start-state */ +export type StateOverride = + | "scheme start" + | "scheme" + | "no scheme" + | "special relative or authority" + | "path or authority" + | "relative" + | "relative slash" + | "special authority slashes" + | "special authority ignore slashes" + | "authority" + | "host" + | "hostname" + | "port" + | "file" + | "file slash" + | "file host" + | "path start" + | "path" + | "opaque path" + | "query" + | "fragment"; + +/** https://url.spec.whatwg.org/#concept-url-serializer */ +export function serializeURL(urlRecord: URLRecord, excludeFragment?: boolean): string; + +/** https://url.spec.whatwg.org/#concept-host-serializer */ +export function serializeHost(host: string | number | IPv6Address): string; + +/** https://url.spec.whatwg.org/#url-path-serializer */ +export function serializePath(urlRecord: URLRecord): string; + +/** https://url.spec.whatwg.org/#serialize-an-integer */ +export function serializeInteger(number: number): string; + +/** https://html.spec.whatwg.org#ascii-serialisation-of-an-origin */ +export function serializeURLOrigin(urlRecord: URLRecord): string; + +/** https://url.spec.whatwg.org/#set-the-username */ +export function setTheUsername(urlRecord: URLRecord, username: string): void; + +/** https://url.spec.whatwg.org/#set-the-password */ +export function setThePassword(urlRecord: URLRecord, password: string): void; + +/** https://url.spec.whatwg.org/#url-opaque-path */ +export function hasAnOpaquePath(urlRecord: URLRecord): boolean; + +/** https://url.spec.whatwg.org/#cannot-have-a-username-password-port */ +export function cannotHaveAUsernamePasswordPort(urlRecord: URLRecord): boolean; + +/** https://url.spec.whatwg.org/#percent-decode */ +export function percentDecodeBytes(buffer: TypedArray): Uint8Array; + +/** https://url.spec.whatwg.org/#percent-decode-string */ +export function percentDecodeString(string: string): Uint8Array; + +export type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | Float32Array + | Float64Array; diff --git a/nodejs/node_modules/@types/whatwg-url/lib/URL-impl.d.ts b/nodejs/node_modules/@types/whatwg-url/lib/URL-impl.d.ts new file mode 100644 index 00000000..c0bb5984 --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/lib/URL-impl.d.ts @@ -0,0 +1,22 @@ +import { Globals } from "webidl-conversions"; +import { implementation as URLSearchParamsImpl } from "./URLSearchParams-impl"; + +declare class URLImpl { + constructor(globalObject: Globals, constructorArgs: readonly [url: string, base?: string]); + + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParamsImpl; + hash: string; + + toJSON(): string; +} +export { URLImpl as implementation }; diff --git a/nodejs/node_modules/@types/whatwg-url/lib/URL.d.ts b/nodejs/node_modules/@types/whatwg-url/lib/URL.d.ts new file mode 100644 index 00000000..85474a70 --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/lib/URL.d.ts @@ -0,0 +1,66 @@ +import { URL } from "../index"; +import { implementation as URLImpl } from "./URL-impl"; + +/** + * Checks whether `obj` is a `URL` object with an implementation + * provided by this package. + */ +export function is(obj: unknown): obj is URL; + +/** + * Checks whether `obj` is a `URLImpl` WebIDL2JS implementation object + * provided by this package. + */ +export function isImpl(obj: unknown): obj is URLImpl; + +/** + * Converts the `URL` wrapper into a `URLImpl` object. + * + * @throws {TypeError} If `obj` is not a `URL` wrapper instance provided by this package. + */ +export function convert(globalObject: object, obj: unknown, { context }?: { context: string }): URLImpl; + +/** + * Creates a new `URL` instance. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URL` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function create(globalObject: object, constructorArgs: readonly [url: string, base?: string]): URL; + +/** + * Calls `create()` and returns the internal `URLImpl`. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URL` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function createImpl(globalObject: object, constructorArgs: readonly [url: string, base?: string]): URLImpl; + +/** + * Initializes the `URL` instance, called by `create()`. + * + * Useful when manually sub-classing a non-constructable wrapper object. + */ +export function setup( + obj: T, + globalObject: object, + constructorArgs: readonly [url: string, base?: string], +): T; + +/** + * Creates a new `URL` object without runing the constructor steps. + * + * Useful when implementing specifications that initialize objects + * in different ways than their constructors do. + */ +declare function _new(globalObject: object, newTarget?: new(url: string, base?: string) => URL): URLImpl; +export { _new as new }; + +/** + * Installs the `URL` constructor onto the `globalObject`. + * + * @throws {Error} If the target `globalObject` doesn't have an `Error` constructor. + */ +export function install(globalObject: object, globalNames: readonly string[]): void; diff --git a/nodejs/node_modules/@types/whatwg-url/lib/URLSearchParams-impl.d.ts b/nodejs/node_modules/@types/whatwg-url/lib/URLSearchParams-impl.d.ts new file mode 100644 index 00000000..cf507011 --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/lib/URLSearchParams-impl.d.ts @@ -0,0 +1,20 @@ +declare class URLSearchParamsImpl { + constructor( + globalObject: object, + constructorArgs: readonly [ + init?: ReadonlyArray | { readonly [name: string]: string } | string, + ], + privateData: { readonly doNotStripQMark?: boolean | undefined }, + ); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + + [Symbol.iterator](): IterableIterator<[name: string, value: string]>; +} +export { URLSearchParamsImpl as implementation }; diff --git a/nodejs/node_modules/@types/whatwg-url/lib/URLSearchParams.d.ts b/nodejs/node_modules/@types/whatwg-url/lib/URLSearchParams.d.ts new file mode 100644 index 00000000..8b35d1d1 --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/lib/URLSearchParams.d.ts @@ -0,0 +1,92 @@ +import { URLSearchParams } from "../index"; +import { implementation as URLSearchParamsImpl } from "./URLSearchParams-impl"; + +/** + * Checks whether `obj` is a `URLSearchParams` object with an implementation + * provided by this package. + */ +export function is(obj: unknown): obj is URLSearchParams; + +/** + * Checks whether `obj` is a `URLSearchParamsImpl` WebIDL2JS implementation object + * provided by this package. + */ +export function isImpl(obj: unknown): obj is URLSearchParamsImpl; + +/** + * Converts the `URLSearchParams` wrapper into a `URLSearchParamsImpl` object. + * + * @throws {TypeError} If `obj` is not a `URLSearchParams` wrapper instance provided by this package. + */ +export function convert(globalObject: object, obj: unknown, { context }?: { context: string }): URLSearchParamsImpl; + +export function createDefaultIterator( + globalObject: object, + target: URLSearchParamsImpl, + kind: TIteratorKind, +): IterableIterator; + +/** + * Creates a new `URLSearchParams` instance. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URLSearchParams` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function create( + globalObject: object, + constructorArgs?: readonly [ + init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string, + ], + privateData?: { doNotStripQMark?: boolean | undefined }, +): URLSearchParams; + +/** + * Calls `create()` and returns the internal `URLSearchParamsImpl`. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URLSearchParams` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function createImpl( + globalObject: object, + constructorArgs?: readonly [ + init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string, + ], + privateData?: { doNotStripQMark?: boolean | undefined }, +): URLSearchParamsImpl; + +/** + * Initializes the `URLSearchParams` instance, called by `create()`. + * + * Useful when manually sub-classing a non-constructable wrapper object. + */ +export function setup( + obj: T, + globalObject: object, + constructorArgs?: readonly [ + init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string, + ], + privateData?: { doNotStripQMark?: boolean | undefined }, +): T; + +/** + * Creates a new `URLSearchParams` object without runing the constructor steps. + * + * Useful when implementing specifications that initialize objects + * in different ways than their constructors do. + */ +declare function _new( + globalObject: object, + newTarget?: new( + init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string, + ) => URLSearchParams, +): URLSearchParamsImpl; +export { _new as new }; + +/** + * Installs the `URLSearchParams` constructor onto the `globalObject`. + * + * @throws {Error} If the target `globalObject` doesn't have an `Error` constructor. + */ +export function install(globalObject: object, globalNames: readonly string[]): void; diff --git a/nodejs/node_modules/@types/whatwg-url/package.json b/nodejs/node_modules/@types/whatwg-url/package.json new file mode 100644 index 00000000..eb886acc --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/package.json @@ -0,0 +1,37 @@ +{ + "name": "@types/whatwg-url", + "version": "11.0.4", + "description": "TypeScript definitions for whatwg-url", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url", + "license": "MIT", + "contributors": [ + { + "name": "Alexander Marks", + "githubUsername": "aomarks", + "url": "https://github.com/aomarks" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "BendingBender", + "githubUsername": "BendingBender", + "url": "https://github.com/BendingBender" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/whatwg-url" + }, + "scripts": {}, + "dependencies": { + "@types/webidl-conversions": "*" + }, + "typesPublisherContentHash": "3efa2ac3da0eef7a1b38bc379a0936a1d6a3f437ff481a88b01f2aa6ba5dae2e", + "typeScriptVersion": "4.6" +} \ No newline at end of file diff --git a/nodejs/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts b/nodejs/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts new file mode 100644 index 00000000..96029b76 --- /dev/null +++ b/nodejs/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts @@ -0,0 +1,4 @@ +import * as URL from "./lib/URL"; +import * as URLSearchParams from "./lib/URLSearchParams"; + +export { URL, URLSearchParams }; diff --git a/nodejs/node_modules/abstract-leveldown/.airtap.yml b/nodejs/node_modules/abstract-leveldown/.airtap.yml new file mode 100644 index 00000000..260969d1 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/.airtap.yml @@ -0,0 +1,15 @@ +browsers: + - name: chrome + version: latest + platform: Windows 10 + - name: internet explorer + version: '11' + - name: firefox + version: latest + platform: Windows 10 + - name: iphone + version: '9.0' + - name: android + version: '6.0' + - name: microsoftedge + version: latest diff --git a/nodejs/node_modules/abstract-leveldown/.travis.yml b/nodejs/node_modules/abstract-leveldown/.travis.yml new file mode 100644 index 00000000..a81ab914 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/.travis.yml @@ -0,0 +1,28 @@ +sudo: false +language: node_js + +matrix: + fast_finish: true + include: + - node_js: 6 + env: CMD=test + - node_js: 8 + env: CMD=test + - node_js: 10 + env: CMD=test + - node_js: stable + env: CMD=test-browsers + addons: + sauce_connect: true + hosts: + - airtap.local + +before_script: git fetch --tags + +script: + - DEBUG=airtap:* npm run $CMD + +after_success: npm run coverage + +notifications: + email: false diff --git a/nodejs/node_modules/abstract-leveldown/CHANGELOG.md b/nodejs/node_modules/abstract-leveldown/CHANGELOG.md new file mode 100644 index 00000000..99953c9e --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/CHANGELOG.md @@ -0,0 +1,962 @@ +# Changelog + +_**If you are upgrading:** please see [`UPGRADING.md`](UPGRADING.md)._ + +## [6.2.3] - 2020-04-03 + +### Changed + +- Upgrade `airtap` devDependency from `^2.0.0` to `^3.0.0` ([#360](https://github.com/Level/abstract-leveldown/issues/360)) ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Add `buffer` and `immediate` for browsers ([#355](https://github.com/Level/abstract-leveldown/issues/355), [#362](https://github.com/Level/abstract-leveldown/issues/362), [#363](https://github.com/Level/abstract-leveldown/issues/363)) ([**@Raynos**](https://github.com/Raynos), [**@hugomrdias**](https://github.com/hugomrdias), [**@vweevers**](https://github.com/vweevers)) + +## [6.2.2] - 2019-10-21 + +### Added + +- Add more range tests ([#353](https://github.com/Level/abstract-leveldown/issues/353)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.2.1] - 2019-10-01 + +### Fixed + +- Fix `manifest-test` to open & close its db ([#352](https://github.com/Level/abstract-leveldown/issues/352)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.2.0] - 2019-09-30 + +### Changed + +- Upgrade `hallmark` devDependency from `^1.0.0` to `^2.0.0` ([#349](https://github.com/Level/abstract-leveldown/issues/349)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `standard` devDependency from `^13.0.1` to `^14.0.0` ([#348](https://github.com/Level/abstract-leveldown/issues/348)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Add manifest ([Level/community#83](https://github.com/Level/community/issues/83)) ([#351](https://github.com/Level/abstract-leveldown/issues/351)) ([**@vweevers**](https://github.com/vweevers)) +- Document mandatory methods ([#350](https://github.com/Level/abstract-leveldown/issues/350)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.1.1] - 2019-08-18 + +### Fixed + +- Remove `process.emitWarning` because it breaks AppVeyor builds ([`8e963c3`](https://github.com/Level/abstract-leveldown/commit/8e963c3)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.1.0] - 2019-08-18 + +### Changed + +- Upgrade `hallmark` devDependency from `^0.1.0` to `^1.0.0` ([#343](https://github.com/Level/abstract-leveldown/issues/343)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `standard` devDependency from `^12.0.0` to `^13.0.1` ([#341](https://github.com/Level/abstract-leveldown/issues/341)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Add `clear()` method to delete all entries or a range ([#310](https://github.com/Level/abstract-leveldown/issues/310)) ([**@vweevers**](https://github.com/vweevers)). + +**Historical Note** The `clear()` method is experimental and optional for the time being. Please see the [README](https://github.com/Level/abstract-leveldown) for details. + +## [6.0.3] - 2019-04-26 + +### Changed + +- Upgrade `nyc` devDependency from `^13.2.0` to `^14.0.0` ([#334](https://github.com/Level/abstract-leveldown/issues/334)) ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Fix and test asynchronicity of empty batch ([#337](https://github.com/Level/abstract-leveldown/issues/337)) ([**@vweevers**](https://github.com/vweevers)) +- Fix Level badge ([`8993257`](https://github.com/Level/abstract-leveldown/commit/8993257)) ([**@vweevers**](https://github.com/vweevers)) +- Remove link to dead website ([`c0abe28`](https://github.com/Level/abstract-leveldown/commit/c0abe28)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.0.2] - 2019-03-30 + +### Changed + +- Upgrade `sinon` devDependency from `^6.0.0` to `^7.2.4` ([#330](https://github.com/Level/abstract-leveldown/issues/330)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `nyc` devDependency from `^12.0.2` to `^13.2.0` ([#327](https://github.com/Level/abstract-leveldown/issues/327)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `airtap` devDependency from `0.1.0` to `^2.0.0` ([#323](https://github.com/Level/abstract-leveldown/issues/323)) ([**@vweevers**](https://github.com/vweevers)) +- Apply common project tweaks ([#324](https://github.com/Level/abstract-leveldown/issues/324), [#325](https://github.com/Level/abstract-leveldown/issues/325)) ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Fix subtests by adding `t.plan()` ([#329](https://github.com/Level/abstract-leveldown/issues/329)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.0.1] - 2018-12-27 + +### Changed + +- Upgrade `hallmark` devDependency from `0.0.2` to `0.1.0` ([#316](https://github.com/level/abstract-leveldown/issues/316)) ([**@vweevers**](https://github.com/vweevers)) +- Split v6 upgrade guide into sections for consumers and implementors ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Remove range tests that assumed zero-length strings or Buffers meant "not defined" ([#319](https://github.com/level/abstract-leveldown/issues/319)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.0.0] - 2018-10-20 + +_If you are upgrading, please consult the [Upgrade Guide](UPGRADING.md#v6)._ + +### Changed + +- Upgrade `airtap` devDependency from `0.0.5` to `0.1.0` ([#229](https://github.com/level/abstract-leveldown/issues/229), [#231](https://github.com/level/abstract-leveldown/issues/231), [#245](https://github.com/level/abstract-leveldown/issues/245), [`029f56a`](https://github.com/level/abstract-leveldown/commit/029f56a), [#252](https://github.com/level/abstract-leveldown/issues/252)) ([**@vweevers**](https://github.com/vweevers), [**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `sinon` devDependency from `^5.0.0` to `^6.0.0` ([#232](https://github.com/level/abstract-leveldown/issues/232)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `standard` devDependency from `^11.0.0` to `^12.0.0` ([#303](https://github.com/level/abstract-leveldown/issues/303)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Reject nullish values ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) +- Make default `_serializeKey` and `_serializeValue` identity functions ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) +- Don't coerce keys to strings to check if they're empty, instead check arrays explicitly ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) +- Make `db` property mandatory and public on iterator and chained batch ([#257](https://github.com/level/abstract-leveldown/issues/257), [#309](https://github.com/level/abstract-leveldown/issues/309)) ([**@vweevers**](https://github.com/vweevers)) +- Align `AbstractChainedBatch#_clear` with `_put` and `_del` ([#257](https://github.com/level/abstract-leveldown/issues/257)) ([**@vweevers**](https://github.com/vweevers)) +- Add `AbstractChainedBatch#_write` with options ([#257](https://github.com/level/abstract-leveldown/issues/257)) ([**@vweevers**](https://github.com/vweevers)) +- Use `level-concat-iterator` instead of `collectEntries` ([#246](https://github.com/level/abstract-leveldown/issues/246)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Document API and test suite ([#251](https://github.com/level/abstract-leveldown/issues/251), [#290](https://github.com/level/abstract-leveldown/issues/290), [#295](https://github.com/level/abstract-leveldown/issues/295), [#296](https://github.com/level/abstract-leveldown/issues/296), [#305](https://github.com/level/abstract-leveldown/issues/305)) ([**@vweevers**](https://github.com/vweevers)) +- Export test suite as a single function ([#271](https://github.com/level/abstract-leveldown/issues/271), [#293](https://github.com/level/abstract-leveldown/issues/293), [#297](https://github.com/level/abstract-leveldown/issues/297)) ([**@vweevers**](https://github.com/vweevers), [**@ralphtheninja**](https://github.com/ralphtheninja)) +- Use factory function to create `db` instances in test suite ([#258](https://github.com/level/abstract-leveldown/issues/258), [#268](https://github.com/level/abstract-leveldown/issues/268), [#282](https://github.com/level/abstract-leveldown/issues/282)) ([**@ralphtheninja**](https://github.com/ralphtheninja), [**@vweevers**](https://github.com/vweevers)) +- Isolate snapshot tests so that they can be skipped ([#239](https://github.com/level/abstract-leveldown/issues/239), [#274](https://github.com/level/abstract-leveldown/issues/274)) ([**@vweevers**](https://github.com/vweevers), [**@ralphtheninja**](https://github.com/ralphtheninja)) +- Isolate openAdvanced tests so that they can be skipped ([#271](https://github.com/level/abstract-leveldown/issues/271)) ([**@vweevers**](https://github.com/vweevers)) +- Rename `abstract/` to `test/` ([#253](https://github.com/level/abstract-leveldown/issues/253)) ([**@vweevers**](https://github.com/vweevers)) +- Refactor internal test methods to have the same signature `(test, testCommon)` ([#268](https://github.com/level/abstract-leveldown/issues/268), [#275](https://github.com/level/abstract-leveldown/issues/275)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Prefer `exports.*` over `module.exports.*` ([#276](https://github.com/level/abstract-leveldown/issues/276)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Tweak copyright years for less maintenance ([`0b2949a`](https://github.com/level/abstract-leveldown/commit/0b2949a)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Add `iterator#seek()` ([#237](https://github.com/level/abstract-leveldown/issues/237), [#302](https://github.com/level/abstract-leveldown/issues/302), [#307](https://github.com/level/abstract-leveldown/issues/307)) ([**@vweevers**](https://github.com/vweevers), [**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `nyc` and `coveralls` devDependencies for code coverage ([#253](https://github.com/level/abstract-leveldown/issues/253)) ([**@vweevers**](https://github.com/vweevers)) +- Add `setUp` and `tearDown` to all sub tests ([#279](https://github.com/level/abstract-leveldown/issues/279), [#289](https://github.com/level/abstract-leveldown/issues/289)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add test for implementations that cannot support snapshots ([#239](https://github.com/level/abstract-leveldown/issues/239)) ([**@vweevers**](https://github.com/vweevers)) +- Add `hallmark` devDependency for Markdown style and contributors ([#312](https://github.com/level/abstract-leveldown/issues/312)) ([**@vweevers**](https://github.com/vweevers)) + +### Removed + +- Remove `location` ([#258](https://github.com/level/abstract-leveldown/issues/258)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove `lastLocation`, `cleanup`, `rimraf` ([#249](https://github.com/level/abstract-leveldown/issues/249)) ([**@vweevers**](https://github.com/vweevers)) +- Remove IE10 from Sauce Labs test matrix ([#312](https://github.com/level/abstract-leveldown/issues/312)) ([**@vweevers**](https://github.com/vweevers)) +- Remove node 9 from Travis ([`0b52395`](https://github.com/level/abstract-leveldown/commit/0b52395)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove tests that assumed support of boolean and NaN keys ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) +- Remove range tests that assumed `null` meant "not defined" ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) +- Remove sync test from `test/put-test.js` ([#300](https://github.com/level/abstract-leveldown/issues/300)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove empty `errorValues()` test ([#273](https://github.com/level/abstract-leveldown/issues/273)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove default `testCommon` parameter ([#264](https://github.com/level/abstract-leveldown/issues/264), [#271](https://github.com/level/abstract-leveldown/issues/271)) ([**@vweevers**](https://github.com/vweevers)) +- Remove `contributors` from `package.json` ([`542f350`](https://github.com/level/abstract-leveldown/commit/542f350)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove copyright headers from code ([`a36c04f`](https://github.com/level/abstract-leveldown/commit/a36c04f)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Make sure all `t.throw` tests check error messages correctly ([#286](https://github.com/level/abstract-leveldown/issues/286)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Check options objects properly for `null` ([#257](https://github.com/level/abstract-leveldown/issues/257), [#288](https://github.com/level/abstract-leveldown/issues/288)) ([**@ralphtheninja**](https://github.com/ralphtheninja), [**@vweevers**](https://github.com/vweevers)) +- Serialize range options same as keys ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) +- Allow nullish and empty range options ([#277](https://github.com/level/abstract-leveldown/issues/277)) ([**@vweevers**](https://github.com/vweevers)) + +## [5.0.0] - 2018-05-22 + +### Changed + +- Upgrade `sinon` to `^5.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Tweak README ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Replace `const` with `var` to support IE10 ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Add node 10 to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `airtap` for browser tests ([**@vweevers**](https://github.com/vweevers)) + +### Removed + +- Remove node 4, 5 and 7 from Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove TypeScript tests ([**@vweevers**](https://github.com/vweevers)) +- Remove TypeScript typings ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [4.0.3] - 2018-02-21 + +### Changed + +- Upgrade `ts-node` to `^5.0.0` ([**@zixia**](https://github.com/zixia)) +- Upgrade `standard` to `^11.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Remove invalid TypeScript from `Batch` ([**@Tapppi**](https://github.com/Tapppi)) +- Add JSDoc to incorrectly inferred TypeScript types ([**@Tapppi**](https://github.com/Tapppi)) + +## [4.0.2] - 2018-02-09 + +### Fixed + +- Fix `iterator#next` to return `this` ([**@vweevers**](https://github.com/vweevers)) + +## [4.0.1] - 2018-02-09 + +### Added + +- Run test suite in TypeScript in addition to Node.js ([**@vweevers**](https://github.com/vweevers)) +- Add TypeScript smoke test ([**@vweevers**](https://github.com/vweevers)) +- Add TypeScript readme section with stability badge ([**@vweevers**](https://github.com/vweevers)) + +### Removed + +- Remove obsolete parameters from tests ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Update TypeScript typings for v4 ([**@vweevers**](https://github.com/vweevers)) +- Use ES6 classes in tests to please TypeScript ([**@vweevers**](https://github.com/vweevers)) +- Define default methods on prototype to please TypeScript ([**@vweevers**](https://github.com/vweevers)) + +**Historical Note** This was released as a patch because it only changed tests +and TypeScript typings (which are marked experimental and don't follow semver). + +## [4.0.0] - 2018-01-20 + +### Changed + +- Ignore empty range options in `AbstractLevelDOWN#_setupIteratorOptions` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Make `testCommon.js` the default value for `testCommon` parameter ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Use `Buffer.isBuffer()` instead of `AbstractLevelDOWN#isBuffer` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Cleanup iterator tests ([#161](https://github.com/level/abstract-leveldown/issues/161)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Pass test function as a parameter instead of setting local global ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Assert batch type is `'put'` or `'del'` ([**@vweevers**](https://github.com/vweevers)) +- Assert batch array elements are objects ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Add `standard` for linting ([#150](https://github.com/level/abstract-leveldown/issues/150)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Test that callbacks are called asynchronously ([**@vweevers**](https://github.com/vweevers)) +- Test serialization extensibility ([**@vweevers**](https://github.com/vweevers)) +- Add [**@vweevers**](https://github.com/vweevers) to contributors ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add upgrade guide in `UPGRADING.md` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add node 9 to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove `isLevelDOWN` function and corresponding tests ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove `AbstractLevelDOWN#approximateSize` method and corresponding tests ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove `testBuffer` in `abstract/put-get-del-test.js` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove object value test in `abstract/put-test.js` ([**@vweevers**](https://github.com/vweevers)) +- Remove serialize buffer tests ([**@vweevers**](https://github.com/vweevers)) +- Remove serialize object tests ([**@vweevers**](https://github.com/vweevers)) +- Remove `BufferType` parameter in `abstract/put-get-del-test.js`, use `Buffer` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Ensure stores are closed properly (fixes problems on Windows) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Call back errors on next tick to avoid `zalgo` ([**@vweevers**](https://github.com/vweevers)) + +## [3.0.0] - 2017-11-04 + +### Added + +- Add node version badge ([**@vweevers**](https://github.com/vweevers)) + +### Removed + +- Drop support for `0.12`. Cause for new major version! ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Fix errors in `index.d.ts` ([**@sandersn**](https://github.com/sandersn)) + +## [2.7.2] - 2017-10-11 + +### Changed + +- Update `README` with new style ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.7.1] - 2017-09-30 + +### Changed + +- Refactor typings as ES2015 module ([**@MeirionHughes**](https://github.com/MeirionHughes)) + +## [2.7.0] - 2017-09-12 + +### Added + +- Add `TypeScript` definitions in `index.d.ts` ([**@MeirionHughes**](https://github.com/MeirionHughes)) + +## [2.6.3] - 2017-09-05 + +### Changed + +- Upgrade dependencies ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Convert nullish values to empty strings ([**@bigeasy**](https://github.com/bigeasy)) +- Use `t.equal(a, b)` instead of `t.ok(a === b)` ([**@bigeasy**](https://github.com/bigeasy)) +- Relax tests for serializing object in `abstract/chained-batch-test.js` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Add `GreenKeeper` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Test key/value serialization ([**@bigeasy**](https://github.com/bigeasy)) +- Test `undefined` value serializing to empty string ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Document `.status` property ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.6.2] - 2017-07-30 + +### Changed + +- Upgrade dependencies and float `devDependencies` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update copyright years ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update node versions on Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Test serialization extensibility ([**@juliangruber**](https://github.com/juliangruber)) + +### Fixed + +- Fix put test on object serialization ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.6.1] - 2016-09-12 + +### Fixed + +- Fix `null` case in default value serializer (fixes problems in `2.6.0`) ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.6.0] - 2016-03-10 + +### Changed + +- Use proto delegation to patch methods on db ([**@deanlandolt**](https://github.com/deanlandolt)) +- Allow serialization functions to return buffers ([**@deanlandolt**](https://github.com/deanlandolt)) + +### Added + +- Add `collectBatchOps` function to buffer `_put` and `_del` inputs in `abstract/chained-batch-test.js` ([**@deanlandolt**](https://github.com/deanlandolt)) + +### Removed + +- Remove unnecessary initialization hackery in `abstract/chained-batch-test.js` ([**@deanlandolt**](https://github.com/deanlandolt)) + +**Historical Note** This release was a breaking change. See [**@juliangruber**](https://github.com/juliangruber)'s [comment](https://github.com/Level/abstract-leveldown/pull/85#issuecomment-246980978) for more information. + +## [2.5.0] - 2016-05-01 + +### Changed + +- Upgrade dependencies and add more node versions to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Add dependency badge to `README` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `AbstractLevelDOWN#_serializeKey` ([**@juliangruber**](https://github.com/juliangruber)) +- Add `AbstractLevelDOWN#_serializeValue` ([**@juliangruber**](https://github.com/juliangruber)) +- Add `AbstractChainedBatch#_serializeKey` ([**@juliangruber**](https://github.com/juliangruber)) +- Add `AbstractChainedBatch#_serializeValue` ([**@juliangruber**](https://github.com/juliangruber)) +- Test `_serialize` with object and buffer ([**@juliangruber**](https://github.com/juliangruber)) + +### Removed + +- Remove stringification of keys and values ([**@juliangruber**](https://github.com/juliangruber)) +- Remove `.toBuffer` ([**@juliangruber**](https://github.com/juliangruber)) + +### Fixed + +- Update `memdown` url ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- `AbstractLevelDOWN#._checkKey` does not take three parameters ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Only show build status for the master branch ([**@watson**](https://github.com/watson)) +- Fix minor typos in `README` ([**@timkuijsten**](https://github.com/timkuijsten)) + +## [2.4.1] - 2015-08-29 + +### Fixed + +- Remove use of `const` ([**@nolanlawson**](https://github.com/nolanlawson)) + +## [2.4.0] - 2015-05-19 + +### Added + +- Add `.status` property to `AbstractLevelDOWN` ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.3.1] - 2015-05-18 + +### Added + +- Link to `level/community` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Extract `Contributors` section from `README` into `level/community` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Document `isLevelDown` function ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.3.0] - 2015-05-18 + +### Changed + +- Use `t.equal(a, b)` instead of `t.ok(a === b)` ([**@juliangruber**](https://github.com/juliangruber)) +- Export API from `index.js` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Import `isLevelDOWN` function to `is-leveldown.js` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.2.2] - 2015-05-13 + +### Fixed + +- Revert changes to `location` in `2.2.1` ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.2.1] - 2015-05-12 + +### Fixed + +- Copy paste error gave wrong test description ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- `t.throws()` is different for `tape` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Assert `location` is not an empty string ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.2.0] - 2015-05-10 + +### Added + +- Test `{ sync: true }` option in `abstract/put-test.js` ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.1.4] - 2015-04-28 + +### Fixed + +- Use `t.equal()` with `tape` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.1.3] - 2015-04-28 + +### Changed + +- Change from `tap` to `tape` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.1.2] - 2015-04-27 + +### Changed + +- Convert buffer to string so we can compare ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.1.1] - 2015-04-27 + +### Changed + +- Update logo and copyright ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Add [**@ralphtheninja**](https://github.com/ralphtheninja) to contributors ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `0.12` and `iojs` to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Include `.nonErrorValues()` test in `abstract/put-get-del-test.js` ([**@hden**](https://github.com/hden)) +- `rvagg/node-abstract-leveldown` moved to `level/abstract-leveldown` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Fix Travis for `0.8` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.1.0] - 2014-11-09 + +### Changed + +- Use `setTimeout` instead of `process.nextTick` ([**@bigeasy**](https://github.com/bigeasy)) + +### Added + +- Add [**@watson**](https://github.com/watson) to contributors ([**@rvagg**](https://github.com/rvagg)) + +### Fixed + +- Don't fail if no value is returned by `._get` ([**@watson**](https://github.com/watson)) +- Use `error` test function when testing for errors ([**@watson**](https://github.com/watson)) + +## [2.0.3] - 2014-10-02 + +No change. + +## [2.0.2] - 2014-10-02 + +### Added + +- Test atomic batch operations ([**@calvinmetcalf**](https://github.com/calvinmetcalf)) + +## [2.0.1] - 2014-09-01 + +### Changed + +- Set default values for options to `.open`, `.get`, `.put`, `.del` and `.batch` ([**@watson**](https://github.com/watson)) +- Update pattern for setting default options for the iterator ([**@watson**](https://github.com/watson)) +- Allow boolean options to be falsy/truthy ([**@watson**](https://github.com/watson)) + +### Removed + +- Remove default options that are too `LevelDOWN` specific ([**@watson**](https://github.com/watson)) + +## [2.0.0] - 2014-08-26 + +### Changed + +- Switch to allowing writes of empty values, `null`, `undefined`, `''`, `[]` and empty buffer ([**@juliangruber**](https://github.com/juliangruber)) +- Rename `AbstractLevelDOWN#_checkKeyValue` to `AbstractLevelDOWN#_checkKey` ([**@rvagg**](https://github.com/rvagg)) + +## [1.0.0] - 2014-08-24 + +### Changed + +- Ensure `Boolean` iterator options are `Boolean` ([**@watson**](https://github.com/watson)) + +### Added + +- Test that an error is thrown when location isn't a string ([**@calvinmetcalf**](https://github.com/calvinmetcalf)) +- Test opening and closing the store ([**@calvinmetcalf**](https://github.com/calvinmetcalf)) +- Test iterator with `limit` set to `0` ([**@watson**](https://github.com/watson)) +- Add more tests to `abstract/batch-test.js` ([**@calvinmetcalf**](https://github.com/calvinmetcalf)) +- Set default values of iterator options ([**@watson**](https://github.com/watson)) +- Account for batch options that are `null` ([**@calvinmetcalf**](https://github.com/calvinmetcalf)) + +### Removed + +- Remove options.start hackery ([**@rvagg**](https://github.com/rvagg)) + +## [0.12.4] - 2014-08-20 + +### Changed + +- Change license to plain MIT ([**@andrewrk**](https://github.com/andrewrk)) + +### Added + +- Test that `simple-iterator` returns buffers ([**@kesla**](https://github.com/kesla)) +- Test implicit snapshots ([**@kesla**](https://github.com/kesla)) + +## [0.12.3] - 2014-06-27 + +### Changed + +- Upgrade `xtend` dependency ([**@andrewrk**](https://github.com/andrewrk)) + +## [0.12.2] - 2014-04-26 + +### Changed + +- Have `isTypedArray` check for existence of `ArrayBuffer` and `Uint8Array` constructors before usage ([**@rvagg**](https://github.com/rvagg)) + +## [0.12.1] - 2014-04-26 + +### Changed + +- Set default `BufferType` in `abstract/put-get-del-test.js` to `Buffer` instead of `ArrayBuffer` ([**@maxogden**](https://github.com/maxogden)) + +## [0.12.0] - 2014-03-12 + +### Changed + +- Revert to pure `Buffer` and remove usage of `Uint16Array` ([**@rvagg**](https://github.com/rvagg)) + +## [0.11.4] - 2014-03-11 + +### Removed + +- Remove duplicate call to `t.end()` ([**@maxogden**](https://github.com/maxogden)) + +## [0.11.3] - 2014-01-26 + +### Changed + +- Loosen the buffer type check ([**@rvagg**](https://github.com/rvagg)) + +## [0.11.2] - 2013-12-05 + +### Added + +- Add npm badges ([**@rvagg**](https://github.com/rvagg)) + +### Fixed + +- Fix iterator tests in `test.js` ([**@rvagg**](https://github.com/rvagg)) + +## [0.11.1] - 2013-11-15 + +### Changed + +- Adjust `abstract/approximate-size-test.js` to account for snappy compression ([**@rvagg**](https://github.com/rvagg)) + +## [0.11.0] - 2013-10-14 + +### Added + +- Normalize `iterator()` options with `AbstractLevelDOWN#_setupIteratorOptions` ([**@rvagg**](https://github.com/rvagg)) + +## [0.10.2] - 2013-09-06 + +### Changed + +- Refactor duplicated versions of `isTypedArray` into `abstract/util.js` ([**@rvagg**](https://github.com/rvagg)) +- Refactor duplicated versions of `'NotFound'` checks into `abstract/util.js`, fixed too-strict version in `get-test.js` ([**@rvagg**](https://github.com/rvagg)) + +## [0.10.1] - 2013-08-29 + +### Changed + +- Relax check for `Not Found` error message to be case insensitive in `get-test.js` ([**@rvagg**](https://github.com/rvagg)) + +### Added + +- Add [**@substack**](https://github.com/substack) to contributors ([**@rvagg**](https://github.com/rvagg)) + +## [0.10.0] - 2013-08-19 + +### Added + +- Test `gt`, `gte`, `lt` and `lte` ranges ([**@dominictarr**](https://github.com/dominictarr)) + +## [0.9.0] - 2013-08-11 + +### Changed + +- Make `AbstractChainedBatch` extensible ([**@kesla**](https://github.com/kesla)) +- Export `AbstractChainedBatch` from `abstract-leveldown.js` ([**@kesla**](https://github.com/kesla)) + +### Added + +- Test simultaneous get's ([**@kesla**](https://github.com/kesla)) +- Test `AbstractChainedBatch` extensibility ([**@kesla**](https://github.com/kesla)) + +### Fixed + +- Fix broken test assertion in `abstract/get-test.js` ([**@rvagg**](https://github.com/rvagg)) +- Fix tests that weren't running properly ([**@kesla**](https://github.com/kesla)) + +## [0.8.2] - 2013-08-02 + +No changes. Merely published changes made in `0.8.1`. + +## [0.8.1] - 2013-08-02 + +### Changed + +- Remove use of `const` in `testCommon.js` ([**@rvagg**](https://github.com/rvagg)) + +**Historical Note** The version in `package.json` was changed from `0.7.4` to `0.8.1`. The `0.8.1` tag exists but this version was never published to npm. + +## [0.8.0] - 2013-08-02 + +### Changed + +- Use `process.browser` check instead of `process.title == 'browser'` ([**@rvagg**](https://github.com/rvagg)) + +### Added + +- Add `BufferType` parameter to `abstract/put-get-del-test.js` for `bops` support ([**@rvagg**](https://github.com/rvagg)) +- Add `isTypedArray` function which checks `ArrayBuffer` or `Uint8Array` for `bops` support ([**@rvagg**](https://github.com/rvagg)) + +### Fixed + +- Fix `cleanup` function not calling back when browserified ([**@rvagg**](https://github.com/rvagg)) + +**Historical Note** It seems the version in `package.json` was never changed to `0.8.0` in the git history, even though the `0.8.0` tag exists. Most likely `package.json` was modified locally during `npm publish` but was never committed. + +## [0.7.4] - 2013-08-02 + +### Fixed + +- Fix problems related to `browserify` and `rimraf` ([**@rvagg**](https://github.com/rvagg)) + +## [0.7.3] - 2013-07-26 + +### Added + +- Add [**@pgte**](https://github.com/pgte) to contributors ([**@rvagg**](https://github.com/rvagg)) +- Test iterator with `limit` set to `-1` ([**@kesla**](https://github.com/kesla)) + +## [0.7.2] - 2013-07-08 + +### Changed + +- Freeze chained batch state after `.write()` has been called ([**@rvagg**](https://github.com/rvagg)) +- Make `NotFound` error case insensitive ([**@rvagg**](https://github.com/rvagg)) +- Use `self` rather than binding functions to `this` ([**@juliangruber**](https://github.com/juliangruber)) + +### Added + +- Add `AbstractChainedBatch#_checkWritten` ([**@rvagg**](https://github.com/rvagg)) +- Test delete on non-existent key ([**@rvagg**](https://github.com/rvagg)) +- Test iterator with `start` after database `end` ([**@juliangruber**](https://github.com/juliangruber)) + +### Fixed + +- Don't coerce values to strings in browser ([**@maxogden**](https://github.com/maxogden)) +- Make tests work in node and browser ([**@maxogden**](https://github.com/maxogden)) + +## [0.7.1] - 2013-05-15 + +### Changed + +- Adjust tests to be browserable ([**@rvagg**](https://github.com/rvagg)) + +## [0.7.0] - 2013-05-14 + +### Added + +- Add `AbstractChainedBatch#clear` ([**@rvagg**](https://github.com/rvagg)) + +## [0.6.1] - 2013-05-14 + +### Changed + +- Make `AbstractIterator` call back with an error instead of throwing on nexting and ending ([**@mcollina**](https://github.com/mcollina)) + +## [0.6.0] - 2013-05-14 + +### Changed + +- Split `t.deepEqual()` into multiple `t.equal()` in `abstract/iterator-test.js` ([**@rvagg**](https://github.com/rvagg)) +- Make `AbstractIterator` call back with an error instead of throwing on nexting and ending ([**@mcollina**](https://github.com/mcollina)) + +## [0.5.0] - 2013-05-14 + +### Changed + +- Make `iterator.end(cb)` and `iterator.next(cb)` call back with an error instead of throwing ([**@mcollina**](https://github.com/mcollina)) + +## [0.4.0] - 2013-05-14 + +### Changed + +- Move `AbstractIterator` from `abstract-leveldown.js` to `abstract-iterator.js` ([**@rvagg**](https://github.com/rvagg)) + +### Added + +- Add `AbstractChainedBatch` ([**@rvagg**](https://github.com/rvagg)) +- Add `AbstractLevelDOWN#_chainedBatch` ([**@rvagg**](https://github.com/rvagg)) +- Add `abstract/batch-test.js` and `abstract/chained-batch-test.js` ([**@rvagg**](https://github.com/rvagg)) + +## [0.4.0-1] - 2013-05-14 + +### Added + +- Add [**@No9**](https://github.com/No9) and [**@mcollina**](https://github.com/mcollina) to contributors ([**@rvagg**](https://github.com/rvagg)) + +## [0.3.0] - 2013-05-04 + +### Changed + +- Use `this._checkKeyValue()` instead of local function ([**@rvagg**](https://github.com/rvagg)) +- Use `this._isBuffer()` instead of `Buffer.isBuffer()` ([**@rvagg**](https://github.com/rvagg)) + +### Added + +- Restore test for opening the database without options ([**@rvagg**](https://github.com/rvagg)) +- Add `AbstractLevelDOWN#_isBuffer` so it can be overridden ([**@rvagg**](https://github.com/rvagg)) +- Add `AbstractLevelDOWN#_checkKeyValue` so it can be overridden ([**@rvagg**](https://github.com/rvagg)) + +## [0.2.3] - 2013-05-04 + +### Removed + +- Remove test for opening the database without options ([**@rvagg**](https://github.com/rvagg)) + +## [0.2.2] - 2013-05-04 + +### Changed + +- Split `.open()` tests into `.open()` and `.openAdvanced()` ([**@rvagg**](https://github.com/rvagg)) + +## [0.2.1] - 2013-05-04 + +### Changed + +- Convert values to `string` in `abstract/put-get-del-test.js` if `Buffer` is `undefined` ([**@rvagg**](https://github.com/rvagg)) + +## [0.2.0] - 2013-05-04 + +### Changed + +- Convert values to `string` in `abstract/get-test.js` if `Buffer` is `undefined` ([**@rvagg**](https://github.com/rvagg)) +- Don't stringify keys and values in `abstract/iterator-test.js` ([**@maxogden**](https://github.com/maxogden)) + +### Added + +- Add `process.browser` check for `start` and `end` keys in browser ([**@maxogden**](https://github.com/maxogden)) +- Add `levelup` contributors ([**@rvagg**](https://github.com/rvagg)) + +### Fixed + +- Fix `tape` compatibility issues ([**@maxogden**](https://github.com/maxogden)) + +## [0.1.0] - 2013-04-23 + +### Added + +- Import abstract tests from `leveldown` ([**@maxogden**](https://github.com/maxogden)) + +### Fixed + +- Clarify `README` ([**@rvagg**](https://github.com/rvagg)) + +## [0.0.2] - 2013-03-18 + +### Changed + +- Export `checkKeyValue` ([**@rvagg**](https://github.com/rvagg)) + +### Added + +- Add node 0.10 to Travis ([**@rvagg**](https://github.com/rvagg)) +- Add `Buffer.isBuffer()` checks to keys and values ([**@rvagg**](https://github.com/rvagg)) + +## [0.0.1] - 2013-03-18 + +### Added + +- Add `checkKeyValue` function for more complete error checking ([**@rvagg**](https://github.com/rvagg)) + +## 0.0.0 - 2013-03-15 + +First release. :seedling: + +[6.2.3]: https://github.com/Level/abstract-leveldown/compare/v6.2.2...v6.2.3 + +[6.2.2]: https://github.com/Level/abstract-leveldown/compare/v6.2.1...v6.2.2 + +[6.2.1]: https://github.com/Level/abstract-leveldown/compare/v6.2.0...v6.2.1 + +[6.2.0]: https://github.com/Level/abstract-leveldown/compare/v6.1.1...v6.2.0 + +[6.1.1]: https://github.com/Level/abstract-leveldown/compare/v6.1.0...v6.1.1 + +[6.1.0]: https://github.com/Level/abstract-leveldown/compare/v6.0.3...v6.1.0 + +[6.0.3]: https://github.com/Level/abstract-leveldown/compare/v6.0.2...v6.0.3 + +[6.0.2]: https://github.com/Level/abstract-leveldown/compare/v6.0.1...v6.0.2 + +[6.0.1]: https://github.com/Level/abstract-leveldown/compare/v6.0.0...v6.0.1 + +[6.0.0]: https://github.com/Level/abstract-leveldown/compare/v5.0.0...v6.0.0 + +[5.0.0]: https://github.com/Level/abstract-leveldown/compare/v4.0.3...v5.0.0 + +[4.0.3]: https://github.com/Level/abstract-leveldown/compare/v4.0.2...v4.0.3 + +[4.0.2]: https://github.com/Level/abstract-leveldown/compare/v4.0.1...v4.0.2 + +[4.0.1]: https://github.com/Level/abstract-leveldown/compare/v4.0.0...v4.0.1 + +[4.0.0]: https://github.com/Level/abstract-leveldown/compare/v3.0.0...v4.0.0 + +[3.0.0]: https://github.com/Level/abstract-leveldown/compare/v2.7.2...v3.0.0 + +[2.7.2]: https://github.com/Level/abstract-leveldown/compare/v2.7.1...v2.7.2 + +[2.7.1]: https://github.com/Level/abstract-leveldown/compare/v2.7.0...v2.7.1 + +[2.7.0]: https://github.com/Level/abstract-leveldown/compare/v2.6.3...v2.7.0 + +[2.6.3]: https://github.com/Level/abstract-leveldown/compare/v2.6.2...v2.6.3 + +[2.6.2]: https://github.com/Level/abstract-leveldown/compare/v2.6.1...v2.6.2 + +[2.6.1]: https://github.com/Level/abstract-leveldown/compare/v2.6.0...v2.6.1 + +[2.6.0]: https://github.com/Level/abstract-leveldown/compare/v2.5.0...v2.6.0 + +[2.5.0]: https://github.com/Level/abstract-leveldown/compare/v2.4.1...v2.5.0 + +[2.4.1]: https://github.com/Level/abstract-leveldown/compare/v2.4.0...v2.4.1 + +[2.4.0]: https://github.com/Level/abstract-leveldown/compare/v2.3.1...v2.4.0 + +[2.3.1]: https://github.com/Level/abstract-leveldown/compare/v2.3.0...v2.3.1 + +[2.3.0]: https://github.com/Level/abstract-leveldown/compare/v2.2.2...v2.3.0 + +[2.2.2]: https://github.com/Level/abstract-leveldown/compare/v2.2.1...v2.2.2 + +[2.2.1]: https://github.com/Level/abstract-leveldown/compare/v2.2.0...v2.2.1 + +[2.2.0]: https://github.com/Level/abstract-leveldown/compare/v2.1.4...v2.2.0 + +[2.1.4]: https://github.com/Level/abstract-leveldown/compare/v2.1.3...v2.1.4 + +[2.1.3]: https://github.com/Level/abstract-leveldown/compare/v2.1.2...v2.1.3 + +[2.1.2]: https://github.com/Level/abstract-leveldown/compare/v2.1.1...v2.1.2 + +[2.1.1]: https://github.com/Level/abstract-leveldown/compare/v2.1.0...v2.1.1 + +[2.1.0]: https://github.com/Level/abstract-leveldown/compare/v2.0.3...v2.1.0 + +[2.0.3]: https://github.com/Level/abstract-leveldown/compare/v2.0.2...v2.0.3 + +[2.0.2]: https://github.com/Level/abstract-leveldown/compare/v2.0.1...v2.0.2 + +[2.0.1]: https://github.com/Level/abstract-leveldown/compare/v2.0.0...v2.0.1 + +[2.0.0]: https://github.com/Level/abstract-leveldown/compare/v1.0.0...v2.0.0 + +[1.0.0]: https://github.com/Level/abstract-leveldown/compare/v0.12.4...v1.0.0 + +[0.12.4]: https://github.com/Level/abstract-leveldown/compare/v0.12.3...v0.12.4 + +[0.12.3]: https://github.com/Level/abstract-leveldown/compare/v0.12.2...v0.12.3 + +[0.12.2]: https://github.com/Level/abstract-leveldown/compare/v0.12.1...v0.12.2 + +[0.12.1]: https://github.com/Level/abstract-leveldown/compare/v0.12.0...v0.12.1 + +[0.12.0]: https://github.com/Level/abstract-leveldown/compare/v0.11.4...v0.12.0 + +[0.11.4]: https://github.com/Level/abstract-leveldown/compare/v0.11.3...v0.11.4 + +[0.11.3]: https://github.com/Level/abstract-leveldown/compare/v0.11.2...v0.11.3 + +[0.11.2]: https://github.com/Level/abstract-leveldown/compare/0.11.1...v0.11.2 + +[0.11.1]: https://github.com/Level/abstract-leveldown/compare/0.11.0...0.11.1 + +[0.11.0]: https://github.com/Level/abstract-leveldown/compare/0.10.2...0.11.0 + +[0.10.2]: https://github.com/Level/abstract-leveldown/compare/0.10.1...0.10.2 + +[0.10.1]: https://github.com/Level/abstract-leveldown/compare/0.10.0...0.10.1 + +[0.10.0]: https://github.com/Level/abstract-leveldown/compare/0.9.0...0.10.0 + +[0.9.0]: https://github.com/Level/abstract-leveldown/compare/0.8.2...0.9.0 + +[0.8.2]: https://github.com/Level/abstract-leveldown/compare/0.8.1...0.8.2 + +[0.8.1]: https://github.com/Level/abstract-leveldown/compare/0.8.0...0.8.1 + +[0.8.0]: https://github.com/Level/abstract-leveldown/compare/0.7.4...0.8.0 + +[0.7.4]: https://github.com/Level/abstract-leveldown/compare/0.7.3...0.7.4 + +[0.7.3]: https://github.com/Level/abstract-leveldown/compare/0.7.2...0.7.3 + +[0.7.2]: https://github.com/Level/abstract-leveldown/compare/0.7.1...0.7.2 + +[0.7.1]: https://github.com/Level/abstract-leveldown/compare/0.7.0...0.7.1 + +[0.7.0]: https://github.com/Level/abstract-leveldown/compare/0.6.1...0.7.0 + +[0.6.1]: https://github.com/Level/abstract-leveldown/compare/0.6.0...0.6.1 + +[0.6.0]: https://github.com/Level/abstract-leveldown/compare/0.5.0...0.6.0 + +[0.5.0]: https://github.com/Level/abstract-leveldown/compare/0.4.0...0.5.0 + +[0.4.0]: https://github.com/Level/abstract-leveldown/compare/0.4.0-1...0.4.0 + +[0.4.0-1]: https://github.com/Level/abstract-leveldown/compare/0.3.0...0.4.0-1 + +[0.3.0]: https://github.com/Level/abstract-leveldown/compare/0.2.3...0.3.0 + +[0.2.3]: https://github.com/Level/abstract-leveldown/compare/0.2.2...0.2.3 + +[0.2.2]: https://github.com/Level/abstract-leveldown/compare/0.2.1...0.2.2 + +[0.2.1]: https://github.com/Level/abstract-leveldown/compare/0.2.0...0.2.1 + +[0.2.0]: https://github.com/Level/abstract-leveldown/compare/0.1.0...0.2.0 + +[0.1.0]: https://github.com/Level/abstract-leveldown/compare/0.0.2...0.1.0 + +[0.0.2]: https://github.com/Level/abstract-leveldown/compare/0.0.1...0.0.2 + +[0.0.1]: https://github.com/Level/abstract-leveldown/compare/0.0.0...0.0.1 diff --git a/nodejs/node_modules/abstract-leveldown/CONTRIBUTORS.md b/nodejs/node_modules/abstract-leveldown/CONTRIBUTORS.md new file mode 100644 index 00000000..a7b60a7a --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/CONTRIBUTORS.md @@ -0,0 +1,27 @@ +# Contributors + +| Name | GitHub | Social | +| :------------------------- | :----------------------------------------------------- | :----------------------------------------------------------------------- | +| **Rod Vagg** | [**@rvagg**](https://github.com/rvagg) | [**@rvagg@twitter**](https://twitter.com/rvagg) | +| **Vincent Weevers** | [**@vweevers**](https://github.com/vweevers) | [**@vweevers@twitter**](https://twitter.com/vweevers) | +| **Lars-Magnus Skog** | [**@ralphtheninja**](https://github.com/ralphtheninja) | [**@ralph@social.weho.st**](https://social.weho.st/@ralph) | +| **Julian Gruber** | [**@juliangruber**](https://github.com/juliangruber) | [**@juliangruber@twitter**](https://twitter.com/juliangruber) | +| **David Björklund** | [**@kesla**](https://github.com/kesla) | [**@david_bjorklund@twitter**](https://twitter.com/david_bjorklund) | +| **Max Ogden** | [**@maxogden**](https://github.com/maxogden) | [**@maxogden@twitter**](https://twitter.com/maxogden) | +| **Thomas Watson Steen** | | | +| **Alan Gutierrez** | [**@bigeasy**](https://github.com/bigeasy) | [**@bigeasy@twitter**](https://twitter.com/bigeasy) | +| **Dean Landolt** | [**@deanlandolt**](https://github.com/deanlandolt) | | +| **Calvin Metcalf** | [**@calvinmetcalf**](https://github.com/calvinmetcalf) | | +| **Meirion Hughes** | [**@MeirionHughes**](https://github.com/MeirionHughes) | | +| **Matteo Collina** | [**@mcollina**](https://github.com/mcollina) | [**@matteocollina@twitter**](https://twitter.com/matteocollina) | +| **Andrew Kelley** | [**@andrewrk**](https://github.com/andrewrk) | | +| **Tapani Moilanen** | [**@Tapppi**](https://github.com/Tapppi) | | +| **Dominic Tarr** | [**@dominictarr**](https://github.com/dominictarr) | [**@dominictarr@twitter**](https://twitter.com/dominictarr) | +| **Hao-kang Den** | | | +| **Hugo Dias** | | | +| **Jake Verbaten** | [**@Raynos**](https://github.com/Raynos) | [**@raynos@twitter**](https://twitter.com/raynos) | +| **Kyle Robinson Young** | [**@shama**](https://github.com/shama) | [**@shamakry@twitter**](https://twitter.com/shamakry) | +| **Nathan Shively-Sanders** | [**@sandersn**](https://github.com/sandersn) | | +| **Nolan Lawson** | [**@nolanlawson**](https://github.com/nolanlawson) | [**@nolan@toot.cafe**](https://toot.cafe/@nolan) | +| **Tim Kuijsten** | [**@timkuijsten**](https://github.com/timkuijsten) | [**@timkuijsten@mastodon.social**](https://mastodon.social/@timkuijsten) | +| **Tim Oxley** | [**@timoxley**](https://github.com/timoxley) | [**@secoif@twitter**](https://twitter.com/secoif) | diff --git a/nodejs/node_modules/abstract-leveldown/LICENSE.md b/nodejs/node_modules/abstract-leveldown/LICENSE.md new file mode 100644 index 00000000..1e78cf89 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +**Copyright © 2013-present Rod Vagg and [Contributors](CONTRIBUTORS.md).** + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/abstract-leveldown/README.md b/nodejs/node_modules/abstract-leveldown/README.md new file mode 100644 index 00000000..19553276 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/README.md @@ -0,0 +1,629 @@ +# abstract-leveldown + +> An abstract prototype matching the [`leveldown`][leveldown] API. Useful for extending [`levelup`](https://github.com/Level/levelup) functionality by providing a replacement to `leveldown`. + +[![level badge][level-badge]](https://github.com/Level/awesome) +[![npm](https://img.shields.io/npm/v/abstract-leveldown.svg?label=&logo=npm)](https://www.npmjs.com/package/abstract-leveldown) +[![Node version](https://img.shields.io/node/v/abstract-leveldown.svg)](https://www.npmjs.com/package/abstract-leveldown) +[![Travis](https://img.shields.io/travis/com/Level/abstract-leveldown.svg?logo=travis&label=)](https://travis-ci.com/Level/abstract-leveldown) +[![Coverage Status](https://coveralls.io/repos/github/Level/abstract-leveldown/badge.svg)](https://coveralls.io/github/Level/abstract-leveldown) +[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) +[![npm](https://img.shields.io/npm/dm/abstract-leveldown.svg?label=dl)](https://www.npmjs.com/package/abstract-leveldown) +[![Backers on Open Collective](https://opencollective.com/level/backers/badge.svg?color=orange)](#backers) +[![Sponsors on Open Collective](https://opencollective.com/level/sponsors/badge.svg?color=orange)](#sponsors) + +## Table of Contents + +
Click to expand + +- [Background](#background) +- [Example](#example) +- [Browser Support](#browser-support) +- [Public API For Consumers](#public-api-for-consumers) +- [Private API For Implementors](#private-api-for-implementors) +- [Test Suite](#test-suite) +- [Spread The Word](#spread-the-word) +- [Install](#install) +- [Contributing](#contributing) +- [Big Thanks](#big-thanks) +- [Donate](#donate) +- [License](#license) + +
+ +## Background + +This module provides a simple base prototype for a key-value store. It has a public API for consumers and a private API for implementors. To implement a `abstract-leveldown` compliant store, extend its prototype and override the private underscore versions of the methods. For example, to implement `put()`, override `_put()` on your prototype. + +Where possible, the default private methods have sensible _noop_ defaults that essentially do nothing. For example, `_open(callback)` will invoke `callback` on a next tick. Other methods like `_clear(..)` have functional defaults. Each method listed below documents whether implementing it is mandatory. + +The private methods are always provided with consistent arguments, regardless of what is passed in through the public API. All public methods provide argument checking: if a consumer calls `open()` without a callback argument they'll get an `Error('open() requires a callback argument')`. + +Where optional arguments are involved, private methods receive sensible defaults: a `get(key, callback)` call translates to `_get(key, options, callback)` where the `options` argument is an empty object. These arguments are documented below. + +**If you are upgrading:** please see [UPGRADING.md](UPGRADING.md). + +## Example + +Let's implement a simplistic in-memory [`leveldown`][leveldown] replacement: + +```js +var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN +var util = require('util') + +// Constructor +function FakeLevelDOWN () { + AbstractLevelDOWN.call(this) +} + +// Our new prototype inherits from AbstractLevelDOWN +util.inherits(FakeLevelDOWN, AbstractLevelDOWN) + +FakeLevelDOWN.prototype._open = function (options, callback) { + // Initialize a memory storage object + this._store = {} + + // Use nextTick to be a nice async citizen + process.nextTick(callback) +} + +FakeLevelDOWN.prototype._serializeKey = function (key) { + // As an example, prefix all input keys with an exclamation mark. + // Below methods will receive serialized keys in their arguments. + return '!' + key +} + +FakeLevelDOWN.prototype._put = function (key, value, options, callback) { + this._store[key] = value + process.nextTick(callback) +} + +FakeLevelDOWN.prototype._get = function (key, options, callback) { + var value = this._store[key] + + if (value === undefined) { + // 'NotFound' error, consistent with LevelDOWN API + return process.nextTick(callback, new Error('NotFound')) + } + + process.nextTick(callback, null, value) +} + +FakeLevelDOWN.prototype._del = function (key, options, callback) { + delete this._store[key] + process.nextTick(callback) +} +``` + +Now we can use our implementation with `levelup`: + +```js +var levelup = require('levelup') + +var db = levelup(new FakeLevelDOWN()) + +db.put('foo', 'bar', function (err) { + if (err) throw err + + db.get('foo', function (err, value) { + if (err) throw err + + console.log(value) // 'bar' + }) +}) +``` + +See [`memdown`](https://github.com/Level/memdown/) if you are looking for a complete in-memory replacement for `leveldown`. + +## Browser Support + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/abstract-leveldown.svg)](https://saucelabs.com/u/abstract-leveldown) + +## Public API For Consumers + +### `db = constructor(..)` + +Constructors typically take a `location` argument pointing to a location on disk where the data will be stored. Since not all implementations are disk-based and some are non-persistent, implementors are free to take zero or more arguments in their constructor. + +### `db.status` + +A read-only property. An `abstract-leveldown` compliant store can be in one of the following states: + +- `'new'` - newly created, not opened or closed +- `'opening'` - waiting for the store to be opened +- `'open'` - successfully opened the store, available for use +- `'closing'` - waiting for the store to be closed +- `'closed'` - store has been successfully closed, should not be used. + +### `db.supports` + +A read-only [manifest](https://github.com/Level/supports). Might be used like so: + +```js +if (!db.supports.permanence) { + throw new Error('Persistent storage is required') +} + +if (db.supports.bufferKeys && db.supports.promises) { + await db.put(Buffer.from('key'), 'value') +} +``` + +### `db.open([options, ]callback)` + +Open the store. The `callback` function will be called with no arguments when the store has been successfully opened, or with a single error argument if the open operation failed for any reason. + +The optional `options` argument may contain: + +- `createIfMissing` _(boolean, default: `true`)_: If `true` and the store doesn't exist it will be created. If `false` and the store doesn't exist, `callback` will receive an error. +- `errorIfExists` _(boolean, default: `false`)_: If `true` and the store exists, `callback` will receive an error. + +Not all implementations support the above options. + +### `db.close(callback)` + +Close the store. The `callback` function will be called with no arguments if the operation is successful or with a single `error` argument if closing failed for any reason. + +### `db.get(key[, options], callback)` + +Get a value from the store by `key`. The optional `options` object may contain: + +- `asBuffer` _(boolean, default: `true`)_: Whether to return the `value` as a Buffer. If `false`, the returned type depends on the implementation. + +The `callback` function will be called with an `Error` if the operation failed for any reason. If successful the first argument will be `null` and the second argument will be the value. + +### `db.put(key, value[, options], callback)` + +Store a new entry or overwrite an existing entry. There are no `options` by default but implementations may add theirs. The `callback` function will be called with no arguments if the operation is successful or with an `Error` if putting failed for any reason. + +### `db.del(key[, options], callback)` + +Delete an entry. There are no `options` by default but implementations may add theirs. The `callback` function will be called with no arguments if the operation is successful or with an `Error` if deletion failed for any reason. + +### `db.batch(operations[, options], callback)` + +Perform multiple _put_ and/or _del_ operations in bulk. The `operations` argument must be an `Array` containing a list of operations to be executed sequentially, although as a whole they are performed as an atomic operation. + +Each operation is contained in an object having the following properties: `type`, `key`, `value`, where the `type` is either `'put'` or `'del'`. In the case of `'del'` the `value` property is ignored. + +There are no `options` by default but implementations may add theirs. The `callback` function will be called with no arguments if the batch is successful or with an `Error` if the batch failed for any reason. + +### `db.batch()` + +Returns a [`chainedBatch`](#chainedbatch). + +### `db.iterator([options])` + +Returns an [`iterator`](#iterator). Accepts the following range options: + +- `gt` (greater than), `gte` (greater than or equal) define the lower bound of the range to be iterated. Only entries where the key is greater than (or equal to) this option will be included in the range. When `reverse=true` the order will be reversed, but the entries iterated will be the same. +- `lt` (less than), `lte` (less than or equal) define the higher bound of the range to be iterated. Only entries where the key is less than (or equal to) this option will be included in the range. When `reverse=true` the order will be reversed, but the entries iterated will be the same. +- `reverse` _(boolean, default: `false`)_: iterate entries in reverse order. Beware that a reverse seek can be slower than a forward seek. +- `limit` _(number, default: `-1`)_: limit the number of entries collected by this iterator. This number represents a _maximum_ number of entries and may not be reached if you get to the end of the range first. A value of `-1` means there is no limit. When `reverse=true` the entries with the highest keys will be returned instead of the lowest keys. + +Legacy options: + +- `start`: instead use `gte` +- `end`: instead use `lte`. + +**Note** Zero-length strings, buffers and arrays as well as `null` and `undefined` are invalid as keys, yet valid as range options. These types are significant in encodings like [`bytewise`](https://github.com/deanlandolt/bytewise) and [`charwise`](https://github.com/dominictarr/charwise) as well as some underlying stores like IndexedDB. Consumers of an implementation should assume that `{ gt: undefined }` is _not_ the same as `{}`. An implementation can choose to: + +- [_Serialize_](#db_serializekeykey) or [_encode_][encoding-down] these types to make them meaningful +- Have no defined behavior (moving the concern to a higher level) +- Delegate to an underlying store (moving the concern to a lower level). + +If you are an implementor, a final note: the [abstract test suite](#test-suite) does not test these types. Whether they are supported or how they sort is up to you; add custom tests accordingly. + +In addition to range options, `iterator()` takes the following options: + +- `keys` _(boolean, default: `true`)_: whether to return the key of each entry. If set to `false`, calls to `iterator.next(callback)` will yield keys with a value of `undefined`. +- `values` _(boolean, default: `true`)_: whether to return the value of each entry. If set to `false`, calls to `iterator.next(callback)` will yield values with a value of `undefined`. +- `keyAsBuffer` _(boolean, default: `true`)_: Whether to return the key of each entry as a Buffer. If `false`, the returned type depends on the implementation. +- `valueAsBuffer` _(boolean, default: `true`)_: Whether to return the value of each entry as a Buffer. + +Lastly, an implementation is free to add its own options. + +### `db.clear([options, ]callback)` + +**This method is experimental. Not all implementations support it yet.** + +Delete all entries or a range. Not guaranteed to be atomic. Accepts the following range options (with the same rules as on iterators): + +- `gt` (greater than), `gte` (greater than or equal) define the lower bound of the range to be deleted. Only entries where the key is greater than (or equal to) this option will be included in the range. When `reverse=true` the order will be reversed, but the entries deleted will be the same. +- `lt` (less than), `lte` (less than or equal) define the higher bound of the range to be deleted. Only entries where the key is less than (or equal to) this option will be included in the range. When `reverse=true` the order will be reversed, but the entries deleted will be the same. +- `reverse` _(boolean, default: `false`)_: delete entries in reverse order. Only effective in combination with `limit`, to remove the last N records. +- `limit` _(number, default: `-1`)_: limit the number of entries to be deleted. This number represents a _maximum_ number of entries and may not be reached if you get to the end of the range first. A value of `-1` means there is no limit. When `reverse=true` the entries with the highest keys will be deleted instead of the lowest keys. + +If no options are provided, all entries will be deleted. The `callback` function will be called with no arguments if the operation was successful or with an `Error` if it failed for any reason. + +### `chainedBatch` + +#### `chainedBatch.put(key, value)` + +Queue a `put` operation on this batch. This may throw if `key` or `value` is invalid. + +#### `chainedBatch.del(key)` + +Queue a `del` operation on this batch. This may throw if `key` is invalid. + +#### `chainedBatch.clear()` + +Clear all queued operations on this batch. + +#### `chainedBatch.write([options, ]callback)` + +Commit the queued operations for this batch. All operations will be written atomically, that is, they will either all succeed or fail with no partial commits. + +There are no `options` by default but implementations may add theirs. The `callback` function will be called with no arguments if the batch is successful or with an `Error` if the batch failed for any reason. + +After `write` has been called, no further operations are allowed. + +#### `chainedBatch.db` + +A reference to the `db` that created this chained batch. + +### `iterator` + +An iterator allows you to _iterate_ the entire store or a range. It operates on a snapshot of the store, created at the time `db.iterator()` was called. This means reads on the iterator are unaffected by simultaneous writes. Most but not all implementations can offer this guarantee. + +An iterator keeps track of when a `next()` is in progress and when an `end()` has been called so it doesn't allow concurrent `next()` calls, it does allow `end()` while a `next()` is in progress and it doesn't allow either `next()` or `end()` after `end()` has been called. + +#### `iterator.next(callback)` + +Advance the iterator and yield the entry at that key. If an error occurs, the `callback` function will be called with an `Error`. Otherwise, the `callback` receives `null`, a `key` and a `value`. The type of `key` and `value` depends on the options passed to `db.iterator()`. + +If the iterator has reached its end, both `key` and `value` will be `undefined`. This happens in the following situations: + +- The end of the store has been reached +- The end of the range has been reached +- The last `iterator.seek()` was out of range. + +**Note:** Don't forget to call `iterator.end()`, even if you received an error. + +#### `iterator.seek(target)` + +Seek the iterator to a given key or the closest key. Subsequent calls to `iterator.next()` will yield entries with keys equal to or larger than `target`, or equal to or smaller than `target` if the `reverse` option passed to `db.iterator()` was true. + +If range options like `gt` were passed to `db.iterator()` and `target` does not fall within that range, the iterator will reach its end. + +**Note:** At the time of writing, [`leveldown`][leveldown] is the only known implementation to support `seek()`. In other implementations, it is a noop. + +#### `iterator.end(callback)` + +End iteration and free up underlying resources. The `callback` function will be called with no arguments on success or with an `Error` if ending failed for any reason. + +#### `iterator.db` + +A reference to the `db` that created this iterator. + +### Type Support + +The following applies to any method above that takes a `key` argument or option: all implementations _must_ support a `key` of type String and _should_ support a `key` of type Buffer. A `key` may not be `null`, `undefined`, a zero-length Buffer, zero-length string or zero-length array. + +The following applies to any method above that takes a `value` argument or option: all implementations _must_ support a `value` of type String or Buffer. A `value` may not be `null` or `undefined` due to preexisting significance in streams and iterators. + +Support of other key and value types depends on the implementation as well as its underlying storage. See also [`db._serializeKey`](#db_serializekeykey) and [`db._serializeValue`](#db_serializevaluevalue). + +## Private API For Implementors + +Each of these methods will receive exactly the number and order of arguments described. Optional arguments will receive sensible defaults. All callbacks are error-first and must be asynchronous. + +If an operation within your implementation is synchronous, be sure to invoke the callback on a next tick using `process.nextTick` or some other means of microtask scheduling. For convenience, the prototypes of `AbstractLevelDOWN`, `AbstractIterator` and `AbstractChainedBatch` include a `_nextTick` method that is compatible with node and browsers. + +### `db = AbstractLevelDOWN([manifest])` + +The constructor. Sets the `.status` to `'new'`. Optionally takes a [manifest](https://github.com/Level/supports) object which `abstract-leveldown` will enrich: + +```js +AbstractLevelDOWN.call(this, { + bufferKeys: true, + snapshots: true, + // .. +}) +``` + +### `db._open(options, callback)` + +Open the store. The `options` object will always have the following properties: `createIfMissing`, `errorIfExists`. If opening failed, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +The default `_open()` is a sensible noop and invokes `callback` on a next tick. + +### `db._close(callback)` + +Close the store. If closing failed, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +The default `_close()` is a sensible noop and invokes `callback` on a next tick. + +### `db._serializeKey(key)` + +Convert a `key` to a type supported by the underlying storage. All methods below that take a `key` argument or option - including `db._iterator()` with its range options and `iterator._seek()` with its `target` argument - will receive serialized keys. For example, if `_serializeKey` is implemented as: + +```js +FakeLevelDOWN.prototype._serializeKey = function (key) { + return Buffer.isBuffer(key) ? key : String(key) +} +``` + +Then `db.get(2, callback)` translates into `db._get('2', options, callback)`. Similarly, `db.iterator({ gt: 2 })` translates into `db._iterator({ gt: '2', ... })` and `iterator.seek(2)` translates into `iterator._seek('2')`. + +If the underlying storage supports any JavaScript type or if your implementation wraps another implementation, it is recommended to make `_serializeKey` an identity function (returning the key as-is). Serialization is irreversible, unlike _encoding_ as performed by implementations like [`encoding-down`][encoding-down]. This also applies to `_serializeValue`. + +The default `_serializeKey()` is an identity function. + +### `db._serializeValue(value)` + +Convert a `value` to a type supported by the underlying storage. All methods below that take a `value` argument or option will receive serialized values. For example, if `_serializeValue` is implemented as: + +```js +FakeLevelDOWN.prototype._serializeValue = function (value) { + return Buffer.isBuffer(value) ? value : String(value) +} +``` + +Then `db.put(key, 2, callback)` translates into `db._put(key, '2', options, callback)`. + +The default `_serializeValue()` is an identity function. + +### `db._get(key, options, callback)` + +Get a value by `key`. The `options` object will always have the following properties: `asBuffer`. If the key does not exist, call the `callback` function with a `new Error('NotFound')`. Otherwise call `callback` with `null` as the first argument and the value as the second. + +The default `_get()` invokes `callback` on a next tick with a `NotFound` error. It must be overridden. + +### `db._put(key, value, options, callback)` + +Store a new entry or overwrite an existing entry. There are no default options but `options` will always be an object. If putting failed, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +The default `_put()` invokes `callback` on a next tick. It must be overridden. + +### `db._del(key, options, callback)` + +Delete an entry. There are no default options but `options` will always be an object. If deletion failed, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +The default `_del()` invokes `callback` on a next tick. It must be overridden. + +### `db._batch(operations, options, callback)` + +Perform multiple _put_ and/or _del_ operations in bulk. The `operations` argument is always an `Array` containing a list of operations to be executed sequentially, although as a whole they should be performed as an atomic operation. Each operation is guaranteed to have at least `type` and `key` properties. There are no default options but `options` will always be an object. If the batch failed, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +The default `_batch()` invokes `callback` on a next tick. It must be overridden. + +### `db._chainedBatch()` + +The default `_chainedBatch()` returns a functional `AbstractChainedBatch` instance that uses `db._batch(array, options, callback)` under the hood. The prototype is available on the main exports for you to extend. If you want to implement chainable batch operations in a different manner then you should extend `AbstractChainedBatch` and return an instance of this prototype in the `_chainedBatch()` method: + +```js +var AbstractChainedBatch = require('abstract-leveldown').AbstractChainedBatch +var inherits = require('util').inherits + +function ChainedBatch (db) { + AbstractChainedBatch.call(this, db) +} + +inherits(ChainedBatch, AbstractChainedBatch) + +FakeLevelDOWN.prototype._chainedBatch = function () { + return new ChainedBatch(this) +} +``` + +### `db._iterator(options)` + +The default `_iterator()` returns a noop `AbstractIterator` instance. It must be overridden, by extending `AbstractIterator` (available on the main module exports) and returning an instance of this prototype in the `_iterator(options)` method. + +The `options` object will always have the following properties: `reverse`, `keys`, `values`, `limit`, `keyAsBuffer` and `valueAsBuffer`. + +### `db._clear(options, callback)` + +**This method is experimental and optional for the time being. To enable its tests, set the [`clear` option of the test suite](#excluding-tests) to `true`.** + +Delete all entries or a range. Does not have to be atomic. It is recommended (and possibly mandatory in the future) to operate on a snapshot so that writes scheduled after a call to `clear()` will not be affected. + +The default `_clear()` uses `_iterator()` and `_del()` to provide a reasonable fallback, but requires binary key support. It is _recommended_ to implement `_clear()` with more performant primitives than `_iterator()` and `_del()` if the underlying storage has such primitives. Implementations that don't support binary keys _must_ implement their own `_clear()`. + +Implementations that wrap another `db` can typically forward the `_clear()` call to that `db`, having transformed range options if necessary. + +The `options` object will always have the following properties: `reverse` and `limit`. + +### `iterator = AbstractIterator(db)` + +The first argument to this constructor must be an instance of your `AbstractLevelDOWN` implementation. The constructor will set `iterator.db` which is used to access `db._serialize*` and ensures that `db` will not be garbage collected in case there are no other references to it. + +#### `iterator._next(callback)` + +Advance the iterator and yield the entry at that key. If nexting failed, call the `callback` function with an `Error`. Otherwise, call `callback` with `null`, a `key` and a `value`. + +The default `_next()` invokes `callback` on a next tick. It must be overridden. + +#### `iterator._seek(target)` + +Seek the iterator to a given key or the closest key. This method is optional. + +#### `iterator._end(callback)` + +Free up underlying resources. This method is guaranteed to only be called once. If ending failed, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +The default `_end()` invokes `callback` on a next tick. Overriding is optional. + +### `chainedBatch = AbstractChainedBatch(db)` + +The first argument to this constructor must be an instance of your `AbstractLevelDOWN` implementation. The constructor will set `chainedBatch.db` which is used to access `db._serialize*` and ensures that `db` will not be garbage collected in case there are no other references to it. + +#### `chainedBatch._put(key, value)` + +Queue a `put` operation on this batch. + +#### `chainedBatch._del(key)` + +Queue a `del` operation on this batch. + +#### `chainedBatch._clear()` + +Clear all queued operations on this batch. + +#### `chainedBatch._write(options, callback)` + +The default `_write` method uses `db._batch`. If the `_write` method is overridden it must atomically commit the queued operations. There are no default options but `options` will always be an object. If committing fails, call the `callback` function with an `Error`. Otherwise call `callback` without any arguments. + +## Test Suite + +To prove that your implementation is `abstract-leveldown` compliant, include the abstract test suite in your `test.js` (or similar): + +```js +const test = require('tape') +const suite = require('abstract-leveldown/test') +const YourDOWN = require('.') + +suite({ + test: test, + factory: function () { + return new YourDOWN() + } +}) +``` + +This is the most minimal setup. The `test` option _must_ be a function that is API-compatible with `tape`. The `factory` option _must_ be a function that returns a unique and isolated database instance. The factory will be called many times by the test suite. + +If your implementation is disk-based we recommend using [`tempy`](https://github.com/sindresorhus/tempy) (or similar) to create unique temporary directories. Your setup could look something like: + +```js +const test = require('tape') +const tempy = require('tempy') +const suite = require('abstract-leveldown/test') +const YourDOWN = require('.') + +suite({ + test: test, + factory: function () { + return new YourDOWN(tempy.directory()) + } +}) +``` + +### Excluding tests + +As not every implementation can be fully compliant due to limitations of its underlying storage, some tests may be skipped. For example, to skip snapshot tests: + +```js +suite({ + // .. + snapshots: false +}) +``` + +This also serves as a signal to users of your implementation. The following options are available: + +- `bufferKeys`: set to `false` if binary keys are not supported by the underlying storage +- `seek`: set to `false` if your `iterator` does not implement `_seek` +- `clear`: defaults to `false` until a next major release. Set to `true` if your implementation either implements `_clear()` itself or is suitable to use the default implementation of `_clear()` (which requires binary key support). +- `snapshots`: set to `false` if any of the following is true: + - Reads don't operate on a [snapshot](#iterator) + - Snapshots are created asynchronously +- `createIfMissing` and `errorIfExists`: set to `false` if `db._open()` does not support these options. + +This metadata will be moved to manifests (`db.supports`) in the future. + +### Setup and teardown + +To perform (a)synchronous work before or after each test, you may define `setUp` and `tearDown` functions: + +```js +suite({ + // .. + setUp: function (t) { + t.end() + }, + tearDown: function (t) { + t.end() + } +}) +``` + +### Reusing `testCommon` + +The input to the test suite is a `testCommon` object. Should you need to reuse `testCommon` for your own (additional) tests, use the included utility to create a `testCommon` with defaults: + +```js +const test = require('tape') +const suite = require('abstract-leveldown/test') +const YourDOWN = require('.') + +const testCommon = suite.common({ + test: test, + factory: function () { + return new YourDOWN() + } +}) + +suite(testCommon) +``` + +The `testCommon` object will have all the properties describe above: `test`, `factory`, `setUp`, `tearDown` and the skip options. You might use it like so: + +```js +test('setUp', testCommon.setUp) + +test('custom test', function (t) { + var db = testCommon.factory() + // .. +}) + +test('another custom test', function (t) { + var db = testCommon.factory() + // .. +}) + +test('tearDown', testCommon.tearDown) +``` + +## Spread The Word + +If you'd like to share your awesome implementation with the world, here's what you might want to do: + +- Add an awesome badge to your `README`: `![level badge](https://leveljs.org/img/badge.svg)` +- Publish your awesome module to [npm](https://npmjs.org) +- Send a Pull Request to [Level/awesome](https://github.com/Level/awesome) to advertise your work! + +## Install + +With [npm](https://npmjs.org) do: + +``` +npm install abstract-leveldown +``` + +## Contributing + +[`Level/abstract-leveldown`](https://github.com/Level/abstract-leveldown) is an **OPEN Open Source Project**. This means that: + +> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +See the [Contribution Guide](https://github.com/Level/community/blob/master/CONTRIBUTING.md) for more details. + +## Big Thanks + +Cross-browser Testing Platform and Open Source ♥ Provided by [Sauce Labs](https://saucelabs.com). + +[![Sauce Labs logo](./sauce-labs.svg)](https://saucelabs.com) + +## Donate + +To sustain [`Level`](https://github.com/Level) and its activities, become a backer or sponsor on [Open Collective](https://opencollective.com/level). Your logo or avatar will be displayed on our 28+ [GitHub repositories](https://github.com/Level) and [npm](https://www.npmjs.com/) packages. 💖 + +### Backers + +[![Open Collective backers](https://opencollective.com/level/backers.svg?width=890)](https://opencollective.com/level) + +### Sponsors + +[![Open Collective sponsors](https://opencollective.com/level/sponsors.svg?width=890)](https://opencollective.com/level) + +## License + +[MIT](LICENSE.md) © 2013-present Rod Vagg and [Contributors](CONTRIBUTORS.md). + +[level-badge]: https://leveljs.org/img/badge.svg + +[encoding-down]: https://github.com/Level/encoding-down + +[leveldown]: https://github.com/Level/leveldown diff --git a/nodejs/node_modules/abstract-leveldown/UPGRADING.md b/nodejs/node_modules/abstract-leveldown/UPGRADING.md new file mode 100644 index 00000000..e19c647d --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/UPGRADING.md @@ -0,0 +1,322 @@ +# Upgrade Guide + +This document describes breaking changes and how to upgrade. For a complete list of changes including minor and patch releases, please refer to the [changelog](CHANGELOG.md). + +## Table of Contents + +
Click to expand + +- [v6](#v6) +- [v5](#v5) +- [v4](#v4) +- [v3](#v3) + +
+ +## v6 + +This release brings a major refactoring of the test suite, decouples `abstract-leveldown` from disk-based implementations and solves long-standing issues around serialization and type support. Because the changes are substantial, this guide has two sections: + +1. **Changes to public API** - for consumers of any implementation. +2. **Changes to private API** - intended for implementors. + +### Changes to public API + +#### Nullish values are rejected + +In addition to rejecting `null` and `undefined` as _keys_, `abstract-leveldown` now also rejects these types as _values_, due to preexisting significance in streams and iterators. + +Before this, the behavior of these types depended on a large number of factors: `_serializeValue` and type support of the underlying storage, whether `get()`, `iterator()` or a stream was used to retrieve values, the `keys` and `asBuffer` options of `iterator()` and finally, which encoding was selected. + +#### Range options are serialized + +Previously, range options like `lt` were passed through as-is, unlike keys. + +#### The rules for range options have been relaxed + +Because `null`, `undefined`, zero-length strings and zero-length buffers are significant types in encodings like `bytewise` and `charwise`, they became valid as range options. In fact, any type is now valid. This means `db.iterator({ gt: undefined })` is not the same as `db.iterator({})`. + +Furthermore, `abstract-leveldown` makes no assumptions about the meaning of these types. Range tests that assumed `null` meant "not defined" have been removed. + +#### Zero-length array keys are rejected + +Though this was already the case because `_checkKey` stringified its input before checking the length, that behavior has been replaced with an explicit `Array.isArray()` check and a new error message. + +#### No longer assumes support of boolean and `NaN` keys + +A test that asserted boolean and `NaN` keys were valid has been removed. + +#### Browser support + +IE10 has been dropped. + +### Changes to private API + +#### `location` was removed + +`AbstractLevelDOWN` is no longer associated with a `location`. It's up to the implementation to handle it if it's required. + +If your implementation has a `location` and you previously did: + +```js +function YourDOWN (location) { + AbstractLevelDOWN.call(this, location) +} +``` + +You must now do: + +```js +function YourDOWN (location) { + this.location = location + AbstractLevelDOWN.call(this) +} +``` + +Be sure to include appropriate type checks. If you relied on the default `AbstractLevelDOWN` behavior that would be: + +```js +if (typeof location !== 'string') { + throw new Error('constructor requires a location string argument') +} +``` + +#### Abstract test suite has moved to a single entry point + +Instead of including test files individually, you can and should include the test suite with one `require()` statement. If you previously did: + +```js +const test = require('tape') +const testCommon = require('abstract-leveldown/testCommon') +const YourDOWN = require('.') + +require('abstract-leveldown/abstract/get-test').all(YourDOWN, test, testCommon) +require('abstract-leveldown/abstract/put-test').all(YourDOWN, test, testCommon) + +// etc +``` + +You must now do: + +```js +const test = require('tape') +const suite = require('abstract-leveldown/test') +const YourDOWN = require('.') + +suite({ + test: test, + factory: function () { + return new YourDOWN() + } +}) +``` + +The input to the test suite is a new form of `testCommon`. Should you need to reuse `testCommon` for your own (additional) tests, use the included utility to create a `testCommon` with defaults: + +```js +const test = require('tape') +const suite = require('abstract-leveldown/test') +const YourDOWN = require('.') + +const testCommon = suite.common({ + test: test, + factory: function () { + return new YourDOWN() + } +}) + +suite(testCommon) +``` + +As part of removing `location`, the abstract tests no longer use `testCommon.location()`. Instead an implementation _must_ implement `factory()` which _must_ return a unique and isolated database instance. This allows implementations to pass options to their constructor. + +The `testCommon.cleanup` method has been removed. Because `factory()` returns a unique database instance, cleanup should no longer be necessary. The `testCommon.lastLocation` method has also been removed as there is no remaining use of it in abstract tests. + +Previously, implementations using the default `testCommon` had to include `rimraf` in their `devDependencies` and browser-based implementations had to exclude `rimraf` from browserify builds. This is no longer the case. + +If your implementation is disk-based we recommend using [`tempy`](https://github.com/sindresorhus/tempy) (or similar) to create unique temporary directories. Together with `factory()` your setup could now look something like: + +```js +const test = require('tape') +const tempy = require('tempy') +const suite = require('abstract-leveldown/test') +const YourDOWN = require('.') + +suite({ + test: test, + factory: function () { + return new YourDOWN(tempy.directory()) + } +}) +``` + +#### The `collectEntries` utility has moved + +The `testCommon.collectEntries` method has moved to the npm package `level-concat-iterator`. If your (additional) tests depend on `collectEntries` and you previously did: + +```js +testCommon.collectEntries(iterator, function (err, entries) {}) +``` + +You must now do: + +```js +const concat = require('level-concat-iterator') +concat(iterator, function (err, entries) {}) +``` + +#### Setup and teardown became noops + +Because cleanup is no longer necessary, the `testCommon.setUp` and `testCommon.tearDown` methods are now noops by default. If you do need to perform (a)synchronous work before or after each test, `setUp` and `tearDown` can be overridden: + +```js +suite({ + // .. + setUp: function (t) { + t.end() + }, + tearDown: function (t) { + t.end() + } +}) +``` + +#### Optional tests have been separated + +If your implementation does not support snapshots or other optional features, the relevant tests may be skipped. For example: + +```js +suite({ + // .. + snapshots: false +}) +``` + +Please see the [README](README.md) for a list of options. Note that some of these have replaced `process.browser` checks. + +#### Iterator must have a `db` reference + +The `db` argument of the `AbstractIterator` constructor became mandatory, as well as a public `db` property on the instance. Its existence is not new; the test suite now asserts that your implementation also has it. + +#### Seeking became part of official API + +If your implementation previously defined the public `iterator.seek(target)`, it must now define the private `iterator._seek(target)`. The new public API is equal to the reference implementation of `leveldown` except for two differences: + +- The `target` argument is not type checked, this is up to the implementation. +- The `target` argument is passed through `db._serializeKey`. + +Please see the [README](README.md) for details. + +#### Chained batch has been refactored + +- The default `_clear` method is no longer a noop; instead it clears the operations queued by `_put` and/or `_del` +- The `_write` method now takes an `options` object as its first argument +- The `db` argument of the `AbstractChainedBatch` constructor became mandatory, as well as a public `db` property on the instance, which was previously named `_db`. + +#### Default `_serializeKey` and `_serializeValue` became identity functions + +They return whatever is given. Previously they were opinionated and mostly geared towards string- and Buffer-based storages. Implementations that didn't already define their own serialization should now do so, according to the types that they support. Please refer to the [README](README.md) for recommended behavior. + +## v5 + +Dropped support for node 4. No other breaking changes. + +## v4 + +#### default `testCommon` parameter + +The `testCommon` parameter will now default to `abstract-leveldown/testCommon.js`. You can omit this parameter, unless your implementation needs a custom version. + +If your code today looks something like: + +```js +const test = require('tape') +const testCommon = require('abstract-leveldown/testCommon') +const leveldown = require('./your-leveldown') +const abstract = require('abstract-leveldown/abstract/get-test') + +abstract.all(leveldown, test, testCommon) +``` + +You can simplify it to: + +```js +const test = require('tape') +const leveldown = require('./your-leveldown') +const abstract = require('abstract-leveldown/abstract/get-test') + +abstract.all(leveldown, test) +``` + +#### `testBuffer` parameter removed + +The `abstract/put-get-del-test.js` previously took a custom `testBuffer` parameter. After an [analysis](https://github.com/Level/abstract-leveldown/pull/175#issuecomment-353867144) of various implementations we came to the conclusion that the parameter has no use. + +If your implementation is using this abstract test, change from: + +```js +const test = require('tape') +const testCommon = require('abstract-leveldown/testCommon') +const leveldown = require('./your-leveldown') +const fs = require('fs') +const path = require('path') +const testBuffer = fs.readFileSync(path.join(__dirname, 'data/testdata.bin')) +const abstract = require('abstract-leveldown/abstract/put-get-del-test') + +abstract.all(leveldown, test, testBuffer, testCommon) +``` + +to: + +```js +const test = require('tape') +const testCommon = require('abstract-leveldown/testCommon') +const leveldown = require('./your-leveldown') +const abstract = require('abstract-leveldown/abstract/put-get-del-test') + +abstract.all(leveldown, test, testCommon) +``` + +or if `testCommon` is also redundant, to: + +```js +const test = require('tape') +const leveldown = require('./your-leveldown') +const abstract = require('abstract-leveldown/abstract/put-get-del-test') + +abstract.all(leveldown, test) +``` + +#### `.approximateSize` method removed + +The `.approximateSize` method has been removed from the public API. It is heavily related to `LevelDB` and more often than not, other stores lack the native primitives to implement this. If you did implement the internal `_approximateSize` method, that is now dead code. To preserve the method in your public API, rename it to `approximateSize` and also take care of the initialization code. Look to `leveldown` for inspiration. + +Also, the corresponding abstract tests have been removed, so your implementation can no longer require `abstract/approximate-size-test`. + +#### `._isBuffer` method removed + +Because `Buffer` is available in all environments nowadays, there is no need for alternatives like typed arrays. It is preferred to use `Buffer` and `Buffer.isBuffer()` directly. + +#### `isLevelDOWN` function removed + +This was a legacy function. + +#### `ranges-test.js` renamed + +We have refactored a lot of the tests. Specifically the iterator tests were split in two and in that process we renamed `ranges-test.js` to `iterator-range-test.js`. + +If your implementation is using these tests then change from: + +```js +const abstract = require('abstract-leveldown/abstract/ranges-test') +``` + +to: + +```js +const abstract = require('abstract-leveldown/abstract/iterator-range-test') +``` + +## v3 + +No changes to the API. New major version because support for node 0.12 was dropped. diff --git a/nodejs/node_modules/abstract-leveldown/abstract-chained-batch.js b/nodejs/node_modules/abstract-leveldown/abstract-chained-batch.js new file mode 100644 index 00000000..bcdb9fa9 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/abstract-chained-batch.js @@ -0,0 +1,86 @@ +var nextTick = require('./next-tick') + +function AbstractChainedBatch (db) { + if (typeof db !== 'object' || db === null) { + throw new TypeError('First argument must be an abstract-leveldown compliant store') + } + + this.db = db + this._operations = [] + this._written = false +} + +AbstractChainedBatch.prototype._checkWritten = function () { + if (this._written) { + throw new Error('write() already called on this batch') + } +} + +AbstractChainedBatch.prototype.put = function (key, value) { + this._checkWritten() + + var err = this.db._checkKey(key) || this.db._checkValue(value) + if (err) throw err + + key = this.db._serializeKey(key) + value = this.db._serializeValue(value) + + this._put(key, value) + + return this +} + +AbstractChainedBatch.prototype._put = function (key, value) { + this._operations.push({ type: 'put', key: key, value: value }) +} + +AbstractChainedBatch.prototype.del = function (key) { + this._checkWritten() + + var err = this.db._checkKey(key) + if (err) throw err + + key = this.db._serializeKey(key) + this._del(key) + + return this +} + +AbstractChainedBatch.prototype._del = function (key) { + this._operations.push({ type: 'del', key: key }) +} + +AbstractChainedBatch.prototype.clear = function () { + this._checkWritten() + this._clear() + + return this +} + +AbstractChainedBatch.prototype._clear = function () { + this._operations = [] +} + +AbstractChainedBatch.prototype.write = function (options, callback) { + this._checkWritten() + + if (typeof options === 'function') { callback = options } + if (typeof callback !== 'function') { + throw new Error('write() requires a callback argument') + } + if (typeof options !== 'object' || options === null) { + options = {} + } + + this._written = true + this._write(options, callback) +} + +AbstractChainedBatch.prototype._write = function (options, callback) { + this.db._batch(this._operations, options, callback) +} + +// Expose browser-compatible nextTick for dependents +AbstractChainedBatch.prototype._nextTick = nextTick + +module.exports = AbstractChainedBatch diff --git a/nodejs/node_modules/abstract-leveldown/abstract-iterator.js b/nodejs/node_modules/abstract-leveldown/abstract-iterator.js new file mode 100644 index 00000000..8fb0f9cb --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/abstract-iterator.js @@ -0,0 +1,77 @@ +var nextTick = require('./next-tick') + +function AbstractIterator (db) { + if (typeof db !== 'object' || db === null) { + throw new TypeError('First argument must be an abstract-leveldown compliant store') + } + + this.db = db + this._ended = false + this._nexting = false +} + +AbstractIterator.prototype.next = function (callback) { + var self = this + + if (typeof callback !== 'function') { + throw new Error('next() requires a callback argument') + } + + if (self._ended) { + nextTick(callback, new Error('cannot call next() after end()')) + return self + } + + if (self._nexting) { + nextTick(callback, new Error('cannot call next() before previous next() has completed')) + return self + } + + self._nexting = true + self._next(function () { + self._nexting = false + callback.apply(null, arguments) + }) + + return self +} + +AbstractIterator.prototype._next = function (callback) { + nextTick(callback) +} + +AbstractIterator.prototype.seek = function (target) { + if (this._ended) { + throw new Error('cannot call seek() after end()') + } + if (this._nexting) { + throw new Error('cannot call seek() before next() has completed') + } + + target = this.db._serializeKey(target) + this._seek(target) +} + +AbstractIterator.prototype._seek = function (target) {} + +AbstractIterator.prototype.end = function (callback) { + if (typeof callback !== 'function') { + throw new Error('end() requires a callback argument') + } + + if (this._ended) { + return nextTick(callback, new Error('end() already called on iterator')) + } + + this._ended = true + this._end(callback) +} + +AbstractIterator.prototype._end = function (callback) { + nextTick(callback) +} + +// Expose browser-compatible nextTick for dependents +AbstractIterator.prototype._nextTick = nextTick + +module.exports = AbstractIterator diff --git a/nodejs/node_modules/abstract-leveldown/abstract-leveldown.js b/nodejs/node_modules/abstract-leveldown/abstract-leveldown.js new file mode 100644 index 00000000..5039cf32 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/abstract-leveldown.js @@ -0,0 +1,320 @@ +var xtend = require('xtend') +var supports = require('level-supports') +var Buffer = require('buffer').Buffer +var AbstractIterator = require('./abstract-iterator') +var AbstractChainedBatch = require('./abstract-chained-batch') +var nextTick = require('./next-tick') +var hasOwnProperty = Object.prototype.hasOwnProperty +var rangeOptions = 'start end gt gte lt lte'.split(' ') + +function AbstractLevelDOWN (manifest) { + this.status = 'new' + + // TODO (next major): make this mandatory + this.supports = supports(manifest, { + status: true + }) +} + +AbstractLevelDOWN.prototype.open = function (options, callback) { + var self = this + var oldStatus = this.status + + if (typeof options === 'function') callback = options + + if (typeof callback !== 'function') { + throw new Error('open() requires a callback argument') + } + + if (typeof options !== 'object' || options === null) options = {} + + options.createIfMissing = options.createIfMissing !== false + options.errorIfExists = !!options.errorIfExists + + this.status = 'opening' + this._open(options, function (err) { + if (err) { + self.status = oldStatus + return callback(err) + } + self.status = 'open' + callback() + }) +} + +AbstractLevelDOWN.prototype._open = function (options, callback) { + nextTick(callback) +} + +AbstractLevelDOWN.prototype.close = function (callback) { + var self = this + var oldStatus = this.status + + if (typeof callback !== 'function') { + throw new Error('close() requires a callback argument') + } + + this.status = 'closing' + this._close(function (err) { + if (err) { + self.status = oldStatus + return callback(err) + } + self.status = 'closed' + callback() + }) +} + +AbstractLevelDOWN.prototype._close = function (callback) { + nextTick(callback) +} + +AbstractLevelDOWN.prototype.get = function (key, options, callback) { + if (typeof options === 'function') callback = options + + if (typeof callback !== 'function') { + throw new Error('get() requires a callback argument') + } + + var err = this._checkKey(key) + if (err) return nextTick(callback, err) + + key = this._serializeKey(key) + + if (typeof options !== 'object' || options === null) options = {} + + options.asBuffer = options.asBuffer !== false + + this._get(key, options, callback) +} + +AbstractLevelDOWN.prototype._get = function (key, options, callback) { + nextTick(function () { callback(new Error('NotFound')) }) +} + +AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { + if (typeof options === 'function') callback = options + + if (typeof callback !== 'function') { + throw new Error('put() requires a callback argument') + } + + var err = this._checkKey(key) || this._checkValue(value) + if (err) return nextTick(callback, err) + + key = this._serializeKey(key) + value = this._serializeValue(value) + + if (typeof options !== 'object' || options === null) options = {} + + this._put(key, value, options, callback) +} + +AbstractLevelDOWN.prototype._put = function (key, value, options, callback) { + nextTick(callback) +} + +AbstractLevelDOWN.prototype.del = function (key, options, callback) { + if (typeof options === 'function') callback = options + + if (typeof callback !== 'function') { + throw new Error('del() requires a callback argument') + } + + var err = this._checkKey(key) + if (err) return nextTick(callback, err) + + key = this._serializeKey(key) + + if (typeof options !== 'object' || options === null) options = {} + + this._del(key, options, callback) +} + +AbstractLevelDOWN.prototype._del = function (key, options, callback) { + nextTick(callback) +} + +AbstractLevelDOWN.prototype.batch = function (array, options, callback) { + if (!arguments.length) return this._chainedBatch() + + if (typeof options === 'function') callback = options + + if (typeof array === 'function') callback = array + + if (typeof callback !== 'function') { + throw new Error('batch(array) requires a callback argument') + } + + if (!Array.isArray(array)) { + return nextTick(callback, new Error('batch(array) requires an array argument')) + } + + if (array.length === 0) { + return nextTick(callback) + } + + if (typeof options !== 'object' || options === null) options = {} + + var serialized = new Array(array.length) + + for (var i = 0; i < array.length; i++) { + if (typeof array[i] !== 'object' || array[i] === null) { + return nextTick(callback, new Error('batch(array) element must be an object and not `null`')) + } + + var e = xtend(array[i]) + + if (e.type !== 'put' && e.type !== 'del') { + return nextTick(callback, new Error("`type` must be 'put' or 'del'")) + } + + var err = this._checkKey(e.key) + if (err) return nextTick(callback, err) + + e.key = this._serializeKey(e.key) + + if (e.type === 'put') { + var valueErr = this._checkValue(e.value) + if (valueErr) return nextTick(callback, valueErr) + + e.value = this._serializeValue(e.value) + } + + serialized[i] = e + } + + this._batch(serialized, options, callback) +} + +AbstractLevelDOWN.prototype._batch = function (array, options, callback) { + nextTick(callback) +} + +AbstractLevelDOWN.prototype.clear = function (options, callback) { + if (typeof options === 'function') { + callback = options + } else if (typeof callback !== 'function') { + throw new Error('clear() requires a callback argument') + } + + options = cleanRangeOptions(this, options) + options.reverse = !!options.reverse + options.limit = 'limit' in options ? options.limit : -1 + + this._clear(options, callback) +} + +AbstractLevelDOWN.prototype._clear = function (options, callback) { + // Avoid setupIteratorOptions, would serialize range options a second time. + options.keys = true + options.values = false + options.keyAsBuffer = true + options.valueAsBuffer = true + + var iterator = this._iterator(options) + var emptyOptions = {} + var self = this + + var next = function (err) { + if (err) { + return iterator.end(function () { + callback(err) + }) + } + + iterator.next(function (err, key) { + if (err) return next(err) + if (key === undefined) return iterator.end(callback) + + // This could be optimized by using a batch, but the default _clear + // is not meant to be fast. Implementations have more room to optimize + // if they override _clear. Note: using _del bypasses key serialization. + self._del(key, emptyOptions, next) + }) + } + + next() +} + +AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { + options = cleanRangeOptions(this, options) + + options.reverse = !!options.reverse + options.keys = options.keys !== false + options.values = options.values !== false + options.limit = 'limit' in options ? options.limit : -1 + options.keyAsBuffer = options.keyAsBuffer !== false + options.valueAsBuffer = options.valueAsBuffer !== false + + return options +} + +function cleanRangeOptions (db, options) { + var result = {} + + for (var k in options) { + if (!hasOwnProperty.call(options, k)) continue + + var opt = options[k] + + if (isRangeOption(k)) { + // Note that we don't reject nullish and empty options here. While + // those types are invalid as keys, they are valid as range options. + opt = db._serializeKey(opt) + } + + result[k] = opt + } + + return result +} + +function isRangeOption (k) { + return rangeOptions.indexOf(k) !== -1 +} + +AbstractLevelDOWN.prototype.iterator = function (options) { + if (typeof options !== 'object' || options === null) options = {} + options = this._setupIteratorOptions(options) + return this._iterator(options) +} + +AbstractLevelDOWN.prototype._iterator = function (options) { + return new AbstractIterator(this) +} + +AbstractLevelDOWN.prototype._chainedBatch = function () { + return new AbstractChainedBatch(this) +} + +AbstractLevelDOWN.prototype._serializeKey = function (key) { + return key +} + +AbstractLevelDOWN.prototype._serializeValue = function (value) { + return value +} + +AbstractLevelDOWN.prototype._checkKey = function (key) { + if (key === null || key === undefined) { + return new Error('key cannot be `null` or `undefined`') + } else if (Buffer.isBuffer(key) && key.length === 0) { + return new Error('key cannot be an empty Buffer') + } else if (key === '') { + return new Error('key cannot be an empty String') + } else if (Array.isArray(key) && key.length === 0) { + return new Error('key cannot be an empty Array') + } +} + +AbstractLevelDOWN.prototype._checkValue = function (value) { + if (value === null || value === undefined) { + return new Error('value cannot be `null` or `undefined`') + } +} + +// Expose browser-compatible nextTick for dependents +AbstractLevelDOWN.prototype._nextTick = nextTick + +module.exports = AbstractLevelDOWN diff --git a/nodejs/node_modules/abstract-leveldown/index.js b/nodejs/node_modules/abstract-leveldown/index.js new file mode 100644 index 00000000..682a79ab --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/index.js @@ -0,0 +1,3 @@ +exports.AbstractLevelDOWN = require('./abstract-leveldown') +exports.AbstractIterator = require('./abstract-iterator') +exports.AbstractChainedBatch = require('./abstract-chained-batch') diff --git a/nodejs/node_modules/abstract-leveldown/next-tick-browser.js b/nodejs/node_modules/abstract-leveldown/next-tick-browser.js new file mode 100644 index 00000000..3e424be5 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/next-tick-browser.js @@ -0,0 +1 @@ +module.exports = require('immediate') diff --git a/nodejs/node_modules/abstract-leveldown/next-tick.js b/nodejs/node_modules/abstract-leveldown/next-tick.js new file mode 100644 index 00000000..32b40935 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/next-tick.js @@ -0,0 +1 @@ +module.exports = process.nextTick diff --git a/nodejs/node_modules/abstract-leveldown/package.json b/nodejs/node_modules/abstract-leveldown/package.json new file mode 100644 index 00000000..aac722b1 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/package.json @@ -0,0 +1,54 @@ +{ + "name": "abstract-leveldown", + "version": "6.2.3", + "description": "An abstract prototype matching the LevelDOWN API", + "license": "MIT", + "main": "index.js", + "browser": { + "./next-tick.js": "./next-tick-browser.js" + }, + "scripts": { + "test": "standard && hallmark && nyc node test/self.js", + "test-browsers": "airtap --coverage --loopback airtap.local test/self.js", + "test-browser-local": "airtap --coverage --local test/self.js", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "hallmark": "hallmark --fix", + "dependency-check": "dependency-check . test/*.js", + "prepublishOnly": "npm run dependency-check" + }, + "dependencies": { + "buffer": "^5.5.0", + "immediate": "^3.2.3", + "level-concat-iterator": "~2.0.0", + "level-supports": "~1.0.0", + "xtend": "~4.0.0" + }, + "devDependencies": { + "airtap": "^3.0.0", + "coveralls": "^3.0.2", + "dependency-check": "^3.3.0", + "hallmark": "^2.0.0", + "level-community": "^3.0.0", + "nyc": "^14.0.0", + "sinon": "^7.2.4", + "standard": "^14.0.0", + "tape": "^4.10.0" + }, + "hallmark": { + "community": "level-community" + }, + "repository": { + "type": "git", + "url": "https://github.com/Level/abstract-leveldown.git" + }, + "homepage": "https://github.com/Level/abstract-leveldown", + "keywords": [ + "level", + "leveldb", + "leveldown", + "levelup" + ], + "engines": { + "node": ">=6" + } +} diff --git a/nodejs/node_modules/abstract-leveldown/sauce-labs.svg b/nodejs/node_modules/abstract-leveldown/sauce-labs.svg new file mode 100644 index 00000000..574cf16b --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/sauce-labs.svg @@ -0,0 +1,81 @@ + + + + + Sauce Labs + + + + + + + + + + + + + + + + diff --git a/nodejs/node_modules/abstract-leveldown/test/batch-test.js b/nodejs/node_modules/abstract-leveldown/test/batch-test.js new file mode 100644 index 00000000..4b2a4719 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/batch-test.js @@ -0,0 +1,318 @@ +var db +var verifyNotFoundError = require('./util').verifyNotFoundError +var isTypedArray = require('./util').isTypedArray + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test callback-less, 2-arg, batch() throws', function (t) { + t.throws( + db.batch.bind(db, 'foo', {}), + /Error: batch\(array\) requires a callback argument/, + 'callback-less, 2-arg batch() throws' + ) + t.end() + }) + + test('test batch() with missing `value`', function (t) { + db.batch([{ type: 'put', key: 'foo1' }], function (err) { + t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message') + t.end() + }) + }) + + test('test batch() with null or undefined `value`', function (t) { + var illegalValues = [null, undefined] + + t.plan(illegalValues.length) + + illegalValues.forEach(function (value) { + db.batch([{ type: 'put', key: 'foo1', value: value }], function (err) { + t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message') + }) + }) + }) + + test('test batch() with missing `key`', function (t) { + var async = false + + db.batch([{ type: 'put', value: 'foo1' }], function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with null or undefined `key`', function (t) { + var illegalKeys = [null, undefined] + + t.plan(illegalKeys.length * 3) + + illegalKeys.forEach(function (key) { + var async = false + + db.batch([{ type: 'put', key: key, value: 'foo1' }], function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + t.ok(async, 'callback is asynchronous') + }) + + async = true + }) + }) + + test('test batch() with empty `key`', function (t) { + var illegalKeys = [ + { type: 'String', key: '' }, + { type: 'Buffer', key: Buffer.alloc(0) }, + { type: 'Array', key: [] } + ] + + t.plan(illegalKeys.length * 3) + + illegalKeys.forEach(function (item) { + var async = false + + db.batch([{ type: 'put', key: item.key, value: 'foo1' }], function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'key cannot be an empty ' + item.type, 'correct error message') + t.ok(async, 'callback is asynchronous') + }) + + async = true + }) + }) + + test('test batch() with missing `key` and `value`', function (t) { + var async = false + + db.batch([{ type: 'put' }], function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with missing `type`', function (t) { + var async = false + + db.batch([{ key: 'key', value: 'value' }], function (err) { + t.ok(err, 'got error') + t.equal(err.message, "`type` must be 'put' or 'del'", 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with wrong `type`', function (t) { + var async = false + + db.batch([{ key: 'key', value: 'value', type: 'foo' }], function (err) { + t.ok(err, 'got error') + t.equal(err.message, "`type` must be 'put' or 'del'", 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with missing array', function (t) { + var async = false + + db.batch(function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'batch(array) requires an array argument', 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with undefined array', function (t) { + var async = false + + db.batch(undefined, function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'batch(array) requires an array argument', 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with null array', function (t) { + var async = false + + db.batch(null, function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'batch(array) requires an array argument', 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test batch() with null options', function (t) { + db.batch([], null, function (err) { + t.error(err) + t.end() + }) + }) + + ;[null, undefined, 1, true].forEach(function (element) { + var type = element === null ? 'null' : typeof element + + test('test batch() with ' + type + ' element', function (t) { + var async = false + + db.batch([element], function (err) { + t.ok(err, 'got error') + t.equal(err.message, 'batch(array) element must be an object and not `null`', 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + }) + + test('test batch() with empty array', function (t) { + var async = false + + db.batch([], function (err) { + t.error(err, 'no error from batch()') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) +} + +exports.batch = function (test, testCommon) { + test('test simple batch()', function (t) { + db.batch([{ type: 'put', key: 'foo', value: 'bar' }], function (err) { + t.error(err) + + db.get('foo', function (err, value) { + t.error(err) + var result + if (isTypedArray(value)) { + result = String.fromCharCode.apply(null, new Uint16Array(value)) + } else { + t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer) + result = value.toString() + } + t.equal(result, 'bar') + t.end() + }) + }) + }) + + test('test multiple batch()', function (t) { + db.batch([ + { type: 'put', key: 'foobatch1', value: 'bar1' }, + { type: 'put', key: 'foobatch2', value: 'bar2' }, + { type: 'put', key: 'foobatch3', value: 'bar3' }, + { type: 'del', key: 'foobatch2' } + ], function (err) { + t.error(err) + + var r = 0 + var done = function () { + if (++r === 3) { t.end() } + } + + db.get('foobatch1', function (err, value) { + t.error(err) + var result + if (isTypedArray(value)) { + result = String.fromCharCode.apply(null, new Uint16Array(value)) + } else { + t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer) + result = value.toString() + } + t.equal(result, 'bar1') + done() + }) + + db.get('foobatch2', function (err, value) { + t.ok(err, 'entry not found') + t.ok(typeof value === 'undefined', 'value is undefined') + t.ok(verifyNotFoundError(err), 'NotFound error') + done() + }) + + db.get('foobatch3', function (err, value) { + t.error(err) + var result + if (isTypedArray(value)) { + result = String.fromCharCode.apply(null, new Uint16Array(value)) + } else { + t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer) + result = value.toString() + } + t.equal(result, 'bar3') + done() + }) + }) + }) +} + +exports.atomic = function (test, testCommon) { + test('test multiple batch()', function (t) { + t.plan(4) + + var async = false + + db.batch([ + { type: 'put', key: 'foobah1', value: 'bar1' }, + { type: 'put', value: 'bar2' }, + { type: 'put', key: 'foobah3', value: 'bar3' } + ], function (err) { + t.ok(err, 'should error') + t.ok(async, 'callback is asynchronous') + + db.get('foobah1', function (err) { + t.ok(err, 'should not be found') + }) + db.get('foobah3', function (err) { + t.ok(err, 'should not be found') + }) + }) + + async = true + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.batch(test, testCommon) + exports.atomic(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/chained-batch-test.js b/nodejs/node_modules/abstract-leveldown/test/chained-batch-test.js new file mode 100644 index 00000000..6bb2adf1 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/chained-batch-test.js @@ -0,0 +1,298 @@ +var collectEntries = require('level-concat-iterator') + +var db + +function collectBatchOps (batch) { + var _put = batch._put + var _del = batch._del + var _operations = [] + + if (typeof _put !== 'function' || typeof _del !== 'function') { + return batch._operations + } + + batch._put = function (key, value) { + _operations.push({ type: 'put', key: key, value: value }) + return _put.apply(this, arguments) + } + + batch._del = function (key) { + _operations.push({ type: 'del', key: key }) + return _del.apply(this, arguments) + } + + return _operations +} + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test batch has db reference', function (t) { + t.ok(db.batch().db === db) + t.end() + }) + + test('test batch#put() with missing `value`', function (t) { + t.plan(1) + + try { + db.batch().put('foo1') + } catch (err) { + t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message') + } + }) + + test('test batch#put() with missing `key`', function (t) { + try { + db.batch().put(undefined, 'foo1') + } catch (err) { + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#put() with null `key`', function (t) { + try { + db.batch().put(null, 'foo1') + } catch (err) { + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#put() with missing `key` and `value`', function (t) { + try { + db.batch().put() + } catch (err) { + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#put() with null or undefined `value`', function (t) { + var illegalValues = [null, undefined] + t.plan(illegalValues.length) + + illegalValues.forEach(function (value) { + try { + db.batch().put('key', value) + } catch (err) { + t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message') + } + }) + }) + + test('test batch#del() with missing `key`', function (t) { + try { + db.batch().del() + } catch (err) { + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#del() with null or undefined `key`', function (t) { + var illegalKeys = [null, undefined] + t.plan(illegalKeys.length) + + illegalKeys.forEach(function (key) { + try { + db.batch().del(key) + } catch (err) { + t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message') + } + }) + }) + + test('test batch#clear() doesn\'t throw', function (t) { + db.batch().clear() + t.end() + }) + + test('test batch#write() with no callback', function (t) { + try { + db.batch().write() + } catch (err) { + t.equal(err.message, 'write() requires a callback argument', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#put() after write()', function (t) { + var batch = db.batch().put('foo', 'bar') + batch.write(function () {}) + try { + batch.put('boom', 'bang') + } catch (err) { + t.equal(err.message, 'write() already called on this batch', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#del() after write()', function (t) { + var batch = db.batch().put('foo', 'bar') + batch.write(function () {}) + try { + batch.del('foo') + } catch (err) { + t.equal(err.message, 'write() already called on this batch', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#clear() after write()', function (t) { + var batch = db.batch().put('foo', 'bar') + batch.write(function () {}) + try { + batch.clear() + } catch (err) { + t.equal(err.message, 'write() already called on this batch', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test batch#write() after write()', function (t) { + var batch = db.batch().put('foo', 'bar') + batch.write(function () {}) + try { + batch.write(function () {}) + } catch (err) { + t.equal(err.message, 'write() already called on this batch', 'correct error message') + return t.end() + } + t.fail('should have thrown') + t.end() + }) + + test('test serialize object', function (t) { + var batch = db.batch() + var ops = collectBatchOps(batch) + + batch + .put({ foo: 'bar' }, { beep: 'boop' }) + .del({ bar: 'baz' }) + ops.forEach(function (op) { + t.ok(op.key, '.key is set for .put and .del operations') + if (op.type === 'put') { + t.ok(op.value, '.value is set for .put operation') + } + }) + t.end() + }) + + test('test custom _serialize*', function (t) { + t.plan(4) + + var _db = Object.create(db) + var batch = _db.batch() + var ops = collectBatchOps(batch) + + _db._serializeKey = function (key) { + t.same(key, { foo: 'bar' }) + return 'key1' + } + + _db._serializeValue = function (value) { + t.same(value, { beep: 'boop' }) + return 'value1' + } + + batch.put({ foo: 'bar' }, { beep: 'boop' }) + + _db._serializeKey = function (key) { + t.same(key, { bar: 'baz' }) + return 'key2' + } + + batch.del({ bar: 'baz' }) + + t.deepEqual(ops, [ + { type: 'put', key: 'key1', value: 'value1' }, + { type: 'del', key: 'key2' } + ]) + }) + + test('test batch#write() with no operations', function (t) { + var async = false + + db.batch().write(function (err) { + t.ifError(err, 'no error from write()') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) +} + +exports.batch = function (test, testCommon) { + test('test basic batch', function (t) { + db.batch([ + { type: 'put', key: 'one', value: '1' }, + { type: 'put', key: 'two', value: '2' }, + { type: 'put', key: 'three', value: '3' } + ], function (err) { + t.error(err) + db.batch() + .put('1', 'one') + .del('2', 'two') + .put('3', 'three') + .clear() + .put('one', 'I') + .put('two', 'II') + .del('three') + .put('foo', 'bar') + .write(function (err) { + t.error(err) + collectEntries( + db.iterator({ keyAsBuffer: false, valueAsBuffer: false }), function (err, data) { + t.error(err) + t.equal(data.length, 3, 'correct number of entries') + var expected = [ + { key: 'foo', value: 'bar' }, + { key: 'one', value: 'I' }, + { key: 'two', value: 'II' } + ] + t.deepEqual(data, expected) + t.end() + } + ) + }) + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.batch(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/clear-range-test.js b/nodejs/node_modules/abstract-leveldown/test/clear-range-test.js new file mode 100644 index 00000000..21586318 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/clear-range-test.js @@ -0,0 +1,258 @@ +var concat = require('level-concat-iterator') + +var data = (function () { + var d = [] + var i = 0 + var k + for (; i < 100; i++) { + k = (i < 10 ? '0' : '') + i + d.push({ + key: k, + value: String(Math.random()) + }) + } + return d +}()) + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) +} + +exports.range = function (test, testCommon) { + function rangeTest (name, opts, expected) { + test('db#clear() with ' + name, function (t) { + prepare(t, function (db) { + db.clear(opts, function (err) { + t.ifError(err, 'no clear error') + verify(t, db, expected) + }) + }) + }) + } + + function prepare (t, callback) { + var db = testCommon.factory() + + db.open(function (err) { + t.ifError(err, 'no open error') + + db.batch(data.map(function (d) { + return { + type: 'put', + key: d.key, + value: d.value + } + }), function (err) { + t.ifError(err, 'no batch error') + callback(db) + }) + }) + } + + function verify (t, db, expected) { + var it = db.iterator({ keyAsBuffer: false, valueAsBuffer: false }) + + concat(it, function (err, result) { + t.ifError(err, 'no concat error') + t.is(result.length, expected.length, 'correct number of entries') + t.same(result, expected) + + db.close(t.end.bind(t)) + }) + } + + function exclude (data, start, end, expectedLength) { + data = data.slice() + var removed = data.splice(start, end - start + 1) // Inclusive + if (expectedLength != null) checkLength(removed, expectedLength) + return data + } + + // For sanity checks on test arguments + function checkLength (arr, length) { + if (arr.length !== length) { + throw new RangeError('Expected ' + length + ' elements, got ' + arr.length) + } + + return arr + } + + rangeTest('full range', {}, []) + + // Reversing has no effect without limit + rangeTest('reverse=true', { + reverse: true + }, []) + + rangeTest('gte=00', { + gte: '00' + }, []) + + rangeTest('gte=50', { + gte: '50' + }, data.slice(0, 50)) + + rangeTest('lte=50 and reverse=true', { + lte: '50', + reverse: true + }, data.slice(51)) + + rangeTest('gte=49.5 (midway)', { + gte: '49.5' + }, data.slice(0, 50)) + + rangeTest('gte=49999 (midway)', { + gte: '49999' + }, data.slice(0, 50)) + + rangeTest('lte=49.5 (midway) and reverse=true', { + lte: '49.5', + reverse: true + }, data.slice(50)) + + rangeTest('lt=49.5 (midway) and reverse=true', { + lt: '49.5', + reverse: true + }, data.slice(50)) + + rangeTest('lt=50 and reverse=true', { + lt: '50', + reverse: true + }, data.slice(50)) + + rangeTest('lte=50', { + lte: '50' + }, data.slice(51)) + + rangeTest('lte=50.5 (midway)', { + lte: '50.5' + }, data.slice(51)) + + rangeTest('lte=50555 (midway)', { + lte: '50555' + }, data.slice(51)) + + rangeTest('lt=50555 (midway)', { + lt: '50555' + }, data.slice(51)) + + rangeTest('gte=50.5 (midway) and reverse=true', { + gte: '50.5', + reverse: true + }, data.slice(0, 51)) + + rangeTest('gt=50.5 (midway) and reverse=true', { + gt: '50.5', + reverse: true + }, data.slice(0, 51)) + + rangeTest('gt=50 and reverse=true', { + gt: '50', + reverse: true + }, data.slice(0, 51)) + + // Starting key is actually '00' so it should avoid it + rangeTest('lte=0', { + lte: '0' + }, data) + + // Starting key is actually '00' so it should avoid it + rangeTest('lt=0', { + lt: '0' + }, data) + + rangeTest('gte=30 and lte=70', { + gte: '30', + lte: '70' + }, exclude(data, 30, 70)) + + rangeTest('gt=29 and lt=71', { + gt: '29', + lt: '71' + }, exclude(data, 30, 70)) + + rangeTest('gte=30 and lte=70 and reverse=true', { + lte: '70', + gte: '30', + reverse: true + }, exclude(data, 30, 70)) + + rangeTest('gt=29 and lt=71 and reverse=true', { + lt: '71', + gt: '29', + reverse: true + }, exclude(data, 30, 70)) + + rangeTest('limit=20', { + limit: 20 + }, data.slice(20)) + + rangeTest('limit=20 and gte=20', { + limit: 20, + gte: '20' + }, exclude(data, 20, 39, 20)) + + rangeTest('limit=20 and reverse=true', { + limit: 20, + reverse: true + }, data.slice(0, -20)) + + rangeTest('limit=20 and lte=79 and reverse=true', { + limit: 20, + lte: '79', + reverse: true + }, exclude(data, 60, 79, 20)) + + rangeTest('limit=-1 should clear whole database', { + limit: -1 + }, []) + + rangeTest('limit=0 should not clear anything', { + limit: 0 + }, data) + + rangeTest('lte after limit', { + limit: 20, + lte: '50' + }, data.slice(20)) + + rangeTest('lte before limit', { + limit: 50, + lte: '19' + }, data.slice(20)) + + rangeTest('gte after database end', { + gte: '9a' + }, data) + + rangeTest('gt after database end', { + gt: '9a' + }, data) + + rangeTest('lte after database end and reverse=true', { + lte: '9a', + reverse: true + }, []) + + rangeTest('lte and gte after database and reverse=true', { + lte: '9b', + gte: '9a', + reverse: true + }, data) + + rangeTest('lt and gt after database and reverse=true', { + lt: '9b', + gt: '9a', + reverse: true + }, data) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.range(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/clear-test.js b/nodejs/node_modules/abstract-leveldown/test/clear-test.js new file mode 100644 index 00000000..d338cad0 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/clear-test.js @@ -0,0 +1,83 @@ +var concat = require('level-concat-iterator') +var db + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test argument-less clear() throws', function (t) { + t.throws( + db.clear.bind(db), + /Error: clear\(\) requires a callback argument/, + 'no-arg clear() throws' + ) + t.end() + }) +} + +exports.clear = function (test, testCommon) { + makeTest('string', ['a', 'b']) + + if (testCommon.bufferKeys) { + makeTest('buffer', [Buffer.from('a'), Buffer.from('b')]) + makeTest('mixed', [Buffer.from('a'), 'b']) + + // These keys would be equal when compared as utf8 strings + makeTest('non-utf8 buffer', [Buffer.from('80', 'hex'), Buffer.from('c0', 'hex')]) + } + + function makeTest (type, keys) { + test('test simple clear() on ' + type + ' keys', function (t) { + t.plan(8) + + var db = testCommon.factory() + var ops = keys.map(function (key) { + return { type: 'put', key: key, value: 'foo' } + }) + + db.open(function (err) { + t.ifError(err, 'no open error') + + db.batch(ops, function (err) { + t.ifError(err, 'no batch error') + + concat(db.iterator(), function (err, entries) { + t.ifError(err, 'no concat error') + t.is(entries.length, keys.length, 'has entries') + + db.clear(function (err) { + t.ifError(err, 'no clear error') + + concat(db.iterator(), function (err, entries) { + t.ifError(err, 'no concat error') + t.is(entries.length, 0, 'has no entries') + + db.close(function (err) { + t.ifError(err, 'no close error') + }) + }) + }) + }) + }) + }) + }) + } +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.clear(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/close-test.js b/nodejs/node_modules/abstract-leveldown/test/close-test.js new file mode 100644 index 00000000..d70a06fb --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/close-test.js @@ -0,0 +1,39 @@ +var db + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.close = function (test, testCommon) { + test('test close()', function (t) { + t.throws( + db.close.bind(db), + /Error: close\(\) requires a callback argument/, + 'no-arg close() throws' + ) + t.throws( + db.close.bind(db, 'foo'), + /Error: close\(\) requires a callback argument/, + 'non-callback close() throws' + ) + + db.close(function (err) { + t.error(err) + t.end() + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.close(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/common.js b/nodejs/node_modules/abstract-leveldown/test/common.js new file mode 100644 index 00000000..cdc216ba --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/common.js @@ -0,0 +1,37 @@ +function testCommon (options) { + var factory = options.factory + var test = options.test + + if (typeof factory !== 'function') { + throw new TypeError('factory must be a function') + } + + if (typeof test !== 'function') { + throw new TypeError('test must be a function') + } + + return { + test: test, + factory: factory, + + // TODO (next major): remove + setUp: options.setUp || noopTest(), + tearDown: options.tearDown || noopTest(), + + // TODO (next major): use db.supports instead + bufferKeys: options.bufferKeys !== false, + createIfMissing: options.createIfMissing !== false, + errorIfExists: options.errorIfExists !== false, + snapshots: options.snapshots !== false, + seek: options.seek !== false, + clear: !!options.clear + } +} + +function noopTest () { + return function (t) { + t.end() + } +} + +module.exports = testCommon diff --git a/nodejs/node_modules/abstract-leveldown/test/del-test.js b/nodejs/node_modules/abstract-leveldown/test/del-test.js new file mode 100644 index 00000000..9dbea61a --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/del-test.js @@ -0,0 +1,92 @@ +var db +var verifyNotFoundError = require('./util').verifyNotFoundError + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test argument-less del() throws', function (t) { + t.throws( + db.del.bind(db), + /Error: del\(\) requires a callback argument/, + 'no-arg del() throws' + ) + t.end() + }) + + test('test callback-less, 1-arg, del() throws', function (t) { + t.throws( + db.del.bind(db, 'foo'), + /Error: del\(\) requires a callback argument/, + 'callback-less, 1-arg del() throws' + ) + t.end() + }) + + test('test callback-less, 3-arg, del() throws', function (t) { + t.throws( + db.del.bind(db, 'foo', {}), + /Error: del\(\) requires a callback argument/, + 'callback-less, 2-arg del() throws' + ) + t.end() + }) + + test('test custom _serialize*', function (t) { + t.plan(3) + var db = testCommon.factory() + db._serializeKey = function (data) { return data } + db._del = function (key, options, callback) { + t.deepEqual(key, { foo: 'bar' }) + process.nextTick(callback) + } + db.open(function () { + db.del({ foo: 'bar' }, function (err) { + t.error(err) + db.close(t.error.bind(t)) + }) + }) + }) +} + +exports.del = function (test, testCommon) { + test('test simple del()', function (t) { + db.put('foo', 'bar', function (err) { + t.error(err) + db.del('foo', function (err) { + t.error(err) + db.get('foo', function (err, value) { + t.ok(err, 'entry properly deleted') + t.ok(typeof value === 'undefined', 'value is undefined') + t.ok(verifyNotFoundError(err), 'NotFound error') + t.end() + }) + }) + }) + }) + + test('test del on non-existent key', function (t) { + db.del('blargh', function (err) { + t.error(err) + t.end() + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.del(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/factory-test.js b/nodejs/node_modules/abstract-leveldown/test/factory-test.js new file mode 100644 index 00000000..4e1413ff --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/factory-test.js @@ -0,0 +1,37 @@ +var concat = require('level-concat-iterator') + +module.exports = function (test, testCommon) { + test('setUp common', testCommon.setUp) + + test('testCommon.factory() returns a unique database', function (t) { + var db1 = testCommon.factory() + var db2 = testCommon.factory() + + function close () { + db1.close(function (err) { + t.error(err, 'no error while closing db1') + db2.close(function (err) { + t.error(err, 'no error while closing db2') + t.end() + }) + }) + } + + db1.open(function (err) { + t.error(err, 'no error while opening db1') + db2.open(function (err) { + t.error(err, 'no error while opening db2') + db1.put('key', 'value', function (err) { + t.error(err, 'put key in db1') + concat(db2.iterator(), function (err, entries) { + t.error(err, 'got items from db2') + t.same(entries, [], 'db2 should be empty') + close() + }) + }) + }) + }) + }) + + test('tearDown', testCommon.tearDown) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/get-test.js b/nodejs/node_modules/abstract-leveldown/test/get-test.js new file mode 100644 index 00000000..8b5190fa --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/get-test.js @@ -0,0 +1,169 @@ +var db +var verifyNotFoundError = require('./util').verifyNotFoundError +var isTypedArray = require('./util').isTypedArray + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test argument-less get() throws', function (t) { + t.throws( + db.get.bind(db), + /Error: get\(\) requires a callback argument/, + 'no-arg get() throws' + ) + t.end() + }) + + test('test callback-less, 1-arg, get() throws', function (t) { + t.throws( + db.get.bind(db, 'foo'), + /Error: get\(\) requires a callback argument/, + 'callback-less, 1-arg get() throws' + ) + t.end() + }) + + test('test callback-less, 3-arg, get() throws', function (t) { + t.throws( + db.get.bind(db, 'foo', {}), + /Error: get\(\) requires a callback argument/, + 'callback-less, 2-arg get() throws' + ) + t.end() + }) + + test('test custom _serialize*', function (t) { + t.plan(3) + var db = testCommon.factory() + db._serializeKey = function (data) { return data } + db._get = function (key, options, callback) { + t.deepEqual(key, { foo: 'bar' }) + process.nextTick(callback) + } + db.open(function () { + db.get({ foo: 'bar' }, function (err) { + t.error(err) + db.close(t.error.bind(t)) + }) + }) + }) +} + +exports.get = function (test, testCommon) { + test('test simple get()', function (t) { + db.put('foo', 'bar', function (err) { + t.error(err) + db.get('foo', function (err, value) { + t.error(err) + t.ok(typeof value !== 'string', 'should not be string by default') + + var result + if (isTypedArray(value)) { + result = String.fromCharCode.apply(null, new Uint16Array(value)) + } else { + t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer) + try { + result = value.toString() + } catch (e) { + t.error(e, 'should not throw when converting value to a string') + } + } + + t.equal(result, 'bar') + + db.get('foo', {}, function (err, value) { // same but with {} + t.error(err) + t.ok(typeof value !== 'string', 'should not be string by default') + + var result + if (isTypedArray(value)) { + result = String.fromCharCode.apply(null, new Uint16Array(value)) + } else { + t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer) + try { + result = value.toString() + } catch (e) { + t.error(e, 'should not throw when converting value to a string') + } + } + + t.equal(result, 'bar') + + db.get('foo', { asBuffer: false }, function (err, value) { + t.error(err) + t.ok(typeof value === 'string', 'should be string if not buffer') + t.equal(value, 'bar') + t.end() + }) + }) + }) + }) + }) + + test('test simultaniously get()', function (t) { + db.put('hello', 'world', function (err) { + t.error(err) + var r = 0 + var done = function () { + if (++r === 20) { t.end() } + } + var i = 0 + var j = 0 + + for (; i < 10; ++i) { + db.get('hello', function (err, value) { + t.error(err) + t.equal(value.toString(), 'world') + done() + }) + } + + for (; j < 10; ++j) { + db.get('not found', function (err, value) { + t.ok(err, 'should error') + t.ok(verifyNotFoundError(err), 'should have correct error message') + t.ok(typeof value === 'undefined', 'value is undefined') + done() + }) + } + }) + }) + + test('test get() not found error is asynchronous', function (t) { + t.plan(5) + + db.put('hello', 'world', function (err) { + t.error(err) + + var async = false + + db.get('not found', function (err, value) { + t.ok(err, 'should error') + t.ok(verifyNotFoundError(err), 'should have correct error message') + t.ok(typeof value === 'undefined', 'value is undefined') + t.ok(async, 'callback is asynchronous') + }) + + async = true + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.get(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/index.js b/nodejs/node_modules/abstract-leveldown/test/index.js new file mode 100644 index 00000000..1ef97afc --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/index.js @@ -0,0 +1,50 @@ +var common = require('./common') + +function suite (options) { + var testCommon = common(options) + var test = testCommon.test + + require('./factory-test')(test, testCommon) + require('./manifest-test')(test, testCommon) + + require('./leveldown-test')(test, testCommon) + require('./open-test').all(test, testCommon) + require('./close-test').all(test, testCommon) + + if (testCommon.createIfMissing) { + require('./open-create-if-missing-test').all(test, testCommon) + } + + if (testCommon.errorIfExists) { + require('./open-error-if-exists-test').all(test, testCommon) + } + + require('./put-test').all(test, testCommon) + require('./get-test').all(test, testCommon) + require('./del-test').all(test, testCommon) + require('./put-get-del-test').all(test, testCommon) + + require('./batch-test').all(test, testCommon) + require('./chained-batch-test').all(test, testCommon) + + require('./iterator-test').all(test, testCommon) + require('./iterator-range-test').all(test, testCommon) + + if (testCommon.seek) { + require('./iterator-seek-test').all(test, testCommon) + } + + if (testCommon.snapshots) { + require('./iterator-snapshot-test').all(test, testCommon) + } else { + require('./iterator-no-snapshot-test').all(test, testCommon) + } + + if (testCommon.clear) { + require('./clear-test').all(test, testCommon) + require('./clear-range-test').all(test, testCommon) + } +} + +suite.common = common +module.exports = suite diff --git a/nodejs/node_modules/abstract-leveldown/test/iterator-no-snapshot-test.js b/nodejs/node_modules/abstract-leveldown/test/iterator-no-snapshot-test.js new file mode 100644 index 00000000..c90df904 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/iterator-no-snapshot-test.js @@ -0,0 +1,72 @@ +var collectEntries = require('level-concat-iterator') + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) +} + +exports.noSnapshot = function (test, testCommon) { + function make (run) { + return function (t) { + var db = testCommon.factory() + var operations = [ + { type: 'put', key: 'a', value: 'a' }, + { type: 'put', key: 'b', value: 'b' }, + { type: 'put', key: 'c', value: 'c' } + ] + + db.open(function (err) { + t.ifError(err, 'no open error') + + db.batch(operations, function (err) { + t.ifError(err, 'no batch error') + + // For this test it is important that we don't read eagerly. + // NOTE: highWaterMark is not an abstract option atm, but + // it is supported by leveldown, rocksdb and others. + var it = db.iterator({ highWaterMark: 0 }) + + run(db, function (err) { + t.ifError(err, 'no run error') + verify(t, it, db) + }) + }) + }) + } + } + + function verify (t, it, db) { + collectEntries(it, function (err, entries) { + t.ifError(err, 'no iterator error') + + var kv = entries.map(function (entry) { + return entry.key.toString() + entry.value.toString() + }) + + if (kv.length === 3) { + t.same(kv, ['aa', 'bb', 'cc'], 'maybe supports snapshots') + } else { + t.same(kv, ['aa', 'cc'], 'ignores keys that have been deleted in the mean time') + } + + db.close(t.end.bind(t)) + }) + } + + test('delete key after creating iterator', make(function (db, done) { + db.del('b', done) + })) + + test('batch delete key after creating iterator', make(function (db, done) { + db.batch([{ type: 'del', key: 'b' }], done) + })) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.noSnapshot(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/iterator-range-test.js b/nodejs/node_modules/abstract-leveldown/test/iterator-range-test.js new file mode 100644 index 00000000..3d5c0909 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/iterator-range-test.js @@ -0,0 +1,381 @@ +var collectEntries = require('level-concat-iterator') +var xtend = require('xtend') + +var db + +var data = (function () { + var d = [] + var i = 0 + var k + for (; i < 100; i++) { + k = (i < 10 ? '0' : '') + i + d.push({ + key: k, + value: String(Math.random()) + }) + } + return d +}()) + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(function () { + db.batch(data.map(function (d) { + return { + type: 'put', + key: d.key, + value: d.value + } + }), t.end.bind(t)) + }) + }) +} + +exports.range = function (test, testCommon) { + function rangeTest (name, opts, expected) { + opts.keyAsBuffer = false + opts.valueAsBuffer = false + test(name, function (t) { + collectEntries(db.iterator(opts), function (err, result) { + t.error(err) + t.is(result.length, expected.length, 'correct number of entries') + t.same(result, expected) + t.end() + }) + }) + + // Test the documented promise that in reverse mode, + // "the returned entries are the same, but in reverse". + if (!opts.reverse && !('limit' in opts)) { + var reverseOpts = xtend(opts, { reverse: true }) + + // Swap start & end options + if (('start' in opts) && ('end' in opts)) { + reverseOpts.end = opts.start + reverseOpts.start = opts.end + } else if ('start' in opts) { + reverseOpts.end = opts.start + delete reverseOpts.start + } else if ('end' in opts) { + reverseOpts.start = opts.end + delete reverseOpts.end + } + + rangeTest( + name + ' (flipped)', + reverseOpts, + expected.slice().reverse() + ) + } + } + + rangeTest('test full data collection', {}, data) + + rangeTest('test iterator with reverse=true', { + reverse: true + }, data.slice().reverse()) + + rangeTest('test iterator with gte=00', { + gte: '00' + }, data) + + rangeTest('test iterator with start=00 - legacy', { + start: '00' + }, data) + + rangeTest('test iterator with gte=50', { + gte: '50' + }, data.slice(50)) + + rangeTest('test iterator with start=50 - legacy', { + start: '50' + }, data.slice(50)) + + rangeTest('test iterator with lte=50 and reverse=true', { + lte: '50', + reverse: true + }, data.slice().reverse().slice(49)) + + rangeTest('test iterator with start=50 and reverse=true - legacy', { + start: '50', + reverse: true + }, data.slice().reverse().slice(49)) + + rangeTest('test iterator with gte=49.5 (midway)', { + gte: '49.5' + }, data.slice(50)) + + rangeTest('test iterator with start=49.5 (midway) - legacy', { + start: '49.5' + }, data.slice(50)) + + rangeTest('test iterator with gte=49999 (midway)', { + gte: '49999' + }, data.slice(50)) + + rangeTest('test iterator with start=49999 (midway) - legacy', { + start: '49999' + }, data.slice(50)) + + rangeTest('test iterator with lte=49.5 (midway) and reverse=true', { + lte: '49.5', + reverse: true + }, data.slice().reverse().slice(50)) + + rangeTest('test iterator with lt=49.5 (midway) and reverse=true', { + lt: '49.5', + reverse: true + }, data.slice().reverse().slice(50)) + + rangeTest('test iterator with lt=50 and reverse=true', { + lt: '50', + reverse: true + }, data.slice().reverse().slice(50)) + + rangeTest('test iterator with start=49.5 (midway) and reverse=true - legacy', { + start: '49.5', + reverse: true + }, data.slice().reverse().slice(50)) + + rangeTest('test iterator with lte=50', { + lte: '50' + }, data.slice(0, 51)) + + rangeTest('test iterator with end=50 - legacy', { + end: '50' + }, data.slice(0, 51)) + + rangeTest('test iterator with lte=50.5 (midway)', { + lte: '50.5' + }, data.slice(0, 51)) + + rangeTest('test iterator with end=50.5 (midway) - legacy', { + end: '50.5' + }, data.slice(0, 51)) + + rangeTest('test iterator with lte=50555 (midway)', { + lte: '50555' + }, data.slice(0, 51)) + + rangeTest('test iterator with lt=50555 (midway)', { + lt: '50555' + }, data.slice(0, 51)) + + rangeTest('test iterator with end=50555 (midway) - legacy', { + end: '50555' + }, data.slice(0, 51)) + + rangeTest('test iterator with gte=50.5 (midway) and reverse=true', { + gte: '50.5', + reverse: true + }, data.slice().reverse().slice(0, 49)) + + rangeTest('test iterator with gt=50.5 (midway) and reverse=true', { + gt: '50.5', + reverse: true + }, data.slice().reverse().slice(0, 49)) + + rangeTest('test iterator with end=50.5 (midway) and reverse=true - legacy', { + end: '50.5', + reverse: true + }, data.slice().reverse().slice(0, 49)) + + rangeTest('test iterator with gt=50 and reverse=true', { + gt: '50', + reverse: true + }, data.slice().reverse().slice(0, 49)) + + // end='0', starting key is actually '00' so it should avoid it + rangeTest('test iterator with lte=0', { + lte: '0' + }, []) + + // end='0', starting key is actually '00' so it should avoid it + rangeTest('test iterator with lt=0', { + lt: '0' + }, []) + + // end='0', starting key is actually '00' so it should avoid it + rangeTest('test iterator with end=0 - legacy', { + end: '0' + }, []) + + rangeTest('test iterator with gte=30 and lte=70', { + gte: '30', + lte: '70' + }, data.slice(30, 71)) + + rangeTest('test iterator with gt=29 and lt=71', { + gt: '29', + lt: '71' + }, data.slice(30, 71)) + + rangeTest('test iterator with start=30 and end=70 - legacy', { + start: '30', + end: '70' + }, data.slice(30, 71)) + + rangeTest('test iterator with gte=30 and lte=70 and reverse=true', { + lte: '70', + gte: '30', + reverse: true + }, data.slice().reverse().slice(29, 70)) + + rangeTest('test iterator with gt=29 and lt=71 and reverse=true', { + lt: '71', + gt: '29', + reverse: true + }, data.slice().reverse().slice(29, 70)) + + rangeTest('test iterator with start=70 and end=30 and reverse=true - legacy', { + start: '70', + end: '30', + reverse: true + }, data.slice().reverse().slice(29, 70)) + + rangeTest('test iterator with limit=20', { + limit: 20 + }, data.slice(0, 20)) + + rangeTest('test iterator with limit=20 and gte=20', { + limit: 20, + gte: '20' + }, data.slice(20, 40)) + + rangeTest('test iterator with limit=20 and start=20 - legacy', { + limit: 20, + start: '20' + }, data.slice(20, 40)) + + rangeTest('test iterator with limit=20 and reverse=true', { + limit: 20, + reverse: true + }, data.slice().reverse().slice(0, 20)) + + rangeTest('test iterator with limit=20 and lte=79 and reverse=true', { + limit: 20, + lte: '79', + reverse: true + }, data.slice().reverse().slice(20, 40)) + + rangeTest('test iterator with limit=20 and start=79 and reverse=true - legacy', { + limit: 20, + start: '79', + reverse: true + }, data.slice().reverse().slice(20, 40)) + + // the default limit value from levelup is -1 + rangeTest('test iterator with limit=-1 should iterate over whole database', { + limit: -1 + }, data) + + rangeTest('test iterator with limit=0 should not iterate over anything', { + limit: 0 + }, []) + + rangeTest('test iterator with lte after limit', { + limit: 20, + lte: '50' + }, data.slice(0, 20)) + + rangeTest('test iterator with end after limit - legacy', { + limit: 20, + end: '50' + }, data.slice(0, 20)) + + rangeTest('test iterator with lte before limit', { + limit: 50, + lte: '19' + }, data.slice(0, 20)) + + rangeTest('test iterator with end before limit - legacy', { + limit: 50, + end: '19' + }, data.slice(0, 20)) + + rangeTest('test iterator with gte after database end', { + gte: '9a' + }, []) + + rangeTest('test iterator with gt after database end', { + gt: '9a' + }, []) + + rangeTest('test iterator with start after database end - legacy', { + start: '9a' + }, []) + + rangeTest('test iterator with lte after database end and reverse=true', { + lte: '9a', + reverse: true + }, data.slice().reverse()) + + rangeTest('test iterator with start after database end and reverse=true - legacy', { + start: '9a', + reverse: true + }, data.slice().reverse()) + + rangeTest('test iterator with lt after database end', { + lt: 'a' + }, data.slice()) + + rangeTest('test iterator with end after database end - legacy', { + end: 'a' + }, data.slice()) + + rangeTest('test iterator with lt at database end', { + lt: data[data.length - 1].key + }, data.slice(0, -1)) + + rangeTest('test iterator with lte at database end', { + lte: data[data.length - 1].key + }, data.slice()) + + rangeTest('test iterator with end at database end - legacy', { + end: data[data.length - 1].key + }, data.slice()) + + rangeTest('test iterator with lt before database end', { + lt: data[data.length - 2].key + }, data.slice(0, -2)) + + rangeTest('test iterator with lte before database end', { + lte: data[data.length - 2].key + }, data.slice(0, -1)) + + rangeTest('test iterator with end before database end - legacy', { + end: data[data.length - 2].key + }, data.slice(0, -1)) + + rangeTest('test iterator with lte and gte after database and reverse=true', { + lte: '9b', + gte: '9a', + reverse: true + }, []) + + rangeTest('test iterator with lt and gt after database and reverse=true', { + lt: '9b', + gt: '9a', + reverse: true + }, []) + + rangeTest('test iterator with start and end after database and reverse=true - legacy', { + start: '9b', + end: '9a', + reverse: true + }, []) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.range(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/iterator-seek-test.js b/nodejs/node_modules/abstract-leveldown/test/iterator-seek-test.js new file mode 100644 index 00000000..d153c9a0 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/iterator-seek-test.js @@ -0,0 +1,281 @@ +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.sequence(test, testCommon) + exports.seek(test, testCommon) + exports.tearDown(test, testCommon) +} + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) +} + +exports.sequence = function (test, testCommon) { + function make (name, testFn) { + test(name, function (t) { + var db = testCommon.factory() + var done = function (err) { + t.error(err, 'no error from done()') + + db.close(function (err) { + t.error(err, 'no error from close()') + t.end() + }) + } + + db.open(function (err) { + t.error(err, 'no error from open()') + testFn(db, t, done) + }) + }) + } + + make('iterator#seek() throws if next() has not completed', function (db, t, done) { + var ite = db.iterator() + var error + var async = false + + ite.next(function (err, key, value) { + t.error(err, 'no error from next()') + t.ok(async, 'next is asynchronous') + ite.end(done) + }) + + async = true + + try { + ite.seek('two') + } catch (err) { + error = err.message + } + + t.is(error, 'cannot call seek() before next() has completed', 'got error') + }) + + make('iterator#seek() throws after end()', function (db, t, done) { + var ite = db.iterator() + + // TODO: why call next? Can't we end immediately? + ite.next(function (err, key, value) { + t.error(err, 'no error from next()') + + ite.end(function (err) { + t.error(err, 'no error from end()') + var error + + try { + ite.seek('two') + } catch (err) { + error = err.message + } + + t.is(error, 'cannot call seek() after end()', 'got error') + done() + }) + }) + }) +} + +exports.seek = function (test, testCommon) { + function make (name, testFn) { + test(name, function (t) { + var db = testCommon.factory() + var done = function (err) { + t.error(err, 'no error from done()') + + db.close(function (err) { + t.error(err, 'no error from close()') + t.end() + }) + } + + db.open(function (err) { + t.error(err, 'no error from open()') + + db.batch([ + { type: 'put', key: 'one', value: '1' }, + { type: 'put', key: 'two', value: '2' }, + { type: 'put', key: 'three', value: '3' } + ], function (err) { + t.error(err, 'no error from batch()') + testFn(db, t, done) + }) + }) + }) + } + + make('iterator#seek() to string target', function (db, t, done) { + var ite = db.iterator() + ite.seek('two') + ite.next(function (err, key, value) { + t.error(err, 'no error') + t.same(key.toString(), 'two', 'key matches') + t.same(value.toString(), '2', 'value matches') + ite.next(function (err, key, value) { + t.error(err, 'no error') + t.same(key, undefined, 'end of iterator') + t.same(value, undefined, 'end of iterator') + ite.end(done) + }) + }) + }) + + if (testCommon.bufferKeys) { + make('iterator#seek() to buffer target', function (db, t, done) { + var ite = db.iterator() + ite.seek(Buffer.from('two')) + ite.next(function (err, key, value) { + t.error(err, 'no error from next()') + t.equal(key.toString(), 'two', 'key matches') + t.equal(value.toString(), '2', 'value matches') + ite.next(function (err, key, value) { + t.error(err, 'no error from next()') + t.equal(key, undefined, 'end of iterator') + t.equal(value, undefined, 'end of iterator') + ite.end(done) + }) + }) + }) + } + + make('iterator#seek() on reverse iterator', function (db, t, done) { + var ite = db.iterator({ reverse: true, limit: 1 }) + ite.seek('three!') + ite.next(function (err, key, value) { + t.error(err, 'no error') + t.same(key.toString(), 'three', 'key matches') + t.same(value.toString(), '3', 'value matches') + ite.end(done) + }) + }) + + make('iterator#seek() to out of range target', function (db, t, done) { + var ite = db.iterator() + ite.seek('zzz') + ite.next(function (err, key, value) { + t.error(err, 'no error') + t.same(key, undefined, 'end of iterator') + t.same(value, undefined, 'end of iterator') + ite.end(done) + }) + }) + + make('iterator#seek() on reverse iterator to out of range target', function (db, t, done) { + var ite = db.iterator({ reverse: true }) + ite.seek('zzz') + ite.next(function (err, key, value) { + t.error(err, 'no error') + t.same(key.toString(), 'two') + t.same(value.toString(), '2') + ite.end(done) + }) + }) + + test('iterator#seek() respects range', function (t) { + var db = testCommon.factory() + + db.open(function (err) { + t.error(err, 'no error from open()') + + // Can't use Array.fill() because IE + var ops = [] + + for (var i = 0; i < 10; i++) { + ops.push({ type: 'put', key: String(i), value: String(i) }) + } + + db.batch(ops, function (err) { + t.error(err, 'no error from batch()') + + var pending = 0 + + expect({ gt: '5' }, '4', undefined) + expect({ gt: '5' }, '5', undefined) + expect({ gt: '5' }, '6', '6') + + expect({ gte: '5' }, '4', undefined) + expect({ gte: '5' }, '5', '5') + expect({ gte: '5' }, '6', '6') + + expect({ start: '5' }, '4', undefined) + expect({ start: '5' }, '5', '5') + expect({ start: '5' }, '6', '6') + + expect({ lt: '5' }, '4', '4') + expect({ lt: '5' }, '5', undefined) + expect({ lt: '5' }, '6', undefined) + + expect({ lte: '5' }, '4', '4') + expect({ lte: '5' }, '5', '5') + expect({ lte: '5' }, '6', undefined) + + expect({ end: '5' }, '4', '4') + expect({ end: '5' }, '5', '5') + expect({ end: '5' }, '6', undefined) + + expect({ lt: '5', reverse: true }, '4', '4') + expect({ lt: '5', reverse: true }, '5', undefined) + expect({ lt: '5', reverse: true }, '6', undefined) + + expect({ lte: '5', reverse: true }, '4', '4') + expect({ lte: '5', reverse: true }, '5', '5') + expect({ lte: '5', reverse: true }, '6', undefined) + + expect({ start: '5', reverse: true }, '4', '4') + expect({ start: '5', reverse: true }, '5', '5') + expect({ start: '5', reverse: true }, '6', undefined) + + expect({ gt: '5', reverse: true }, '4', undefined) + expect({ gt: '5', reverse: true }, '5', undefined) + expect({ gt: '5', reverse: true }, '6', '6') + + expect({ gte: '5', reverse: true }, '4', undefined) + expect({ gte: '5', reverse: true }, '5', '5') + expect({ gte: '5', reverse: true }, '6', '6') + + expect({ end: '5', reverse: true }, '4', undefined) + expect({ end: '5', reverse: true }, '5', '5') + expect({ end: '5', reverse: true }, '6', '6') + + expect({ gt: '7', lt: '8' }, '7', undefined) + expect({ gte: '7', lt: '8' }, '7', '7') + expect({ gte: '7', lt: '8' }, '8', undefined) + expect({ gt: '7', lte: '8' }, '8', '8') + + function expect (range, target, expected) { + pending++ + var ite = db.iterator(range) + + ite.seek(target) + ite.next(function (err, key, value) { + t.error(err, 'no error from next()') + + var json = JSON.stringify(range) + var msg = 'seek(' + target + ') on ' + json + ' yields ' + expected + + if (expected === undefined) { + t.equal(value, undefined, msg) + } else { + t.equal(value.toString(), expected, msg) + } + + ite.end(function (err) { + t.error(err, 'no error from end()') + if (!--pending) done() + }) + }) + } + + function done () { + db.close(function (err) { + t.error(err, 'no error from close()') + t.end() + }) + } + }) + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/iterator-snapshot-test.js b/nodejs/node_modules/abstract-leveldown/test/iterator-snapshot-test.js new file mode 100644 index 00000000..7c022b02 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/iterator-snapshot-test.js @@ -0,0 +1,89 @@ +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) +} + +exports.snapshot = function (test, testCommon) { + function make (run) { + return function (t) { + var db = testCommon.factory() + + db.open(function (err) { + t.ifError(err, 'no open error') + + db.put('z', 'from snapshot', function (err) { + t.ifError(err, 'no put error') + + // For this test it is important that we don't read eagerly. + // NOTE: highWaterMark is not an abstract option atm, but + // it is supported by leveldown, rocksdb and others. + var it = db.iterator({ highWaterMark: 0 }) + + run(t, db, it, function end (err) { + t.ifError(err, 'no run error') + + it.end(function (err) { + t.ifError(err, 'no iterator end error') + db.close(t.end.bind(t)) + }) + }) + }) + }) + } + } + + test('delete key after snapshotting', make(function (t, db, it, end) { + db.del('z', function (err) { + t.ifError(err, 'no del error') + + it.next(function (err, key, value) { + t.ifError(err, 'no next error') + t.ok(key, 'got a key') + t.is(key.toString(), 'z', 'correct key') + t.is(value.toString(), 'from snapshot', 'correct value') + + end() + }) + }) + })) + + test('overwrite key after snapshotting', make(function (t, db, it, end) { + db.put('z', 'not from snapshot', function (err) { + t.ifError(err, 'no put error') + + it.next(function (err, key, value) { + t.ifError(err, 'no next error') + t.ok(key, 'got a key') + t.is(key.toString(), 'z', 'correct key') + t.is(value.toString(), 'from snapshot', 'correct value') + + end() + }) + }) + })) + + test('add key after snapshotting that sorts first', make(function (t, db, it, end) { + db.put('a', 'not from snapshot', function (err) { + t.ifError(err, 'no put error') + + it.next(function (err, key, value) { + t.ifError(err, 'no next error') + + t.ok(key, 'got a key') + t.is(key.toString(), 'z', 'correct key') + t.is(value.toString(), 'from snapshot', 'correct value') + + end() + }) + }) + })) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.snapshot(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/iterator-test.js b/nodejs/node_modules/abstract-leveldown/test/iterator-test.js new file mode 100644 index 00000000..8b82ff4f --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/iterator-test.js @@ -0,0 +1,172 @@ +var db + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test iterator has db reference', function (t) { + var iterator = db.iterator() + t.ok(iterator.db === db) + iterator.end(t.end.bind(t)) + }) + + test('test argument-less iterator#next() throws', function (t) { + var iterator = db.iterator() + t.throws( + iterator.next.bind(iterator), + /Error: next\(\) requires a callback argument/, + 'no-arg iterator#next() throws' + ) + iterator.end(t.end.bind(t)) + }) + + test('test argument-less iterator#end() after next() throws', function (t) { + var iterator = db.iterator() + iterator.next(function () { + t.throws( + iterator.end.bind(iterator), + /Error: end\(\) requires a callback argument/, + 'no-arg iterator#end() throws' + ) + iterator.end(t.end.bind(t)) + }) + }) + + test('test argument-less iterator#end() throws', function (t) { + var iterator = db.iterator() + t.throws( + iterator.end.bind(iterator), + /Error: end\(\) requires a callback argument/, + 'no-arg iterator#end() throws' + ) + iterator.end(t.end.bind(t)) + }) + + test('test iterator#next returns this', function (t) { + var iterator = db.iterator() + var self = iterator.next(function () {}) + t.ok(iterator === self) + iterator.end(t.end.bind(t)) + }) +} + +exports.sequence = function (test, testCommon) { + test('test twice iterator#end() callback with error', function (t) { + var iterator = db.iterator() + iterator.end(function (err) { + t.error(err) + + var async = false + + iterator.end(function (err2) { + t.ok(err2, 'returned error') + t.is(err2.name, 'Error', 'correct error') + t.is(err2.message, 'end() already called on iterator') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + }) + + test('test iterator#next after iterator#end() callback with error', function (t) { + var iterator = db.iterator() + iterator.end(function (err) { + t.error(err) + + var async = false + + iterator.next(function (err2) { + t.ok(err2, 'returned error') + t.is(err2.name, 'Error', 'correct error') + t.is(err2.message, 'cannot call next() after end()', 'correct message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + }) + + test('test twice iterator#next() throws', function (t) { + var iterator = db.iterator() + iterator.next(function (err) { + t.error(err) + iterator.end(function (err) { + t.error(err) + t.end() + }) + }) + + var async = false + + iterator.next(function (err) { + t.ok(err, 'returned error') + t.is(err.name, 'Error', 'correct error') + t.is(err.message, 'cannot call next() before previous next() has completed') + t.ok(async, 'callback is asynchronous') + }) + + async = true + }) +} + +exports.iterator = function (test, testCommon) { + test('test simple iterator()', function (t) { + var data = [ + { type: 'put', key: 'foobatch1', value: 'bar1' }, + { type: 'put', key: 'foobatch2', value: 'bar2' }, + { type: 'put', key: 'foobatch3', value: 'bar3' } + ] + var idx = 0 + + db.batch(data, function (err) { + t.error(err) + var iterator = db.iterator() + var fn = function (err, key, value) { + t.error(err) + if (key && value) { + t.ok(Buffer.isBuffer(key), 'key argument is a Buffer') + t.ok(Buffer.isBuffer(value), 'value argument is a Buffer') + t.is(key.toString(), data[idx].key, 'correct key') + t.is(value.toString(), data[idx].value, 'correct value') + process.nextTick(next) + idx++ + } else { // end + t.ok(typeof err === 'undefined', 'err argument is undefined') + t.ok(typeof key === 'undefined', 'key argument is undefined') + t.ok(typeof value === 'undefined', 'value argument is undefined') + t.is(idx, data.length, 'correct number of entries') + iterator.end(function () { + t.end() + }) + } + } + var next = function () { + iterator.next(fn) + } + + next() + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.sequence(test, testCommon) + exports.iterator(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/leveldown-test.js b/nodejs/node_modules/abstract-leveldown/test/leveldown-test.js new file mode 100644 index 00000000..a6407686 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/leveldown-test.js @@ -0,0 +1,12 @@ +module.exports = function (test, testCommon) { + test('setUp common', testCommon.setUp) + + test('test database open method exists', function (t) { + var db = testCommon.factory() + t.ok(db, 'database object returned') + t.ok(typeof db.open === 'function', 'open() function exists') + t.end() + }) + + test('tearDown', testCommon.tearDown) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/manifest-test.js b/nodejs/node_modules/abstract-leveldown/test/manifest-test.js new file mode 100644 index 00000000..104c8432 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/manifest-test.js @@ -0,0 +1,21 @@ +var suite = require('level-supports/test') + +module.exports = function (test, testCommon) { + test('setUp common', testCommon.setUp) + + suite(test, testCommon) + + test('manifest has status', function (t) { + var db = testCommon.factory() + t.is(db.supports.status, true) + + // The semantics of not opening or closing a new db are unclear + // atm, so let's open it before closing, like every other test. + db.open(function (err) { + t.ifError(err, 'no open error') + db.close(t.end.bind(t)) + }) + }) + + test('tearDown', testCommon.tearDown) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/open-create-if-missing-test.js b/nodejs/node_modules/abstract-leveldown/test/open-create-if-missing-test.js new file mode 100644 index 00000000..388281a3 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/open-create-if-missing-test.js @@ -0,0 +1,29 @@ +exports.setUp = function (test, testCommon) { + test('setUp', testCommon.setUp) +} + +exports.createIfMissing = function (test, testCommon) { + test('test database open createIfMissing:false', function (t) { + var db = testCommon.factory() + var async = false + + db.open({ createIfMissing: false }, function (err) { + t.ok(err, 'error') + t.ok(/does not exist/.test(err.message), 'error is about dir not existing') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.createIfMissing(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/open-error-if-exists-test.js b/nodejs/node_modules/abstract-leveldown/test/open-error-if-exists-test.js new file mode 100644 index 00000000..96d3cd11 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/open-error-if-exists-test.js @@ -0,0 +1,37 @@ +exports.setUp = function (test, testCommon) { + test('setUp', testCommon.setUp) +} + +exports.errorIfExists = function (test, testCommon) { + test('test database open errorIfExists:true', function (t) { + var db = testCommon.factory() + + db.open({}, function (err) { + t.error(err) + db.close(function (err) { + t.error(err) + + var async = false + + db.open({ createIfMissing: false, errorIfExists: true }, function (err) { + t.ok(err, 'error') + t.ok(/exists/.test(err.message), 'error is about already existing') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.errorIfExists(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/open-test.js b/nodejs/node_modules/abstract-leveldown/test/open-test.js new file mode 100644 index 00000000..9d7ef2bf --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/open-test.js @@ -0,0 +1,79 @@ +exports.setUp = function (test, testCommon) { + test('setUp', testCommon.setUp) +} + +exports.args = function (test, testCommon) { + test('test database open no-arg throws', function (t) { + var db = testCommon.factory() + t.throws( + db.open.bind(db), + /Error: open\(\) requires a callback argument/, + 'no-arg open() throws' + ) + t.end() + }) + + test('test callback-less, 1-arg, open() throws', function (t) { + var db = testCommon.factory() + t.throws( + db.open.bind(db, {}), + /Error: open\(\) requires a callback argument/, + 'callback-less, 1-arg open() throws' + ) + t.end() + }) +} + +exports.open = function (test, testCommon) { + test('test database open, no options', function (t) { + var db = testCommon.factory() + + // default createIfMissing=true, errorIfExists=false + db.open(function (err) { + t.error(err) + db.close(function () { + t.end() + }) + }) + }) + + test('test database open, options and callback', function (t) { + var db = testCommon.factory() + + // default createIfMissing=true, errorIfExists=false + db.open({}, function (err) { + t.error(err) + db.close(function () { + t.end() + }) + }) + }) + + test('test database open, close and open', function (t) { + var db = testCommon.factory() + + db.open(function (err) { + t.error(err) + db.close(function (err) { + t.error(err) + db.open(function (err) { + t.error(err) + db.close(function () { + t.end() + }) + }) + }) + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', testCommon.tearDown) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.open(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/put-get-del-test.js b/nodejs/node_modules/abstract-leveldown/test/put-get-del-test.js new file mode 100644 index 00000000..b8fc3ee7 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/put-get-del-test.js @@ -0,0 +1,176 @@ +'use strict' + +var db +var verifyNotFoundError = require('./util').verifyNotFoundError +var testBuffer = Buffer.from('testbuffer') + +function makeGetDelErrorTests (test, type, key, expectedError) { + test('test get() with ' + type + ' causes error', function (t) { + var async = false + + db.get(key, function (err) { + t.ok(err, 'has error') + t.ok(err instanceof Error) + t.ok(err.message.match(expectedError), 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + + test('test del() with ' + type + ' causes error', function (t) { + var async = false + + db.del(key, function (err) { + t.ok(err, 'has error') + t.ok(err instanceof Error) + t.ok(err.message.match(expectedError), 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) +} + +function makePutErrorTest (test, type, key, value, expectedError) { + test('test put() with ' + type + ' causes error', function (t) { + var async = false + + db.put(key, value, function (err) { + t.ok(err, 'has error') + t.ok(err instanceof Error) + t.ok(err.message.match(expectedError), 'correct error message') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) +} + +function makePutGetDelSuccessfulTest (test, type, key, value, expectedResult) { + var hasExpectedResult = arguments.length === 5 + test('test put()/get()/del() with ' + type, function (t) { + db.put(key, value, function (err) { + t.error(err) + db.get(key, function (err, _value) { + t.error(err, 'no error, has key/value for `' + type + '`') + t.ok(Buffer.isBuffer(_value), 'is a Buffer') + var result = _value + if (hasExpectedResult) { + t.equal(result.toString(), expectedResult) + } else { + if (result != null) { result = _value.toString() } + if (value != null) { value = value.toString() } + t.equals(result, value) + } + db.del(key, function (err) { + t.error(err, 'no error, deleted key/value for `' + type + '`') + + var async = false + + db.get(key, function (err, value) { + t.ok(err, 'entry properly deleted') + t.ok(verifyNotFoundError(err), 'should have correct error message') + t.equal(typeof value, 'undefined', 'value is undefined') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true + }) + }) + }) + }) +} + +function makeErrorKeyTest (test, type, key, expectedError) { + makeGetDelErrorTests(test, type, key, expectedError) + makePutErrorTest(test, type, key, 'foo', expectedError) +} + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.errorKeys = function (test, testCommon) { + makeErrorKeyTest(test, 'null key', null, /key cannot be `null` or `undefined`/) + makeErrorKeyTest(test, 'undefined key', undefined, /key cannot be `null` or `undefined`/) + makeErrorKeyTest(test, 'empty String key', '', /key cannot be an empty String/) + makeErrorKeyTest(test, 'empty Buffer key', Buffer.alloc(0), /key cannot be an empty \w*Buffer/) + makeErrorKeyTest(test, 'empty Array key', [], /key cannot be an empty Array/) +} + +exports.errorValues = function (test, testCommon) { + makePutErrorTest(test, 'null value', 'key', null, /value cannot be `null` or `undefined`/) + makePutErrorTest(test, 'undefined value', 'key', undefined, /value cannot be `null` or `undefined`/) +} + +exports.nonErrorKeys = function (test, testCommon) { + // valid falsey keys + makePutGetDelSuccessfulTest(test, '`0` key', 0, 'foo 0') + + // standard String key + makePutGetDelSuccessfulTest( + test + , 'long String key' + , 'some long string that I\'m using as a key for this unit test, cross your fingers human, we\'re going in!' + , 'foo' + ) + + if (testCommon.bufferKeys) { + makePutGetDelSuccessfulTest(test, 'Buffer key', testBuffer, 'foo') + } + + // non-empty Array as a value + makePutGetDelSuccessfulTest(test, 'Array value', 'foo', [1, 2, 3, 4]) +} + +exports.nonErrorValues = function (test, testCommon) { + // valid falsey values + makePutGetDelSuccessfulTest(test, '`false` value', 'foo false', false) + makePutGetDelSuccessfulTest(test, '`0` value', 'foo 0', 0) + makePutGetDelSuccessfulTest(test, '`NaN` value', 'foo NaN', NaN) + + // all of the following result in an empty-string value: + makePutGetDelSuccessfulTest(test, 'empty String value', 'foo', '', '') + makePutGetDelSuccessfulTest(test, 'empty Buffer value', 'foo', Buffer.alloc(0), '') + + // note that an implementation may return the value as an array + makePutGetDelSuccessfulTest(test, 'empty Array value', 'foo', [], '') + + // standard String value + makePutGetDelSuccessfulTest( + test + , 'long String value' + , 'foo' + , 'some long string that I\'m using as a key for this unit test, cross your fingers human, we\'re going in!' + ) + + // standard Buffer value + makePutGetDelSuccessfulTest(test, 'Buffer value', 'foo', testBuffer) + + // non-empty Array as a key + makePutGetDelSuccessfulTest(test, 'Array key', [1, 2, 3, 4], 'foo') +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.errorKeys(test, testCommon) + exports.errorValues(test, testCommon) + exports.nonErrorKeys(test, testCommon) + exports.nonErrorValues(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/put-test.js b/nodejs/node_modules/abstract-leveldown/test/put-test.js new file mode 100644 index 00000000..bc77206a --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/put-test.js @@ -0,0 +1,108 @@ +var db +var isTypedArray = require('./util').isTypedArray + +exports.setUp = function (test, testCommon) { + test('setUp common', testCommon.setUp) + test('setUp db', function (t) { + db = testCommon.factory() + db.open(t.end.bind(t)) + }) +} + +exports.args = function (test, testCommon) { + test('test argument-less put() throws', function (t) { + t.throws( + db.put.bind(db), + /Error: put\(\) requires a callback argument/, + 'no-arg put() throws' + ) + t.end() + }) + + test('test callback-less, 1-arg, put() throws', function (t) { + t.throws( + db.put.bind(db, 'foo'), + /Error: put\(\) requires a callback argument/, + 'callback-less, 1-arg put() throws' + ) + t.end() + }) + + test('test callback-less, 2-arg, put() throws', function (t) { + t.throws( + db.put.bind(db, 'foo', 'bar'), + /Error: put\(\) requires a callback argument/, + 'callback-less, 2-arg put() throws' + ) + t.end() + }) + + test('test callback-less, 3-arg, put() throws', function (t) { + t.throws( + db.put.bind(db, 'foo', 'bar', {}), + /Error: put\(\) requires a callback argument/, + 'callback-less, 3-arg put() throws' + ) + t.end() + }) + + test('test _serialize object', function (t) { + t.plan(3) + var db = testCommon.factory() + db._put = function (key, value, opts, callback) { + t.ok(key) + t.ok(value) + process.nextTick(callback) + } + db.put({}, {}, function (err, val) { + t.error(err) + }) + }) + + test('test custom _serialize*', function (t) { + t.plan(4) + var db = testCommon.factory() + db._serializeKey = db._serializeValue = function (data) { return data } + db._put = function (key, value, options, callback) { + t.deepEqual(key, { foo: 'bar' }) + t.deepEqual(value, { beep: 'boop' }) + process.nextTick(callback) + } + db.open(function () { + db.put({ foo: 'bar' }, { beep: 'boop' }, function (err) { + t.error(err) + db.close(t.error.bind(t)) + }) + }) + }) +} + +exports.put = function (test, testCommon) { + test('test simple put()', function (t) { + db.put('foo', 'bar', function (err) { + t.error(err) + db.get('foo', function (err, value) { + t.error(err) + var result = value.toString() + if (isTypedArray(value)) { + result = String.fromCharCode.apply(null, new Uint16Array(value)) + } + t.equal(result, 'bar') + t.end() + }) + }) + }) +} + +exports.tearDown = function (test, testCommon) { + test('tearDown', function (t) { + db.close(testCommon.tearDown.bind(null, t)) + }) +} + +exports.all = function (test, testCommon) { + exports.setUp(test, testCommon) + exports.args(test, testCommon) + exports.put(test, testCommon) + exports.tearDown(test, testCommon) +} diff --git a/nodejs/node_modules/abstract-leveldown/test/self.js b/nodejs/node_modules/abstract-leveldown/test/self.js new file mode 100644 index 00000000..8dfc6255 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/self.js @@ -0,0 +1,1017 @@ +'use strict' + +var test = require('tape') +var sinon = require('sinon') +var inherits = require('util').inherits +var AbstractLevelDOWN = require('../').AbstractLevelDOWN +var AbstractIterator = require('../').AbstractIterator +var AbstractChainedBatch = require('../').AbstractChainedBatch + +var testCommon = require('./common')({ + test: test, + clear: true, + factory: function () { + return new AbstractLevelDOWN() + } +}) + +var rangeOptions = ['gt', 'gte', 'lt', 'lte'] +var legacyRangeOptions = ['start', 'end'] + +// Test the suite itself as well as the default implementation, +// excluding noop operations that can't pass the test suite. + +require('./leveldown-test')(test, testCommon) +require('./manifest-test')(test, testCommon) +require('./open-test').all(test, testCommon) + +require('./open-create-if-missing-test').setUp(test, testCommon) +require('./open-create-if-missing-test').tearDown(test, testCommon) + +require('./open-error-if-exists-test').setUp(test, testCommon) +require('./open-error-if-exists-test').tearDown(test, testCommon) + +require('./del-test').setUp(test, testCommon) +require('./del-test').args(test, testCommon) + +require('./get-test').setUp(test, testCommon) +require('./get-test').args(test, testCommon) + +require('./put-test').setUp(test, testCommon) +require('./put-test').args(test, testCommon) + +require('./put-get-del-test').setUp(test, testCommon) +require('./put-get-del-test').errorKeys(test, testCommon) +require('./put-get-del-test').tearDown(test, testCommon) + +require('./batch-test').setUp(test, testCommon) +require('./batch-test').args(test, testCommon) + +require('./chained-batch-test').setUp(test, testCommon) +require('./chained-batch-test').args(test, testCommon) +require('./chained-batch-test').tearDown(test, testCommon) + +require('./close-test').all(test, testCommon) + +require('./iterator-test').setUp(test, testCommon) +require('./iterator-test').args(test, testCommon) +require('./iterator-test').sequence(test, testCommon) +require('./iterator-test').tearDown(test, testCommon) + +require('./iterator-range-test').setUp(test, testCommon) +require('./iterator-range-test').tearDown(test, testCommon) + +require('./iterator-snapshot-test').setUp(test, testCommon) +require('./iterator-snapshot-test').tearDown(test, testCommon) + +require('./iterator-no-snapshot-test').setUp(test, testCommon) +require('./iterator-no-snapshot-test').tearDown(test, testCommon) + +require('./iterator-seek-test').setUp(test, testCommon) +require('./iterator-seek-test').sequence(test, testCommon) +require('./iterator-seek-test').tearDown(test, testCommon) + +require('./clear-test').setUp(test, testCommon) +require('./clear-test').args(test, testCommon) +require('./clear-test').tearDown(test, testCommon) + +require('./clear-range-test').setUp(test, testCommon) +require('./clear-range-test').tearDown(test, testCommon) + +function implement (ctor, methods) { + function Test () { + ctor.apply(this, arguments) + } + + inherits(Test, ctor) + + for (var k in methods) { + Test.prototype[k] = methods[k] + } + + return Test +} + +/** + * Extensibility + */ + +test('test core extensibility', function (t) { + var Test = implement(AbstractLevelDOWN) + var test = new Test() + t.equal(test.status, 'new', 'status is new') + t.end() +}) + +test('test key/value serialization', function (t) { + var Test = implement(AbstractLevelDOWN) + var test = new Test() + + ;['', {}, null, undefined, Buffer.alloc(0)].forEach(function (v) { + t.ok(test._serializeKey(v) === v, '_serializeKey is an identity function') + t.ok(test._serializeValue(v) === v, '_serializeValue is an identity function') + }) + + t.end() +}) + +test('test open() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var expectedOptions = { createIfMissing: true, errorIfExists: false } + var Test = implement(AbstractLevelDOWN, { _open: spy }) + var test = new Test('foobar') + + test.open(expectedCb) + + t.equal(spy.callCount, 1, 'got _open() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _open() was correct') + t.equal(spy.getCall(0).args.length, 2, 'got two arguments') + t.deepEqual(spy.getCall(0).args[0], expectedOptions, 'got default options argument') + + test.open({ options: 1 }, expectedCb) + + expectedOptions.options = 1 + + t.equal(spy.callCount, 2, 'got _open() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _open() was correct') + t.equal(spy.getCall(1).args.length, 2, 'got two arguments') + t.deepEqual(spy.getCall(1).args[0], expectedOptions, 'got expected options argument') + t.end() +}) + +test('test close() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var Test = implement(AbstractLevelDOWN, { _close: spy }) + var test = new Test('foobar') + + test.close(expectedCb) + + t.equal(spy.callCount, 1, 'got _close() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _close() was correct') + t.equal(spy.getCall(0).args.length, 1, 'got one arguments') + t.end() +}) + +test('test get() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var expectedOptions = { asBuffer: true } + var expectedKey = 'a key' + var Test = implement(AbstractLevelDOWN, { _get: spy }) + var test = new Test('foobar') + + test.get(expectedKey, expectedCb) + + t.equal(spy.callCount, 1, 'got _get() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _get() was correct') + t.equal(spy.getCall(0).args.length, 3, 'got three arguments') + t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument') + t.deepEqual(spy.getCall(0).args[1], expectedOptions, 'got default options argument') + t.equal(spy.getCall(0).args[2], expectedCb, 'got expected cb argument') + + test.get(expectedKey, { options: 1 }, expectedCb) + + expectedOptions.options = 1 + + t.equal(spy.callCount, 2, 'got _get() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _get() was correct') + t.equal(spy.getCall(1).args.length, 3, 'got three arguments') + t.equal(spy.getCall(1).args[0], expectedKey, 'got expected key argument') + t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument') + t.equal(spy.getCall(1).args[2], expectedCb, 'got expected cb argument') + t.end() +}) + +test('test del() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var expectedOptions = { options: 1 } + var expectedKey = 'a key' + var Test = implement(AbstractLevelDOWN, { _del: spy }) + var test = new Test('foobar') + + test.del(expectedKey, expectedCb) + + t.equal(spy.callCount, 1, 'got _del() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _del() was correct') + t.equal(spy.getCall(0).args.length, 3, 'got three arguments') + t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument') + t.deepEqual(spy.getCall(0).args[1], {}, 'got blank options argument') + t.equal(spy.getCall(0).args[2], expectedCb, 'got expected cb argument') + + test.del(expectedKey, expectedOptions, expectedCb) + + t.equal(spy.callCount, 2, 'got _del() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _del() was correct') + t.equal(spy.getCall(1).args.length, 3, 'got three arguments') + t.equal(spy.getCall(1).args[0], expectedKey, 'got expected key argument') + t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument') + t.equal(spy.getCall(1).args[2], expectedCb, 'got expected cb argument') + t.end() +}) + +test('test put() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var expectedOptions = { options: 1 } + var expectedKey = 'a key' + var expectedValue = 'a value' + var Test = implement(AbstractLevelDOWN, { _put: spy }) + var test = new Test('foobar') + + test.put(expectedKey, expectedValue, expectedCb) + + t.equal(spy.callCount, 1, 'got _put() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _put() was correct') + t.equal(spy.getCall(0).args.length, 4, 'got four arguments') + t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument') + t.equal(spy.getCall(0).args[1], expectedValue, 'got expected value argument') + t.deepEqual(spy.getCall(0).args[2], {}, 'got blank options argument') + t.equal(spy.getCall(0).args[3], expectedCb, 'got expected cb argument') + + test.put(expectedKey, expectedValue, expectedOptions, expectedCb) + + t.equal(spy.callCount, 2, 'got _put() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _put() was correct') + t.equal(spy.getCall(1).args.length, 4, 'got four arguments') + t.equal(spy.getCall(1).args[0], expectedKey, 'got expected key argument') + t.equal(spy.getCall(1).args[1], expectedValue, 'got expected value argument') + t.deepEqual(spy.getCall(1).args[2], expectedOptions, 'got blank options argument') + t.equal(spy.getCall(1).args[3], expectedCb, 'got expected cb argument') + t.end() +}) + +test('test batch([]) (array-form) extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var expectedOptions = { options: 1 } + var expectedArray = [ + { type: 'put', key: '1', value: '1' }, + { type: 'del', key: '2' } + ] + var Test = implement(AbstractLevelDOWN, { _batch: spy }) + var test = new Test('foobar') + + test.batch(expectedArray, expectedCb) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _batch() was correct') + t.equal(spy.getCall(0).args.length, 3, 'got three arguments') + t.deepEqual(spy.getCall(0).args[0], expectedArray, 'got expected array argument') + t.deepEqual(spy.getCall(0).args[1], {}, 'got expected options argument') + t.equal(spy.getCall(0).args[2], expectedCb, 'got expected callback argument') + + test.batch(expectedArray, expectedOptions, expectedCb) + + t.equal(spy.callCount, 2, 'got _batch() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _batch() was correct') + t.equal(spy.getCall(1).args.length, 3, 'got three arguments') + t.deepEqual(spy.getCall(1).args[0], expectedArray, 'got expected array argument') + t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument') + t.equal(spy.getCall(1).args[2], expectedCb, 'got expected callback argument') + + test.batch(expectedArray, null, expectedCb) + + t.equal(spy.callCount, 3, 'got _batch() call') + t.equal(spy.getCall(2).thisValue, test, '`this` on _batch() was correct') + t.equal(spy.getCall(2).args.length, 3, 'got three arguments') + t.deepEqual(spy.getCall(2).args[0], expectedArray, 'got expected array argument') + t.ok(spy.getCall(2).args[1], 'options should not be null') + t.equal(spy.getCall(2).args[2], expectedCb, 'got expected callback argument') + t.end() +}) + +test('test batch([]) (array-form) with empty array is asynchronous', function (t) { + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { _batch: spy }) + var test = new Test() + var async = false + + test.batch([], function (err) { + t.ifError(err, 'no error') + t.ok(async, 'callback is asynchronous') + + // Assert that asynchronicity is provided by batch() rather than _batch() + t.is(spy.callCount, 0, '_batch() call was bypassed') + t.end() + }) + + async = true +}) + +test('test chained batch() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var expectedOptions = { options: 1 } + var Test = implement(AbstractLevelDOWN, { _batch: spy }) + var test = new Test('foobar') + + test.batch().put('foo', 'bar').del('bang').write(expectedCb) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _batch() was correct') + t.equal(spy.getCall(0).args.length, 3, 'got three arguments') + t.equal(spy.getCall(0).args[0].length, 2, 'got expected array argument') + t.deepEqual(spy.getCall(0).args[0][0], { type: 'put', key: 'foo', value: 'bar' }, 'got expected array argument[0]') + t.deepEqual(spy.getCall(0).args[0][1], { type: 'del', key: 'bang' }, 'got expected array argument[1]') + t.deepEqual(spy.getCall(0).args[1], {}, 'got expected options argument') + t.equal(spy.getCall(0).args[2], expectedCb, 'got expected callback argument') + + test.batch().put('foo', 'bar').del('bang').write(expectedOptions, expectedCb) + + t.equal(spy.callCount, 2, 'got _batch() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _batch() was correct') + t.equal(spy.getCall(1).args.length, 3, 'got three arguments') + t.equal(spy.getCall(1).args[0].length, 2, 'got expected array argument') + t.deepEqual(spy.getCall(1).args[0][0], { type: 'put', key: 'foo', value: 'bar' }, 'got expected array argument[0]') + t.deepEqual(spy.getCall(1).args[0][1], { type: 'del', key: 'bang' }, 'got expected array argument[1]') + t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument') + t.equal(spy.getCall(1).args[2], expectedCb, 'got expected callback argument') + + t.end() +}) + +test('test chained batch() with no operations is asynchronous', function (t) { + var Test = implement(AbstractLevelDOWN, {}) + var test = new Test() + var async = false + + test.batch().write(function (err) { + t.ifError(err, 'no error') + t.ok(async, 'callback is asynchronous') + t.end() + }) + + async = true +}) + +test('test chained batch() (custom _chainedBatch) extensibility', function (t) { + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { _chainedBatch: spy }) + var test = new Test('foobar') + + test.batch() + + t.equal(spy.callCount, 1, 'got _chainedBatch() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _chainedBatch() was correct') + + test.batch() + + t.equal(spy.callCount, 2, 'got _chainedBatch() call') + t.equal(spy.getCall(1).thisValue, test, '`this` on _chainedBatch() was correct') + + t.end() +}) + +test('test AbstractChainedBatch extensibility', function (t) { + var Test = implement(AbstractChainedBatch) + var db = {} + var test = new Test(db) + t.ok(test.db === db, 'instance has db reference') + t.end() +}) + +test('test AbstractChainedBatch expects a db', function (t) { + t.plan(1) + + var Test = implement(AbstractChainedBatch) + + try { + Test() + } catch (err) { + t.is(err.message, 'First argument must be an abstract-leveldown compliant store') + } +}) + +test('test AbstractChainedBatch#write() extensibility', function (t) { + var spy = sinon.spy() + var spycb = sinon.spy() + var Test = implement(AbstractChainedBatch, { _write: spy }) + var test = new Test({ test: true }) + + test.write(spycb) + + t.equal(spy.callCount, 1, 'got _write() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _write() was correct') + t.equal(spy.getCall(0).args.length, 2, 'got two arguments') + t.same(spy.getCall(0).args[0], {}, 'got options') + // awkward here cause of nextTick & an internal wrapped cb + t.equal(typeof spy.getCall(0).args[1], 'function', 'got a callback function') + t.equal(spycb.callCount, 0, 'spycb not called') + spy.getCall(0).args[1]() + t.equal(spycb.callCount, 1, 'spycb called, i.e. was our cb argument') + t.end() +}) + +test('test AbstractChainedBatch#write() extensibility with null options', function (t) { + var spy = sinon.spy() + var Test = implement(AbstractChainedBatch, { _write: spy }) + var test = new Test({ test: true }) + + test.write(null, function () {}) + + t.equal(spy.callCount, 1, 'got _write() call') + t.same(spy.getCall(0).args[0], {}, 'got options') + t.end() +}) + +test('test AbstractChainedBatch#write() extensibility with options', function (t) { + var spy = sinon.spy() + var Test = implement(AbstractChainedBatch, { _write: spy }) + var test = new Test({ test: true }) + + test.write({ test: true }, function () {}) + + t.equal(spy.callCount, 1, 'got _write() call') + t.same(spy.getCall(0).args[0], { test: true }, 'got options') + t.end() +}) + +test('test AbstractChainedBatch#put() extensibility', function (t) { + var spy = sinon.spy() + var expectedKey = 'key' + var expectedValue = 'value' + var Test = implement(AbstractChainedBatch, { _put: spy }) + var test = new Test(testCommon.factory()) + var returnValue = test.put(expectedKey, expectedValue) + + t.equal(spy.callCount, 1, 'got _put call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _put() was correct') + t.equal(spy.getCall(0).args.length, 2, 'got two arguments') + t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument') + t.equal(spy.getCall(0).args[1], expectedValue, 'got expected value argument') + t.equal(returnValue, test, 'get expected return value') + t.end() +}) + +test('test AbstractChainedBatch#del() extensibility', function (t) { + var spy = sinon.spy() + var expectedKey = 'key' + var Test = implement(AbstractChainedBatch, { _del: spy }) + var test = new Test(testCommon.factory()) + var returnValue = test.del(expectedKey) + + t.equal(spy.callCount, 1, 'got _del call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _del() was correct') + t.equal(spy.getCall(0).args.length, 1, 'got one argument') + t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument') + t.equal(returnValue, test, 'get expected return value') + t.end() +}) + +test('test AbstractChainedBatch#clear() extensibility', function (t) { + var spy = sinon.spy() + var Test = implement(AbstractChainedBatch, { _clear: spy }) + var test = new Test(testCommon.factory()) + var returnValue = test.clear() + + t.equal(spy.callCount, 1, 'got _clear call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _clear() was correct') + t.equal(spy.getCall(0).args.length, 0, 'got zero arguments') + t.equal(returnValue, test, 'get expected return value') + t.end() +}) + +test('test iterator() extensibility', function (t) { + var spy = sinon.spy() + var expectedOptions = { + options: 1, + reverse: false, + keys: true, + values: true, + limit: -1, + keyAsBuffer: true, + valueAsBuffer: true + } + var Test = implement(AbstractLevelDOWN, { _iterator: spy }) + var test = new Test('foobar') + + test.iterator({ options: 1 }) + + t.equal(spy.callCount, 1, 'got _iterator() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _iterator() was correct') + t.equal(spy.getCall(0).args.length, 1, 'got one arguments') + t.deepEqual(spy.getCall(0).args[0], expectedOptions, 'got expected options argument') + t.end() +}) + +test('test AbstractIterator extensibility', function (t) { + var Test = implement(AbstractIterator) + var db = {} + var test = new Test(db) + t.ok(test.db === db, 'instance has db reference') + t.end() +}) + +test('test AbstractIterator#next() extensibility', function (t) { + var spy = sinon.spy() + var spycb = sinon.spy() + var Test = implement(AbstractIterator, { _next: spy }) + var test = new Test({}) + + test.next(spycb) + + t.equal(spy.callCount, 1, 'got _next() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _next() was correct') + t.equal(spy.getCall(0).args.length, 1, 'got one arguments') + // awkward here cause of nextTick & an internal wrapped cb + t.equal(typeof spy.getCall(0).args[0], 'function', 'got a callback function') + t.equal(spycb.callCount, 0, 'spycb not called') + spy.getCall(0).args[0]() + t.equal(spycb.callCount, 1, 'spycb called, i.e. was our cb argument') + t.end() +}) + +test('test AbstractIterator#end() extensibility', function (t) { + var spy = sinon.spy() + var expectedCb = function () {} + var Test = implement(AbstractIterator, { _end: spy }) + var test = new Test({}) + + test.end(expectedCb) + + t.equal(spy.callCount, 1, 'got _end() call') + t.equal(spy.getCall(0).thisValue, test, '`this` on _end() was correct') + t.equal(spy.getCall(0).args.length, 1, 'got one arguments') + t.equal(spy.getCall(0).args[0], expectedCb, 'got expected cb argument') + t.end() +}) + +test('test clear() extensibility', function (t) { + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { _clear: spy }) + var db = new Test() + var callback = function () {} + + call([callback], { reverse: false, limit: -1 }) + call([null, callback], { reverse: false, limit: -1 }) + call([undefined, callback], { reverse: false, limit: -1 }) + call([{ custom: 1 }, callback], { custom: 1, reverse: false, limit: -1 }) + call([{ reverse: true, limit: 0 }, callback], { reverse: true, limit: 0 }) + call([{ reverse: 1 }, callback], { reverse: true, limit: -1 }) + call([{ reverse: null }, callback], { reverse: false, limit: -1 }) + + function call (args, expectedOptions) { + db.clear.apply(db, args) + + t.is(spy.callCount, 1, 'got _clear() call') + t.is(spy.getCall(0).thisValue, db, '`this` on _clear() was correct') + t.is(spy.getCall(0).args.length, 2, 'got two arguments') + t.same(spy.getCall(0).args[0], expectedOptions, 'got expected options argument') + t.is(spy.getCall(0).args[1], callback, 'got expected callback argument') + + spy.resetHistory() + } + + t.end() +}) + +test('test serialization extensibility (put)', function (t) { + t.plan(5) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _put: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + + _serializeValue: function (value) { + t.equal(value, 'nope') + return 'bar' + } + }) + + var test = new Test('foobar') + test.put('no', 'nope', function () {}) + + t.equal(spy.callCount, 1, 'got _put() call') + t.equal(spy.getCall(0).args[0], 'foo', 'got expected key argument') + t.equal(spy.getCall(0).args[1], 'bar', 'got expected value argument') +}) + +test('test serialization extensibility (del)', function (t) { + t.plan(3) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _del: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + _serializeValue: function (value) { + t.fail('should not be called') + } + }) + + var test = new Test('foobar') + test.del('no', function () {}) + + t.equal(spy.callCount, 1, 'got _del() call') + t.equal(spy.getCall(0).args[0], 'foo', 'got expected key argument') + + t.end() +}) + +test('test serialization extensibility (batch array put)', function (t) { + t.plan(5) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _batch: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + _serializeValue: function (value) { + t.equal(value, 'nope') + return 'bar' + } + }) + + var test = new Test('foobar') + test.batch([{ type: 'put', key: 'no', value: 'nope' }], function () {}) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key') + t.equal(spy.getCall(0).args[0][0].value, 'bar', 'got expected value') +}) + +test('test serialization extensibility (batch chain put)', function (t) { + t.plan(5) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _batch: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + _serializeValue: function (value) { + t.equal(value, 'nope') + return 'bar' + } + }) + + var test = new Test('foobar') + test.batch().put('no', 'nope').write(function () {}) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key') + t.equal(spy.getCall(0).args[0][0].value, 'bar', 'got expected value') +}) + +test('test serialization extensibility (batch array del)', function (t) { + t.plan(3) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _batch: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + _serializeValue: function (value) { + t.fail('should not be called') + } + }) + + var test = new Test('foobar') + test.batch([{ type: 'del', key: 'no' }], function () {}) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key') +}) + +test('test serialization extensibility (batch chain del)', function (t) { + t.plan(3) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _batch: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + _serializeValue: function (value) { + t.fail('should not be called') + } + }) + + var test = new Test('foobar') + test.batch().del('no').write(function () {}) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key') +}) + +test('test serialization extensibility (batch array is not mutated)', function (t) { + t.plan(7) + + var spy = sinon.spy() + var Test = implement(AbstractLevelDOWN, { + _batch: spy, + _serializeKey: function (key) { + t.equal(key, 'no') + return 'foo' + }, + _serializeValue: function (value) { + t.equal(value, 'nope') + return 'bar' + } + }) + + var test = new Test('foobar') + var op = { type: 'put', key: 'no', value: 'nope' } + + test.batch([op], function () {}) + + t.equal(spy.callCount, 1, 'got _batch() call') + t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key') + t.equal(spy.getCall(0).args[0][0].value, 'bar', 'got expected value') + + t.equal(op.key, 'no', 'did not mutate input key') + t.equal(op.value, 'nope', 'did not mutate input value') +}) + +test('test serialization extensibility (iterator range options)', function (t) { + t.plan(2) + + function Test () { + AbstractLevelDOWN.call(this) + } + + inherits(Test, AbstractLevelDOWN) + + Test.prototype._serializeKey = function (key) { + t.is(key, 'input') + return 'output' + } + + Test.prototype._iterator = function (options) { + return new Iterator(this, options) + } + + function Iterator (db, options) { + AbstractIterator.call(this, db) + t.is(options.gt, 'output') + } + + inherits(Iterator, AbstractIterator) + + var test = new Test() + test.iterator({ gt: 'input' }) +}) + +test('test serialization extensibility (iterator seek)', function (t) { + t.plan(3) + + var spy = sinon.spy() + var TestIterator = implement(AbstractIterator, { _seek: spy }) + + var Test = implement(AbstractLevelDOWN, { + _iterator: function () { + return new TestIterator(this) + }, + _serializeKey: function (key) { + t.equal(key, 'target') + return 'serialized' + } + }) + + var test = new Test('foobar') + var it = test.iterator() + + it.seek('target') + + t.equal(spy.callCount, 1, 'got _seek() call') + t.equal(spy.getCall(0).args[0], 'serialized', 'got expected target argument') +}) + +test('test serialization extensibility (clear range options)', function (t) { + t.plan(rangeOptions.length * 2) + + rangeOptions.forEach(function (key) { + var Test = implement(AbstractLevelDOWN, { + _serializeKey: function (key) { + t.is(key, 'input') + return 'output' + }, + _clear: function (options, callback) { + t.is(options[key], 'output') + } + }) + + var db = new Test() + var options = {} + + options[key] = 'input' + db.clear(options, function () {}) + }) +}) + +test('clear() does not delete empty or nullish range options', function (t) { + var rangeValues = [Buffer.alloc(0), '', null, undefined] + + t.plan(rangeOptions.length * rangeValues.length) + + rangeValues.forEach(function (value) { + var Test = implement(AbstractLevelDOWN, { + _clear: function (options, callback) { + rangeOptions.forEach(function (key) { + t.ok(key in options, key + ' option should not be deleted') + }) + } + }) + + var db = new Test() + var options = {} + + rangeOptions.forEach(function (key) { + options[key] = value + }) + + db.clear(options, function () {}) + }) +}) + +test('.status', function (t) { + t.plan(5) + + t.test('empty prototype', function (t) { + var Test = implement(AbstractLevelDOWN) + var test = new Test('foobar') + + t.equal(test.status, 'new') + + test.open(function (err) { + t.error(err) + t.equal(test.status, 'open') + + test.close(function (err) { + t.error(err) + t.equal(test.status, 'closed') + t.end() + }) + }) + }) + + t.test('open error', function (t) { + var Test = implement(AbstractLevelDOWN, { + _open: function (options, cb) { + cb(new Error()) + } + }) + + var test = new Test('foobar') + + test.open(function (err) { + t.ok(err) + t.equal(test.status, 'new') + t.end() + }) + }) + + t.test('close error', function (t) { + var Test = implement(AbstractLevelDOWN, { + _close: function (cb) { + cb(new Error()) + } + }) + + var test = new Test('foobar') + test.open(function () { + test.close(function (err) { + t.ok(err) + t.equal(test.status, 'open') + t.end() + }) + }) + }) + + t.test('open', function (t) { + var Test = implement(AbstractLevelDOWN, { + _open: function (options, cb) { + process.nextTick(cb) + } + }) + + var test = new Test('foobar') + test.open(function (err) { + t.error(err) + t.equal(test.status, 'open') + t.end() + }) + t.equal(test.status, 'opening') + }) + + t.test('close', function (t) { + var Test = implement(AbstractLevelDOWN, { + _close: function (cb) { + process.nextTick(cb) + } + }) + + var test = new Test('foobar') + test.open(function (err) { + t.error(err) + test.close(function (err) { + t.error(err) + t.equal(test.status, 'closed') + t.end() + }) + t.equal(test.status, 'closing') + }) + }) +}) + +test('_setupIteratorOptions', function (t) { + var keys = legacyRangeOptions.concat(rangeOptions) + var db = new AbstractLevelDOWN() + + function setupOptions (constrFn) { + var options = {} + keys.forEach(function (key) { + options[key] = constrFn() + }) + return options + } + + function verifyOptions (t, options) { + keys.forEach(function (key) { + t.ok(key in options, key + ' option should not be deleted') + }) + t.end() + } + + t.plan(6) + + t.test('default options', function (t) { + t.same(db._setupIteratorOptions(), { + reverse: false, + keys: true, + values: true, + limit: -1, + keyAsBuffer: true, + valueAsBuffer: true + }, 'correct defaults') + t.end() + }) + + t.test('set options', function (t) { + t.same(db._setupIteratorOptions({ + reverse: false, + keys: false, + values: false, + limit: 20, + keyAsBuffer: false, + valueAsBuffer: false + }), { + reverse: false, + keys: false, + values: false, + limit: 20, + keyAsBuffer: false, + valueAsBuffer: false + }, 'options set correctly') + t.end() + }) + + t.test('does not delete empty buffers', function (t) { + var options = setupOptions(function () { return Buffer.from('') }) + keys.forEach(function (key) { + t.is(Buffer.isBuffer(options[key]), true, 'should be buffer') + t.is(options[key].length, 0, 'should be empty') + }) + verifyOptions(t, db._setupIteratorOptions(options)) + }) + + t.test('does not delete empty strings', function (t) { + var options = setupOptions(function () { return '' }) + keys.forEach(function (key) { + t.is(typeof options[key], 'string', 'should be string') + t.is(options[key].length, 0, 'should be empty') + }) + verifyOptions(t, db._setupIteratorOptions(options)) + }) + + t.test('does not delete null', function (t) { + var options = setupOptions(function () { return null }) + keys.forEach(function (key) { + t.is(options[key], null, 'should be null') + }) + verifyOptions(t, db._setupIteratorOptions(options)) + }) + + t.test('does not delete undefined', function (t) { + var options = setupOptions(function () { return undefined }) + keys.forEach(function (key) { + t.is(options[key], undefined, 'should be undefined') + }) + verifyOptions(t, db._setupIteratorOptions(options)) + }) +}) diff --git a/nodejs/node_modules/abstract-leveldown/test/util.js b/nodejs/node_modules/abstract-leveldown/test/util.js new file mode 100644 index 00000000..db656260 --- /dev/null +++ b/nodejs/node_modules/abstract-leveldown/test/util.js @@ -0,0 +1,10 @@ +var nfre = /NotFound/i + +exports.verifyNotFoundError = function verifyNotFoundError (err) { + return nfre.test(err.message) || nfre.test(err.name) +} + +exports.isTypedArray = function isTypedArray (value) { + return (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) || + (typeof Uint8Array !== 'undefined' && value instanceof Uint8Array) +} diff --git a/nodejs/node_modules/async-limiter/.eslintignore b/nodejs/node_modules/async-limiter/.eslintignore new file mode 100644 index 00000000..e1661e5a --- /dev/null +++ b/nodejs/node_modules/async-limiter/.eslintignore @@ -0,0 +1,2 @@ +coverage +.nyc_output \ No newline at end of file diff --git a/nodejs/node_modules/async-limiter/.nycrc b/nodejs/node_modules/async-limiter/.nycrc new file mode 100644 index 00000000..874c1dee --- /dev/null +++ b/nodejs/node_modules/async-limiter/.nycrc @@ -0,0 +1,10 @@ +{ + "check-coverage": false, + "lines": 99, + "statements": 99, + "functions": 99, + "branches": 99, + "include": [ + "index.js" + ] +} \ No newline at end of file diff --git a/nodejs/node_modules/async-limiter/.travis.yml b/nodejs/node_modules/async-limiter/.travis.yml new file mode 100644 index 00000000..37026e20 --- /dev/null +++ b/nodejs/node_modules/async-limiter/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "6" + - "8" + - "10" + - "node" +script: npm run travis +cache: + yarn: true diff --git a/nodejs/node_modules/async-limiter/LICENSE b/nodejs/node_modules/async-limiter/LICENSE new file mode 100644 index 00000000..9c91fb26 --- /dev/null +++ b/nodejs/node_modules/async-limiter/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Samuel Reed + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/async-limiter/index.js b/nodejs/node_modules/async-limiter/index.js new file mode 100644 index 00000000..c9bd2f97 --- /dev/null +++ b/nodejs/node_modules/async-limiter/index.js @@ -0,0 +1,67 @@ +'use strict'; + +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); + } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); +} + +var arrayAddMethods = [ + 'push', + 'unshift', + 'splice' +]; + +arrayAddMethods.forEach(function(method) { + Queue.prototype[method] = function() { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + this._run(); + return methodResult; + }; +}); + +Object.defineProperty(Queue.prototype, 'length', { + get: function() { + return this.pending + this.jobs.length; + } +}); + +Queue.prototype._run = function() { + if (this.pending === this.concurrency) { + return; + } + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); + this._run(); + } + + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; + +Queue.prototype.onDone = function(cb) { + if (typeof cb === 'function') { + this.cbs.push(cb); + this._run(); + } +}; + +function done() { + this.pending--; + this._run(); +} + +module.exports = Queue; diff --git a/nodejs/node_modules/async-limiter/package.json b/nodejs/node_modules/async-limiter/package.json new file mode 100644 index 00000000..50742cba --- /dev/null +++ b/nodejs/node_modules/async-limiter/package.json @@ -0,0 +1,35 @@ +{ + "name": "async-limiter", + "version": "1.0.1", + "description": "asynchronous function queue with adjustable concurrency", + "keywords": [ + "throttle", + "async", + "limiter", + "asynchronous", + "job", + "task", + "concurrency", + "concurrent" + ], + "dependencies": {}, + "devDependencies": { + "coveralls": "^3.0.3", + "eslint": "^5.16.0", + "eslint-plugin-mocha": "^5.3.0", + "intelli-espower-loader": "^1.0.1", + "mocha": "^6.1.4", + "nyc": "^14.1.1", + "power-assert": "^1.6.1" + }, + "scripts": { + "test": "mocha --require intelli-espower-loader test/", + "travis": "npm run lint && npm run test", + "coverage": "nyc npm test && nyc report --reporter=text-lcov | coveralls", + "example": "node example", + "lint": "eslint ." + }, + "repository": "https://github.com/strml/async-limiter.git", + "author": "Samuel Reed { + const resp = await fetch(url) + return resp.body +}) +``` + +## Breaking Changes +- Most Async methods return a Promise when the final callback is omitted, making them `await`-able! (#1572) +- We are now making heavy use of ES2015 features, this means we have dropped out-of-the-box support for Node 4 and earlier, and many old versions of browsers. (#1541, #1553) +- In `queue`, `priorityQueue`, `cargo` and `cargoQueue`, the "event"-style methods, like `q.drain` and `q.saturated` are now methods that register a callback, rather than properties you assign a callback to. They are now of the form `q.drain(callback)`. If you do not pass a callback a Promise will be returned for the next occurrence of the event, making them `await`-able, e.g. `await q.drain()`. (#1586, #1641) +- Calling `callback(false)` will cancel an async method, preventing further iteration and callback calls. This is useful for preventing memory leaks when you break out of an async flow by calling an outer callback. (#1064, #1542) +- `during` and `doDuring` have been removed, and instead `whilst`, `doWhilst`, `until` and `doUntil` now have asynchronous `test` functions. (#850, #1557) +- `limits` of less than 1 now cause an error to be thrown in queues and collection methods. (#1249, #1552) +- `memoize` no longer memoizes errors (#1465, #1466) +- `applyEach`/`applyEachSeries` have a simpler interface, to make them more easily type-able. It always returns a function that takes in a single callback argument. If that callback is omitted, a promise is returned, making it awaitable. (#1228, #1640) + +## New Features +- Async generators are now supported in all the Collection methods. (#1560) +- Added `cargoQueue`, a queue with both `concurrency` and `payload` size parameters. (#1567) +- Queue objects returned from `queue` now have a `Symbol.iterator` method, meaning they can be iterated over to inspect the current list of items in the queue. (#1459, #1556) +- A ESM-flavored `async.mjs` is included in the `async` package. This is described in the `package.json` `"module"` field, meaning it should be automatically used by Webpack and other compatible bundlers. + +## Bug fixes +- Better handle arbitrary error objects in `asyncify` (#1568, #1569) + +## Other +- Removed Lodash as a dependency (#1283, #1528) +- Miscellaneous docs fixes (#1393, #1501, #1540, #1543, #1558, #1563, #1564, #1579, #1581) +- Miscellaneous test fixes (#1538) + +------- + +# v2.6.1 +- Updated lodash to prevent `npm audit` warnings. (#1532, #1533) +- Made `async-es` more optimized for webpack users (#1517) +- Fixed a stack overflow with large collections and a synchronous iterator (#1514) +- Various small fixes/chores (#1505, #1511, #1527, #1530) + +# v2.6.0 +- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) +- Improved `queue` performance. (#1448, #1454) +- Add missing sourcemap (#1452, #1453) +- Various doc updates (#1448, #1471, #1483) + +# v2.5.0 +- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) +- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) +- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) +- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) + +# v2.4.1 +- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) + +# v2.4.0 +- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) +- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) +- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) +- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) +- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) +- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) +- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) + +# v2.3.0 +- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) +- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) + +# v2.2.0 +- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) +- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) +- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) + +# v2.1.5 +- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) +- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) +- Avoid stack overflow case in queue +- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. +- Cleanup implementations of `some`, `every` and `find` + +# v2.1.3 +- Make bundle size smaller +- Create optimized hotpath for `filter` in array case. + +# v2.1.2 +- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). + +# v2.1.0 + +- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) +- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) +- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) +- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) +- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) + +# v2.0.1 + +- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). + +# v2.0.0 + +Lots of changes here! + +First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. + +The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. + +We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. + +Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. + +Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: + +1. Takes a variable number of arguments +2. The last argument is always a callback +3. The callback can accept any number of arguments +4. The first argument passed to the callback will be treated as an error result, if the argument is truthy +5. Any number of result arguments can be passed after the "error" argument +6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. + +There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, `filter`, `reject` and `detect`. + +Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. + +Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). + +## New Features + +- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) +- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) +- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) +- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) +- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) +- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) +- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). +- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) +- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) +- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) +- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) +- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). +- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) +- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) +- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) + +## Breaking changes + +- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) +- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) +- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) +- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- `filter`, `reject`, `some`, `every`, `detect` and their families like `{METHOD}Series` and `{METHOD}Limit` now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) +- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) +- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) +- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) +- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). +- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) +- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) +- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) + +## Bug Fixes + +- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). +- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). +- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). + +## Other + +- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. +- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). +- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) + +Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. + +------------------------------------------ + +# v1.5.2 +- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) +- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) +- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) +- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) +- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) +- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) +- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) +- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) +- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) +- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) +- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) + +# v1.4.2 + +- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) + +# v1.4.1 + +- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) +- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) +- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) + +# v1.4.0 + +- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) +- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) +- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers +- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) +- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) +- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) +- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) +- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) +- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769)) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)). +- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) +- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) +- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) +- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) +- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) +- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) +- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766)) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) +- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) +- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) +- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) +- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) +- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) +- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) +- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/nodejs/node_modules/async/LICENSE b/nodejs/node_modules/async/LICENSE new file mode 100644 index 00000000..b18aed69 --- /dev/null +++ b/nodejs/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2018 Caolan McMahon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/async/README.md b/nodejs/node_modules/async/README.md new file mode 100644 index 00000000..77f645e2 --- /dev/null +++ b/nodejs/node_modules/async/README.md @@ -0,0 +1,59 @@ +![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg) + +![Github Actions CI status](https://github.com/caolan/async/actions/workflows/ci.yml/badge.svg) +[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async) + + + +Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/v3/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm i async`, it can also be used directly in the browser. A ESM/MJS version is included in the main `async` package that should automatically be used with compatible bundlers such as Webpack and Rollup. + +A pure ESM version of Async is available as [`async-es`](https://www.npmjs.com/package/async-es). + +For Documentation, visit + +*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* + + +```javascript +// for use with Node-style callbacks... +var async = require("async"); + +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, (value, key, callback) => { + fs.readFile(__dirname + value, "utf8", (err, data) => { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }); +}, err => { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}); +``` + +```javascript +var async = require("async"); + +// ...or ES2017 async functions +async.mapLimit(urls, 5, async function(url) { + const response = await fetch(url) + return response.body +}, (err, results) => { + if (err) throw err + // results is now an array of the response bodies + console.log(results) +}) +``` diff --git a/nodejs/node_modules/async/all.js b/nodejs/node_modules/async/all.js new file mode 100644 index 00000000..622b3019 --- /dev/null +++ b/nodejs/node_modules/async/all.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/allLimit.js b/nodejs/node_modules/async/allLimit.js new file mode 100644 index 00000000..375e1260 --- /dev/null +++ b/nodejs/node_modules/async/allLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/allSeries.js b/nodejs/node_modules/async/allSeries.js new file mode 100644 index 00000000..9a6bf7d4 --- /dev/null +++ b/nodejs/node_modules/async/allSeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/any.js b/nodejs/node_modules/async/any.js new file mode 100644 index 00000000..a5bd328a --- /dev/null +++ b/nodejs/node_modules/async/any.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/anyLimit.js b/nodejs/node_modules/async/anyLimit.js new file mode 100644 index 00000000..3a8096fd --- /dev/null +++ b/nodejs/node_modules/async/anyLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/anySeries.js b/nodejs/node_modules/async/anySeries.js new file mode 100644 index 00000000..51aad19b --- /dev/null +++ b/nodejs/node_modules/async/anySeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/apply.js b/nodejs/node_modules/async/apply.js new file mode 100644 index 00000000..d40784f3 --- /dev/null +++ b/nodejs/node_modules/async/apply.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn, ...args) { + return (...callArgs) => fn(...args, ...callArgs); +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/applyEach.js b/nodejs/node_modules/async/applyEach.js new file mode 100644 index 00000000..841842c8 --- /dev/null +++ b/nodejs/node_modules/async/applyEach.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach.js'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _map = require('./map.js'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +exports.default = (0, _applyEach2.default)(_map2.default); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/applyEachSeries.js b/nodejs/node_modules/async/applyEachSeries.js new file mode 100644 index 00000000..f5267f67 --- /dev/null +++ b/nodejs/node_modules/async/applyEachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach.js'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _mapSeries = require('./mapSeries.js'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +exports.default = (0, _applyEach2.default)(_mapSeries2.default); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/asyncify.js b/nodejs/node_modules/async/asyncify.js new file mode 100644 index 00000000..ddc3f02f --- /dev/null +++ b/nodejs/node_modules/async/asyncify.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/auto.js b/nodejs/node_modules/async/auto.js new file mode 100644 index 00000000..163c4f27 --- /dev/null +++ b/nodejs/node_modules/async/auto.js @@ -0,0 +1,333 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = auto; + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return; + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = (0, _onlyOnce2.default)((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return; + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return; + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/autoInject.js b/nodejs/node_modules/async/autoInject.js new file mode 100644 index 00000000..38eac154 --- /dev/null +++ b/nodejs/node_modules/async/autoInject.js @@ -0,0 +1,182 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = autoInject; + +var _auto = require('./auto.js'); + +var _auto2 = _interopRequireDefault(_auto); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; + +function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index + 1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = endIndex === -1 ? string.length : endIndex; + } else if (endBlockComment !== -1 && string[index] === '/' && string[index + 1] === '*') { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; +} + +function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src); + let [, args] = match; + return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + (0, _wrapAsync2.default)(taskFn)(...newArgs); + } + }); + + return (0, _auto2.default)(newTasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/bower.json b/nodejs/node_modules/async/bower.json new file mode 100644 index 00000000..390c6502 --- /dev/null +++ b/nodejs/node_modules/async/bower.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "main": "dist/async.js", + "ignore": [ + "bower_components", + "lib", + "test", + "node_modules", + "perf", + "support", + "**/.*", + "*.config.js", + "*.json", + "index.js", + "Makefile" + ] +} diff --git a/nodejs/node_modules/async/cargo.js b/nodejs/node_modules/async/cargo.js new file mode 100644 index 00000000..d4abd214 --- /dev/null +++ b/nodejs/node_modules/async/cargo.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = cargo; + +var _queue = require('./internal/queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/concatLimit.js b/nodejs/node_modules/async/concatLimit.js new file mode 100644 index 00000000..a27cc7d4 --- /dev/null +++ b/nodejs/node_modules/async/concatLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/concatSeries.js b/nodejs/node_modules/async/concatSeries.js new file mode 100644 index 00000000..332de3f3 --- /dev/null +++ b/nodejs/node_modules/async/concatSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/constant.js b/nodejs/node_modules/async/constant.js new file mode 100644 index 00000000..ea406f65 --- /dev/null +++ b/nodejs/node_modules/async/constant.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (...args) { + return function (...ignoredArgs /*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/detect.js b/nodejs/node_modules/async/detect.js new file mode 100644 index 00000000..d5896ef6 --- /dev/null +++ b/nodejs/node_modules/async/detect.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/detectLimit.js b/nodejs/node_modules/async/detectLimit.js new file mode 100644 index 00000000..c59843b6 --- /dev/null +++ b/nodejs/node_modules/async/detectLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/detectSeries.js b/nodejs/node_modules/async/detectSeries.js new file mode 100644 index 00000000..b4868996 --- /dev/null +++ b/nodejs/node_modules/async/detectSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/dir.js b/nodejs/node_modules/async/dir.js new file mode 100644 index 00000000..8e9fafd7 --- /dev/null +++ b/nodejs/node_modules/async/dir.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc.js'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +exports.default = (0, _consoleFunc2.default)('dir'); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/dist/async.js b/nodejs/node_modules/async/dist/async.js new file mode 100644 index 00000000..e58f8f28 --- /dev/null +++ b/nodejs/node_modules/async/dist/async.js @@ -0,0 +1,6062 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.async = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } + + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } + + /* istanbul ignore file */ + + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + + function fallback(fn) { + setTimeout(fn, 0); + } + + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } + + var _defer$1; + + if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else if (hasNextTick) { + _defer$1 = process.nextTick; + } else { + _defer$1 = fallback; + } + + var setImmediate$1 = wrap(_defer$1); + + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } + + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } + + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } + + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } + + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } + + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } + + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable + } + + function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } + + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } + + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } + + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + var breakLoop$1 = breakLoop; + + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } + + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; + } + + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } + + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop$1 || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); + } + + var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop$1 || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; + }; + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$1 = awaitify(eachOfLimit, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop$1) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } + + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); + } + + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); + + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach = applyEach$1(map$1); + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach$1(mapSeries$1); + + const PROMISE_SYMBOL = Symbol('promiseCallback'); + + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback + } + + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] + } + + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + + function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; + } + + function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } + + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); + } + + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } + + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } + + function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } + + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); + + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; + } + + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } + + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); + + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } + + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop$1); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } + + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) + } + + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); + + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); + } + + var doWhilst$1 = awaitify(doWhilst, 3); + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ + function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit$2, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$1 = awaitify(eachLimit, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } + + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); + + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } + + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } + + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); + } + + var groupByLimit$1 = awaitify(groupByLimit, 4); + + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /* istanbul ignore file */ + + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer; + + if (hasNextTick) { + _defer = process.nextTick; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else { + _defer = fallback; + } + + var nextTick = wrap(_defer); + + var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); + + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } + + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } + } + + function leftChi(i) { + return (i<<1)+1; + } + + function parent(i) { + return ((i+1)>>1)-1; + } + + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } + + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; + } + + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } + + function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) + } + var reject$1 = awaitify(reject, 3); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant(value) { + return function () { + return value; + } + } + + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; + + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] + } + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); + } + + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); + + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); + + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } + + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } + + var tryEach$1 = awaitify(tryEach); + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); + + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + + var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant$1; + exports.default = index; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doDuring = doWhilst$1; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.during = whilst$1; + exports.each = each; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$1; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$1; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.wrapSync = asyncify; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/nodejs/node_modules/async/dist/async.min.js b/nodejs/node_modules/async/dist/async.min.js new file mode 100644 index 00000000..f5c464e3 --- /dev/null +++ b/nodejs/node_modules/async/dist/async.min.js @@ -0,0 +1 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(e="undefined"==typeof globalThis?e||self:globalThis,t(e.async={}))})(this,function(e){"use strict";function t(e,...t){return(...n)=>e(...t,...n)}function n(e){return function(...t){var n=t.pop();return e.call(this,t,n)}}function a(e){setTimeout(e,0)}function i(e){return(t,...n)=>e(()=>t(...n))}function r(e){return d(e)?function(...t){const n=t.pop(),a=e.apply(this,t);return s(a,n)}:n(function(t,n){var a;try{a=e.apply(this,t)}catch(t){return n(t)}return a&&"function"==typeof a.then?s(a,n):void n(null,a)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&(e instanceof Error||e.message)?e:new Error(e))})}function l(e,t,n){try{e(t,n)}catch(e){_e(t=>{throw t},e)}}function d(e){return"AsyncFunction"===e[Symbol.toStringTag]}function u(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function p(e){return"function"==typeof e[Symbol.asyncIterator]}function c(e){if("function"!=typeof e)throw new Error("expected a function");return d(e)?r(e):e}function o(e,t){function n(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise((a,i)=>{n[t-1]=(e,...t)=>e?i(e):void a(1{c(e).apply(i,n.concat(t))},a)});return i}}function f(e,t,n,a){t=t||[];var i=[],r=0,s=c(n);return e(t,(e,t,n)=>{var a=r++;s(e,(e,t)=>{i[a]=t,n(e)})},e=>{a(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,n=e.length;return function a(){return++t=t||u||l||(u=!0,e.next().then(({value:e,done:t})=>{if(!(d||l))return u=!1,t?(l=!0,void(0>=p&&a(null))):void(p++,n(e,c,r),c++,i())}).catch(s))}function r(e,t){return p-=1,d?void 0:e?s(e):!1===e?(l=!0,void(d=!0)):t===be||l&&0>=p?(l=!0,a(null)):void i()}function s(e){d||(u=!1,l=!0,a(e))}let l=!1,d=!1,u=!1,p=0,c=0;i()}function O(e,t,n){function a(e,t){!1===e&&(l=!0);!0===l||(e?n(e):(++r===s||t===be)&&n(null))}n=m(n);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&n(null);i{t=e,n=a}),e}function A(e,t,n){function a(e,t){k.push(()=>l(e,t))}function i(){if(!f){if(0===k.length&&0===h)return n(null,o);for(;k.length&&he()),i()}function l(e,t){if(!y){var a=L((t,...a)=>{if(h--,!1===t)return void(f=!0);if(2>a.length&&([a]=a),t){var i={};if(Object.keys(o).forEach(e=>{i[e]=o[e]}),i[e]=a,y=!0,g=Object.create(null),f)return;n(t,i)}else o[e]=a,s(e)});h++;var i=c(t[t.length-1]);1{0==--S[e]&&v.push(e)});if(t!==p)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function u(t){var n=[];return Object.keys(e).forEach(a=>{const i=e[a];Array.isArray(i)&&0<=i.indexOf(t)&&n.push(a)}),n}"number"!=typeof t&&(n=t,t=null),n=m(n||b());var p=Object.keys(e).length;if(!p)return n(null);t||(t=p);var o={},h=0,f=!1,y=!1,g=Object.create(null),k=[],v=[],S={};return Object.keys(e).forEach(t=>{var n=e[t];if(!Array.isArray(n))return a(t,[n]),void v.push(t);var i=n.slice(0,n.length-1),s=i.length;return 0===s?(a(t,n),void v.push(t)):void(S[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&a(t,n)})}))}),d(),i(),n[Ce]}function I(e){let t="",n=0,a=e.indexOf("*/");for(;ne.replace(Ne,"").trim())}function j(e,t){var n={};return Object.keys(e).forEach(t=>{function a(e,t){var n=i.map(t=>e[t]);n.push(t),c(r)(...n)}var i,r=e[t],s=d(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),n[t]=i.concat(0{r(e,n),t(...a)};f[e].push(n)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,n,a){function i(e,...t){return e?n?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");k.started=!0;var r,s,l=k._createTaskItem(e,n?i:a||i);if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,_e(()=>{y=!1,k.process()})),n||!a)return new Promise((e,t)=>{r=e,s=t})}function d(e){return function(t,...n){o-=1;for(var a=0,r=e.length;as("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var p=c(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),a(e,t)):new Promise((t,n)=>{i(e,(e,a)=>e?n(e):void t(a))});var g=!1,k={_tasks:new Ve,_createTaskItem(e,t){return{data:e,callback:t}},*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:n,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o{t.apply(n,e.concat((e,...t)=>{a(e,t)}))},(e,t)=>a(e,...t)),a[Ce]}}function P(...e){return C(...e.reverse())}function R(...e){return function(...t){var n=t.pop();return n(null,...e)}}function z(e,t){return(n,a,i,r)=>{var s,l=!1;const d=c(i);n(a,(n,a,i)=>{d(n,(a,r)=>a||!1===a?i(a):e(r)&&!s?(l=!0,s=t(!0,n),i(null,be)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function N(e){return(t,...n)=>c(t)(...n,(t,...n)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&n.forEach(t=>console[e](t)))})}function V(e,t,n){const a=c(t);return Xe(e,(...e)=>{const t=e.pop();a(...e,(e,n)=>t(e,!n))},n)}function Y(e){return(t,n,a)=>e(t,a)}function q(e){return d(e)?e:function(...t){var n=t.pop(),a=!0;t.push((...e)=>{a?_e(()=>n(...e)):n(...e)}),e.apply(this,t),a=!1}}function D(e,t,n,a){var r=Array(t.length);e(t,(e,t,a)=>{n(e,(e,n)=>{r[t]=!!n,a(e)})},e=>{if(e)return a(e);for(var n=[],s=0;s{n(e,(n,r)=>n?a(n):void(r&&i.push({index:t,value:e}),a(n)))},e=>e?a(e):void a(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function U(e,t,n,a){var i=y(t)?D:Q;return i(e,t,c(n),a)}function G(e,t,n){return dt(e,1/0,t,n)}function W(e,t,n){return dt(e,1,t,n)}function H(e,t,n){return pt(e,1/0,t,n)}function J(e,t,n){return pt(e,1,t,n)}function K(e,t=e=>e){var a=Object.create(null),r=Object.create(null),s=c(e),l=n((e,n)=>{var d=t(...e);d in a?_e(()=>n(null,...a[d])):d in r?r[d].push(n):(r[d]=[n],s(...e,(e,...t)=>{e||(a[d]=t);var n=r[d];delete r[d];for(var s=0,u=n.length;s{n(e[0],t)},t,1)}function ee(e){return(e<<1)+1}function te(e){return(e+1>>1)-1}function ne(e,t){return e.priority===t.priority?e.pushCount({data:e,priority:t})):{data:e,priority:t}}var a=$(e,t),{push:i,pushAsync:r}=a;return a._tasks=new ht,a._createTaskItem=({data:e,priority:t},n)=>({data:e,priority:t,callback:n}),a.push=function(e,t=0,a){return i(n(e,t),a)},a.pushAsync=function(e,t=0,a){return r(n(e,t),a)},delete a.unshift,delete a.unshiftAsync,a}function ie(e,t,n,a){var i=[...e].reverse();return qe(i,t,n,a)}function re(e){var t=c(e);return n(function a(e,n){return e.push((e,...t)=>{let a={};if(e&&(a.error=e),0=t.length&&([i]=t),a.value=i}n(null,a)}),t.apply(this,e)})}function se(e){var t;return Array.isArray(e)?t=e.map(re):(t={},Object.keys(e).forEach(n=>{t[n]=re.call(this,e[n])})),t}function le(e,t,n,a){const i=c(n);return U(e,t,(e,t)=>{i(e,(e,n)=>{t(e,!n)})},a)}function de(e){return function(){return e}}function ue(e,t,n){function a(){r((e,...t)=>{!1===e||(e&&s++arguments.length&&"function"==typeof e?(n=t||b(),t=e):(pe(i,e),n=n||b()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=c(t),s=1;return a(),n[Ce]}function pe(e,n){if("object"==typeof n)e.times=+n.times||kt,e.intervalFunc="function"==typeof n.interval?n.interval:de(+n.interval||vt),e.errorFilter=n.errorFilter;else if("number"==typeof n||"string"==typeof n)e.times=+n||kt;else throw new Error("Invalid arguments for async.retry")}function ce(e,t){t||(t=e,e=null);let a=e&&e.arity||t.length;d(t)&&(a+=1);var i=c(t);return n((t,n)=>{function r(e){i(...t,e)}return(t.length{function s(){var t=e.name||"anonymous",n=new Error("Callback function \""+t+"\" timed out.");n.code="ETIMEDOUT",a&&(n.info=a),d=!0,r(n)}var l,d=!1;n.push((...e)=>{d||(r(...e),clearTimeout(l))}),l=setTimeout(s,t),i(...n)})}function fe(e){for(var t=Array(e);e--;)t[e]=e;return t}function ye(e,t,n,a){var i=c(n);return De(fe(e),t,i,a)}function me(e,t,n){return ye(e,1/0,t,n)}function ge(e,t,n){return ye(e,1,t,n)}function ke(e,t,n,a){3>=arguments.length&&"function"==typeof t&&(a=n,n=t,t=Array.isArray(e)?[]:{}),a=m(a||b());var i=c(n);return Me(e,(e,n,a)=>{i(t,e,n,a)},e=>a(e,t)),a[Ce]}function ve(e){return(...t)=>(e.unmemoized||e)(...t)}function Se(e,t,n){const a=c(e);return _t(e=>a((t,n)=>e(t,!n)),t,n)}var xe,Le="function"==typeof queueMicrotask&&queueMicrotask,Ee="function"==typeof setImmediate&&setImmediate,Oe="object"==typeof process&&"function"==typeof process.nextTick;xe=Le?queueMicrotask:Ee?setImmediate:Oe?process.nextTick:a;var _e=i(xe);var be={},Ae=e=>(t,n,a)=>{function i(e,t){if(!d)if(c-=1,e)l=!0,a(e);else if(!1===e)l=!0,d=!0;else{if(t===be||l&&0>=c)return l=!0,a(null);o||r()}}function r(){for(o=!0;c=c&&a(null));c+=1,n(t.value,t.key,L(i))}o=!1}if(a=m(a),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return a(null);if(u(t))return E(t,e,n,a);if(p(t))return E(t[Symbol.asyncIterator](),e,n,a);var s=x(t),l=!1,d=!1,c=0,o=!1;r()},Ie=o(function i(e,t,n,a){return Ae(t)(e,c(n),a)},4),Me=o(function a(e,t,n){var i=y(e)?O:_;return i(e,c(t),n)},3),je=o(function a(e,t,n){return f(Me,e,t,n)},3),we=h(je),Be=o(function a(e,t,n){return Ie(e,1,t,n)},3),Te=o(function a(e,t,n){return f(Be,e,t,n)},3),Fe=h(Te);const Ce=Symbol("promiseCallback");var Pe=/^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/,Re=/^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/,ze=/,/,Ne=/(=.+)?(\s*)$/;class Ve{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):w(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):w(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:n}=t;e(t)&&this.removeLink(t),t=n}return this}}var Ye,qe=o(function i(e,t,n,a){a=m(a);var r=c(n);return Be(e,(e,n,a)=>{r(t,e,(e,n)=>{t=n,a(e)})},e=>a(e,t))},4),De=o(function i(e,t,n,a){return f(Ae(t),e,n,a)},4),Qe=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(e,...n)=>e?t(e):t(e,n))},(e,t)=>{for(var n=[],r=0;re,(e,t)=>t)(Me,e,t,n)},3),He=o(function i(e,t,n,a){return z(e=>e,(e,t)=>t)(Ae(t),e,n,a)},4),Je=o(function a(e,t,n){return z(e=>e,(e,t)=>t)(Ae(1),e,t,n)},3),Ke=N("dir"),Xe=o(function a(e,t,n){function i(e,...t){return e?n(e):void(!1===e||(s=t,d(...t,r)))}function r(e,t){return e?n(e):!1===e?void 0:t?void l(i):n(null,...s)}n=L(n);var s,l=c(e),d=c(t);return r(null,!0)},3),Ze=o(function a(e,t,n){return Me(e,Y(c(t)),n)},3),$e=o(function i(e,t,n,a){return Ae(t)(e,Y(c(n)),a)},4),et=o(function a(e,t,n){return $e(e,1,t,n)},3),tt=o(function a(e,t,n){return z(e=>!e,e=>!e)(Me,e,t,n)},3),nt=o(function i(e,t,n,a){return z(e=>!e,e=>!e)(Ae(t),e,n,a)},4),at=o(function a(e,t,n){return z(e=>!e,e=>!e)(Be,e,t,n)},3),it=o(function a(e,t,n){return U(Me,e,t,n)},3),rt=o(function i(e,t,n,a){return U(Ae(t),e,n,a)},4),st=o(function a(e,t,n){return U(Be,e,t,n)},3),lt=o(function n(e,t){function a(e){return e?i(e):void(!1===e||r(a))}var i=L(t),r=c(q(e));return a()},2),dt=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(n,a)=>n?t(n):t(n,{key:a,val:e}))},(e,t)=>{for(var n={},{hasOwnProperty:r}=Object.prototype,s=0;s{s(e,t,(e,a)=>e?n(e):void(r[t]=a,n(e)))},e=>a(e,r))},4);Ye=Oe?process.nextTick:Ee?setImmediate:a;var ct=i(Ye),ot=o((e,t,n)=>{var a=y(t)?[]:{};e(t,(e,t,n)=>{c(e)((e,...i)=>{2>i.length&&([i]=i),a[t]=i,n(e)})},e=>n(e,a))},3);class ht{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let n;0e)(Me,e,t,n)},3),xt=o(function i(e,t,n,a){return z(Boolean,e=>e)(Ae(t),e,n,a)},4),Lt=o(function a(e,t,n){return z(Boolean,e=>e)(Be,e,t,n)},3),Et=o(function a(e,t,n){function i(e,t){var n=e.criteria,a=t.criteria;return na?1:0}var r=c(t);return je(e,(e,t)=>{r(e,(n,a)=>n?t(n):void t(n,{value:e,criteria:a}))},(e,t)=>e?n(e):void n(null,t.sort(i).map(e=>e.value)))},3),Ot=o(function n(e,t){var a,i=null;return et(e,(e,t)=>{c(e)((e,...n)=>!1===e?t(e):void(2>n.length?[a]=n:a=n,i=e,t(e?null:{})))},()=>t(i,a))}),_t=o(function a(e,t,n){function i(e,...t){if(e)return n(e);d=t;!1===e||l(r)}function r(e,t){return e?n(e):!1===e?void 0:t?void s(i):n(null,...d)}n=L(n);var s=c(t),l=c(e),d=[];return l(r)},3),bt=o(function n(e,t){function a(t){var n=c(e[r++]);n(...t,L(i))}function i(n,...i){return!1===n?void 0:n||r===e.length?t(n,...i):void a(i)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;a([])});e.all=tt,e.allLimit=nt,e.allSeries=at,e.any=St,e.anyLimit=xt,e.anySeries=Lt,e.apply=t,e.applyEach=we,e.applyEachSeries=Fe,e.asyncify=r,e.auto=A,e.autoInject=j,e.cargo=T,e.cargoQueue=F,e.compose=P,e.concat=Ue,e.concatLimit=Qe,e.concatSeries=Ge,e.constant=R,e.default={apply:t,applyEach:we,applyEachSeries:Fe,asyncify:r,auto:A,autoInject:j,cargo:T,cargoQueue:F,compose:P,concat:Ue,concatLimit:Qe,concatSeries:Ge,constant:R,detect:We,detectLimit:He,detectSeries:Je,dir:Ke,doUntil:V,doWhilst:Xe,each:Ze,eachLimit:$e,eachOf:Me,eachOfLimit:Ie,eachOfSeries:Be,eachSeries:et,ensureAsync:q,every:tt,everyLimit:nt,everySeries:at,filter:it,filterLimit:rt,filterSeries:st,forever:lt,groupBy:G,groupByLimit:dt,groupBySeries:W,log:ut,map:je,mapLimit:De,mapSeries:Te,mapValues:H,mapValuesLimit:pt,mapValuesSeries:J,memoize:K,nextTick:ct,parallel:X,parallelLimit:Z,priorityQueue:ae,queue:$,race:ft,reduce:qe,reduceRight:ie,reflect:re,reflectAll:se,reject:yt,rejectLimit:mt,rejectSeries:gt,retry:ue,retryable:ce,seq:C,series:oe,setImmediate:_e,some:St,someLimit:xt,someSeries:Lt,sortBy:Et,timeout:he,times:me,timesLimit:ye,timesSeries:ge,transform:ke,tryEach:Ot,unmemoize:ve,until:Se,waterfall:bt,whilst:_t,all:tt,allLimit:nt,allSeries:at,any:St,anyLimit:xt,anySeries:Lt,find:We,findLimit:He,findSeries:Je,flatMap:Ue,flatMapLimit:Qe,flatMapSeries:Ge,forEach:Ze,forEachSeries:et,forEachLimit:$e,forEachOf:Me,forEachOfSeries:Be,forEachOfLimit:Ie,inject:qe,foldl:qe,foldr:ie,select:it,selectLimit:rt,selectSeries:st,wrapSync:r,during:_t,doDuring:Xe},e.detect=We,e.detectLimit=He,e.detectSeries=Je,e.dir=Ke,e.doDuring=Xe,e.doUntil=V,e.doWhilst=Xe,e.during=_t,e.each=Ze,e.eachLimit=$e,e.eachOf=Me,e.eachOfLimit=Ie,e.eachOfSeries=Be,e.eachSeries=et,e.ensureAsync=q,e.every=tt,e.everyLimit=nt,e.everySeries=at,e.filter=it,e.filterLimit=rt,e.filterSeries=st,e.find=We,e.findLimit=He,e.findSeries=Je,e.flatMap=Ue,e.flatMapLimit=Qe,e.flatMapSeries=Ge,e.foldl=qe,e.foldr=ie,e.forEach=Ze,e.forEachLimit=$e,e.forEachOf=Me,e.forEachOfLimit=Ie,e.forEachOfSeries=Be,e.forEachSeries=et,e.forever=lt,e.groupBy=G,e.groupByLimit=dt,e.groupBySeries=W,e.inject=qe,e.log=ut,e.map=je,e.mapLimit=De,e.mapSeries=Te,e.mapValues=H,e.mapValuesLimit=pt,e.mapValuesSeries=J,e.memoize=K,e.nextTick=ct,e.parallel=X,e.parallelLimit=Z,e.priorityQueue=ae,e.queue=$,e.race=ft,e.reduce=qe,e.reduceRight=ie,e.reflect=re,e.reflectAll=se,e.reject=yt,e.rejectLimit=mt,e.rejectSeries=gt,e.retry=ue,e.retryable=ce,e.select=it,e.selectLimit=rt,e.selectSeries=st,e.seq=C,e.series=oe,e.setImmediate=_e,e.some=St,e.someLimit=xt,e.someSeries=Lt,e.sortBy=Et,e.timeout=he,e.times=me,e.timesLimit=ye,e.timesSeries=ge,e.transform=ke,e.tryEach=Ot,e.unmemoize=ve,e.until=Se,e.waterfall=bt,e.whilst=_t,e.wrapSync=r,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/nodejs/node_modules/async/dist/async.mjs b/nodejs/node_modules/async/dist/async.mjs new file mode 100644 index 00000000..41c63c15 --- /dev/null +++ b/nodejs/node_modules/async/dist/async.mjs @@ -0,0 +1,5949 @@ +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); +} + +function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +} + +/* istanbul ignore file */ + +var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer$1; + +if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; +} else if (hasSetImmediate) { + _defer$1 = setImmediate; +} else if (hasNextTick) { + _defer$1 = process.nextTick; +} else { + _defer$1 = fallback; +} + +var setImmediate$1 = wrap(_defer$1); + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } +} + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable +} + +function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +} + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} + +function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; +var breakLoop$1 = breakLoop; + +function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper +} + +function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +} + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; +} + +function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} + +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop$1 || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} + +var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop$1 || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); +} + +var eachOfLimit$1 = awaitify(eachOfLimit, 4); + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop$1) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); +} + +var eachOf$1 = awaitify(eachOf, 3); + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) +} +var map$1 = awaitify(map, 3); + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +var applyEach = applyEach$1(map$1); + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) +} +var eachOfSeries$1 = awaitify(eachOfSeries, 3); + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) +} +var mapSeries$1 = awaitify(mapSeries, 3); + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +var applyEachSeries = applyEach$1(mapSeries$1); + +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback +} + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] +} + +var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; + +function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; +} + +function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); +} + +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; +} + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +var reduce$1 = awaitify(reduce, 4); + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; +} + +/** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ +function compose(...args) { + return seq(...args.reverse()); +} + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) +} +var mapLimit$1 = awaitify(mapLimit, 4); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +var concatLimit$1 = awaitify(concatLimit, 4); + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) +} +var concat$1 = awaitify(concat, 3); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) +} +var concatSeries$1 = awaitify(concatSeries, 3); + +/** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ +function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +} + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop$1); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) +} +var detect$1 = awaitify(detect, 3); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var detectLimit$1 = awaitify(detectLimit, 4); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) +} + +var detectSeries$1 = awaitify(detectSeries, 3); + +function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) +} + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +var dir = consoleFunc('dir'); + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +var doWhilst$1 = awaitify(doWhilst, 3); + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); +} + +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +var each = awaitify(eachLimit$2, 3); + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} +var eachLimit$1 = awaitify(eachLimit, 4); + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) +} +var eachSeries$1 = awaitify(eachSeries, 3); + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) +} +var every$1 = awaitify(every, 3); + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var everyLimit$1 = awaitify(everyLimit, 4); + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) +} +var everySeries$1 = awaitify(everySeries, 3); + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); +} + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) +} +var filter$1 = awaitify(filter, 3); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) +} +var filterLimit$1 = awaitify(filterLimit, 4); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) +} +var filterSeries$1 = awaitify(filterSeries, 3); + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +var forever$1 = awaitify(forever, 2); + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +var groupByLimit$1 = awaitify(groupByLimit, 4); + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) +} + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) +} + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +var log = consoleFunc('log'); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) +} + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} + +/* istanbul ignore file */ + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; + +if (hasNextTick) { + _defer = process.nextTick; +} else if (hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = fallback; +} + +var nextTick = wrap(_defer); + +var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); +} + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); +} + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +} + +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +function leftChi(i) { + return (i<<1)+1; +} + +function parent(i) { + return ((i+1)>>1)-1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } +} + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ +function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; +} + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } +} + +var race$1 = awaitify(race, 2); + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); +} + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; +} + +function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) +} +var reject$1 = awaitify(reject, 3); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) +} +var rejectLimit$1 = awaitify(rejectLimit, 4); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) +} +var rejectSeries$1 = awaitify(rejectSeries, 3); + +function constant(value) { + return function () { + return value; + } +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); +} + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); +} + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) +} +var some$1 = awaitify(some, 3); + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var someLimit$1 = awaitify(someLimit, 4); + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) +} +var someSeries$1 = awaitify(someSeries, 3); + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +var sortBy$1 = awaitify(sortBy, 3); + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} + +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); +} + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) +} + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] +} + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +var tryEach$1 = awaitify(tryEach); + +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +var whilst$1 = awaitify(whilst, 3); + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); +} + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +var waterfall$1 = awaitify(waterfall); + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + +var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 +}; + +export { every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, apply, applyEach, applyEachSeries, asyncify, auto, autoInject, cargo$1 as cargo, cargo as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant$1 as constant, index as default, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doWhilst$1 as doDuring, doUntil, doWhilst$1 as doWhilst, whilst$1 as during, each, eachLimit$1 as eachLimit, eachOf$1 as eachOf, eachOfLimit$1 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, reduce$1 as foldl, reduceRight as foldr, each as forEach, eachLimit$1 as forEachLimit, eachOf$1 as forEachOf, eachOfLimit$1 as forEachOfLimit, eachOfSeries$1 as forEachOfSeries, eachSeries$1 as forEachSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, reduce$1 as inject, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$1 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, asyncify as wrapSync }; diff --git a/nodejs/node_modules/async/doDuring.js b/nodejs/node_modules/async/doDuring.js new file mode 100644 index 00000000..c72766d0 --- /dev/null +++ b/nodejs/node_modules/async/doDuring.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/doUntil.js b/nodejs/node_modules/async/doUntil.js new file mode 100644 index 00000000..519900ee --- /dev/null +++ b/nodejs/node_modules/async/doUntil.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doUntil; + +var _doWhilst = require('./doWhilst.js'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _doWhilst2.default)(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb(err, !truth)); + }, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/doWhilst.js b/nodejs/node_modules/async/doWhilst.js new file mode 100644 index 00000000..c72766d0 --- /dev/null +++ b/nodejs/node_modules/async/doWhilst.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/during.js b/nodejs/node_modules/async/during.js new file mode 100644 index 00000000..4165543f --- /dev/null +++ b/nodejs/node_modules/async/during.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/each.js b/nodejs/node_modules/async/each.js new file mode 100644 index 00000000..fdfcbd88 --- /dev/null +++ b/nodejs/node_modules/async/each.js @@ -0,0 +1,129 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/eachLimit.js b/nodejs/node_modules/async/eachLimit.js new file mode 100644 index 00000000..7f5928c6 --- /dev/null +++ b/nodejs/node_modules/async/eachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/eachOf.js b/nodejs/node_modules/async/eachOf.js new file mode 100644 index 00000000..9ed20f66 --- /dev/null +++ b/nodejs/node_modules/async/eachOf.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/eachOfLimit.js b/nodejs/node_modules/async/eachOfLimit.js new file mode 100644 index 00000000..a596e5ac --- /dev/null +++ b/nodejs/node_modules/async/eachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit.js'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/eachOfSeries.js b/nodejs/node_modules/async/eachOfSeries.js new file mode 100644 index 00000000..04243ada --- /dev/null +++ b/nodejs/node_modules/async/eachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/eachSeries.js b/nodejs/node_modules/async/eachSeries.js new file mode 100644 index 00000000..b04896e3 --- /dev/null +++ b/nodejs/node_modules/async/eachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit.js'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/ensureAsync.js b/nodejs/node_modules/async/ensureAsync.js new file mode 100644 index 00000000..749c5dac --- /dev/null +++ b/nodejs/node_modules/async/ensureAsync.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ensureAsync; + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if ((0, _wrapAsync.isAsync)(fn)) return fn; + return function (...args /*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + (0, _setImmediate2.default)(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/every.js b/nodejs/node_modules/async/every.js new file mode 100644 index 00000000..622b3019 --- /dev/null +++ b/nodejs/node_modules/async/every.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/everyLimit.js b/nodejs/node_modules/async/everyLimit.js new file mode 100644 index 00000000..375e1260 --- /dev/null +++ b/nodejs/node_modules/async/everyLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/everySeries.js b/nodejs/node_modules/async/everySeries.js new file mode 100644 index 00000000..9a6bf7d4 --- /dev/null +++ b/nodejs/node_modules/async/everySeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/filter.js b/nodejs/node_modules/async/filter.js new file mode 100644 index 00000000..2c9a63de --- /dev/null +++ b/nodejs/node_modules/async/filter.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/filterLimit.js b/nodejs/node_modules/async/filterLimit.js new file mode 100644 index 00000000..d3b3f50c --- /dev/null +++ b/nodejs/node_modules/async/filterLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/filterSeries.js b/nodejs/node_modules/async/filterSeries.js new file mode 100644 index 00000000..019a2d0a --- /dev/null +++ b/nodejs/node_modules/async/filterSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/find.js b/nodejs/node_modules/async/find.js new file mode 100644 index 00000000..d5896ef6 --- /dev/null +++ b/nodejs/node_modules/async/find.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/findLimit.js b/nodejs/node_modules/async/findLimit.js new file mode 100644 index 00000000..c59843b6 --- /dev/null +++ b/nodejs/node_modules/async/findLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/findSeries.js b/nodejs/node_modules/async/findSeries.js new file mode 100644 index 00000000..b4868996 --- /dev/null +++ b/nodejs/node_modules/async/findSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/flatMap.js b/nodejs/node_modules/async/flatMap.js new file mode 100644 index 00000000..4540a79c --- /dev/null +++ b/nodejs/node_modules/async/flatMap.js @@ -0,0 +1,115 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/flatMapLimit.js b/nodejs/node_modules/async/flatMapLimit.js new file mode 100644 index 00000000..a27cc7d4 --- /dev/null +++ b/nodejs/node_modules/async/flatMapLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/flatMapSeries.js b/nodejs/node_modules/async/flatMapSeries.js new file mode 100644 index 00000000..332de3f3 --- /dev/null +++ b/nodejs/node_modules/async/flatMapSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/foldl.js b/nodejs/node_modules/async/foldl.js new file mode 100644 index 00000000..8a69548a --- /dev/null +++ b/nodejs/node_modules/async/foldl.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/foldr.js b/nodejs/node_modules/async/foldr.js new file mode 100644 index 00000000..5be1b68d --- /dev/null +++ b/nodejs/node_modules/async/foldr.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forEach.js b/nodejs/node_modules/async/forEach.js new file mode 100644 index 00000000..fdfcbd88 --- /dev/null +++ b/nodejs/node_modules/async/forEach.js @@ -0,0 +1,129 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forEachLimit.js b/nodejs/node_modules/async/forEachLimit.js new file mode 100644 index 00000000..7f5928c6 --- /dev/null +++ b/nodejs/node_modules/async/forEachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forEachOf.js b/nodejs/node_modules/async/forEachOf.js new file mode 100644 index 00000000..9ed20f66 --- /dev/null +++ b/nodejs/node_modules/async/forEachOf.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forEachOfLimit.js b/nodejs/node_modules/async/forEachOfLimit.js new file mode 100644 index 00000000..a596e5ac --- /dev/null +++ b/nodejs/node_modules/async/forEachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit.js'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forEachOfSeries.js b/nodejs/node_modules/async/forEachOfSeries.js new file mode 100644 index 00000000..04243ada --- /dev/null +++ b/nodejs/node_modules/async/forEachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forEachSeries.js b/nodejs/node_modules/async/forEachSeries.js new file mode 100644 index 00000000..b04896e3 --- /dev/null +++ b/nodejs/node_modules/async/forEachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit.js'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/forever.js b/nodejs/node_modules/async/forever.js new file mode 100644 index 00000000..22925185 --- /dev/null +++ b/nodejs/node_modules/async/forever.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _ensureAsync = require('./ensureAsync.js'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = (0, _onlyOnce2.default)(errback); + var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +exports.default = (0, _awaitify2.default)(forever, 2); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/groupBy.js b/nodejs/node_modules/async/groupBy.js new file mode 100644 index 00000000..f2957630 --- /dev/null +++ b/nodejs/node_modules/async/groupBy.js @@ -0,0 +1,108 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBy; + +var _groupByLimit = require('./groupByLimit.js'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function groupBy(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/groupByLimit.js b/nodejs/node_modules/async/groupByLimit.js new file mode 100644 index 00000000..30fd290a --- /dev/null +++ b/nodejs/node_modules/async/groupByLimit.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, { key, val }); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var { hasOwnProperty } = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var { key } = mapResults[i]; + var { val } = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +exports.default = (0, _awaitify2.default)(groupByLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/groupBySeries.js b/nodejs/node_modules/async/groupBySeries.js new file mode 100644 index 00000000..e2a52874 --- /dev/null +++ b/nodejs/node_modules/async/groupBySeries.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBySeries; + +var _groupByLimit = require('./groupByLimit.js'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/index.js b/nodejs/node_modules/async/index.js new file mode 100644 index 00000000..6154647d --- /dev/null +++ b/nodejs/node_modules/async/index.js @@ -0,0 +1,588 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.doDuring = exports.during = exports.wrapSync = undefined; +exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.flatMapSeries = exports.flatMapLimit = exports.flatMap = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.doWhilst = exports.doUntil = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargoQueue = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; + +var _apply = require('./apply'); + +var _apply2 = _interopRequireDefault(_apply); + +var _applyEach = require('./applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _applyEachSeries = require('./applyEachSeries'); + +var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); + +var _asyncify = require('./asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _autoInject = require('./autoInject'); + +var _autoInject2 = _interopRequireDefault(_autoInject); + +var _cargo = require('./cargo'); + +var _cargo2 = _interopRequireDefault(_cargo); + +var _cargoQueue = require('./cargoQueue'); + +var _cargoQueue2 = _interopRequireDefault(_cargoQueue); + +var _compose = require('./compose'); + +var _compose2 = _interopRequireDefault(_compose); + +var _concat = require('./concat'); + +var _concat2 = _interopRequireDefault(_concat); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _concatSeries = require('./concatSeries'); + +var _concatSeries2 = _interopRequireDefault(_concatSeries); + +var _constant = require('./constant'); + +var _constant2 = _interopRequireDefault(_constant); + +var _detect = require('./detect'); + +var _detect2 = _interopRequireDefault(_detect); + +var _detectLimit = require('./detectLimit'); + +var _detectLimit2 = _interopRequireDefault(_detectLimit); + +var _detectSeries = require('./detectSeries'); + +var _detectSeries2 = _interopRequireDefault(_detectSeries); + +var _dir = require('./dir'); + +var _dir2 = _interopRequireDefault(_dir); + +var _doUntil = require('./doUntil'); + +var _doUntil2 = _interopRequireDefault(_doUntil); + +var _doWhilst = require('./doWhilst'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _each = require('./each'); + +var _each2 = _interopRequireDefault(_each); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _every = require('./every'); + +var _every2 = _interopRequireDefault(_every); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _everySeries = require('./everySeries'); + +var _everySeries2 = _interopRequireDefault(_everySeries); + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _filterSeries = require('./filterSeries'); + +var _filterSeries2 = _interopRequireDefault(_filterSeries); + +var _forever = require('./forever'); + +var _forever2 = _interopRequireDefault(_forever); + +var _groupBy = require('./groupBy'); + +var _groupBy2 = _interopRequireDefault(_groupBy); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +var _groupBySeries = require('./groupBySeries'); + +var _groupBySeries2 = _interopRequireDefault(_groupBySeries); + +var _log = require('./log'); + +var _log2 = _interopRequireDefault(_log); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +var _mapValues = require('./mapValues'); + +var _mapValues2 = _interopRequireDefault(_mapValues); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _mapValuesSeries = require('./mapValuesSeries'); + +var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); + +var _memoize = require('./memoize'); + +var _memoize2 = _interopRequireDefault(_memoize); + +var _nextTick = require('./nextTick'); + +var _nextTick2 = _interopRequireDefault(_nextTick); + +var _parallel = require('./parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +var _parallelLimit = require('./parallelLimit'); + +var _parallelLimit2 = _interopRequireDefault(_parallelLimit); + +var _priorityQueue = require('./priorityQueue'); + +var _priorityQueue2 = _interopRequireDefault(_priorityQueue); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _race = require('./race'); + +var _race2 = _interopRequireDefault(_race); + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _reduceRight = require('./reduceRight'); + +var _reduceRight2 = _interopRequireDefault(_reduceRight); + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +var _reflectAll = require('./reflectAll'); + +var _reflectAll2 = _interopRequireDefault(_reflectAll); + +var _reject = require('./reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _rejectLimit = require('./rejectLimit'); + +var _rejectLimit2 = _interopRequireDefault(_rejectLimit); + +var _rejectSeries = require('./rejectSeries'); + +var _rejectSeries2 = _interopRequireDefault(_rejectSeries); + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _retryable = require('./retryable'); + +var _retryable2 = _interopRequireDefault(_retryable); + +var _seq = require('./seq'); + +var _seq2 = _interopRequireDefault(_seq); + +var _series = require('./series'); + +var _series2 = _interopRequireDefault(_series); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _some = require('./some'); + +var _some2 = _interopRequireDefault(_some); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _someSeries = require('./someSeries'); + +var _someSeries2 = _interopRequireDefault(_someSeries); + +var _sortBy = require('./sortBy'); + +var _sortBy2 = _interopRequireDefault(_sortBy); + +var _timeout = require('./timeout'); + +var _timeout2 = _interopRequireDefault(_timeout); + +var _times = require('./times'); + +var _times2 = _interopRequireDefault(_times); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _timesSeries = require('./timesSeries'); + +var _timesSeries2 = _interopRequireDefault(_timesSeries); + +var _transform = require('./transform'); + +var _transform2 = _interopRequireDefault(_transform); + +var _tryEach = require('./tryEach'); + +var _tryEach2 = _interopRequireDefault(_tryEach); + +var _unmemoize = require('./unmemoize'); + +var _unmemoize2 = _interopRequireDefault(_unmemoize); + +var _until = require('./until'); + +var _until2 = _interopRequireDefault(_until); + +var _waterfall = require('./waterfall'); + +var _waterfall2 = _interopRequireDefault(_waterfall); + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +/** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @module async + * @see AsyncFunction + */ + +/** + * A collection of `async` functions for manipulating collections, such as + * arrays and objects. + * @module Collections + */ + +/** + * A collection of `async` functions for controlling the flow through a script. + * @module ControlFlow + */ + +/** + * A collection of `async` utility functions. + * @module Utils + */ + +exports.default = { + apply: _apply2.default, + applyEach: _applyEach2.default, + applyEachSeries: _applyEachSeries2.default, + asyncify: _asyncify2.default, + auto: _auto2.default, + autoInject: _autoInject2.default, + cargo: _cargo2.default, + cargoQueue: _cargoQueue2.default, + compose: _compose2.default, + concat: _concat2.default, + concatLimit: _concatLimit2.default, + concatSeries: _concatSeries2.default, + constant: _constant2.default, + detect: _detect2.default, + detectLimit: _detectLimit2.default, + detectSeries: _detectSeries2.default, + dir: _dir2.default, + doUntil: _doUntil2.default, + doWhilst: _doWhilst2.default, + each: _each2.default, + eachLimit: _eachLimit2.default, + eachOf: _eachOf2.default, + eachOfLimit: _eachOfLimit2.default, + eachOfSeries: _eachOfSeries2.default, + eachSeries: _eachSeries2.default, + ensureAsync: _ensureAsync2.default, + every: _every2.default, + everyLimit: _everyLimit2.default, + everySeries: _everySeries2.default, + filter: _filter2.default, + filterLimit: _filterLimit2.default, + filterSeries: _filterSeries2.default, + forever: _forever2.default, + groupBy: _groupBy2.default, + groupByLimit: _groupByLimit2.default, + groupBySeries: _groupBySeries2.default, + log: _log2.default, + map: _map2.default, + mapLimit: _mapLimit2.default, + mapSeries: _mapSeries2.default, + mapValues: _mapValues2.default, + mapValuesLimit: _mapValuesLimit2.default, + mapValuesSeries: _mapValuesSeries2.default, + memoize: _memoize2.default, + nextTick: _nextTick2.default, + parallel: _parallel2.default, + parallelLimit: _parallelLimit2.default, + priorityQueue: _priorityQueue2.default, + queue: _queue2.default, + race: _race2.default, + reduce: _reduce2.default, + reduceRight: _reduceRight2.default, + reflect: _reflect2.default, + reflectAll: _reflectAll2.default, + reject: _reject2.default, + rejectLimit: _rejectLimit2.default, + rejectSeries: _rejectSeries2.default, + retry: _retry2.default, + retryable: _retryable2.default, + seq: _seq2.default, + series: _series2.default, + setImmediate: _setImmediate2.default, + some: _some2.default, + someLimit: _someLimit2.default, + someSeries: _someSeries2.default, + sortBy: _sortBy2.default, + timeout: _timeout2.default, + times: _times2.default, + timesLimit: _timesLimit2.default, + timesSeries: _timesSeries2.default, + transform: _transform2.default, + tryEach: _tryEach2.default, + unmemoize: _unmemoize2.default, + until: _until2.default, + waterfall: _waterfall2.default, + whilst: _whilst2.default, + + // aliases + all: _every2.default, + allLimit: _everyLimit2.default, + allSeries: _everySeries2.default, + any: _some2.default, + anyLimit: _someLimit2.default, + anySeries: _someSeries2.default, + find: _detect2.default, + findLimit: _detectLimit2.default, + findSeries: _detectSeries2.default, + flatMap: _concat2.default, + flatMapLimit: _concatLimit2.default, + flatMapSeries: _concatSeries2.default, + forEach: _each2.default, + forEachSeries: _eachSeries2.default, + forEachLimit: _eachLimit2.default, + forEachOf: _eachOf2.default, + forEachOfSeries: _eachOfSeries2.default, + forEachOfLimit: _eachOfLimit2.default, + inject: _reduce2.default, + foldl: _reduce2.default, + foldr: _reduceRight2.default, + select: _filter2.default, + selectLimit: _filterLimit2.default, + selectSeries: _filterSeries2.default, + wrapSync: _asyncify2.default, + during: _whilst2.default, + doDuring: _doWhilst2.default +}; +exports.apply = _apply2.default; +exports.applyEach = _applyEach2.default; +exports.applyEachSeries = _applyEachSeries2.default; +exports.asyncify = _asyncify2.default; +exports.auto = _auto2.default; +exports.autoInject = _autoInject2.default; +exports.cargo = _cargo2.default; +exports.cargoQueue = _cargoQueue2.default; +exports.compose = _compose2.default; +exports.concat = _concat2.default; +exports.concatLimit = _concatLimit2.default; +exports.concatSeries = _concatSeries2.default; +exports.constant = _constant2.default; +exports.detect = _detect2.default; +exports.detectLimit = _detectLimit2.default; +exports.detectSeries = _detectSeries2.default; +exports.dir = _dir2.default; +exports.doUntil = _doUntil2.default; +exports.doWhilst = _doWhilst2.default; +exports.each = _each2.default; +exports.eachLimit = _eachLimit2.default; +exports.eachOf = _eachOf2.default; +exports.eachOfLimit = _eachOfLimit2.default; +exports.eachOfSeries = _eachOfSeries2.default; +exports.eachSeries = _eachSeries2.default; +exports.ensureAsync = _ensureAsync2.default; +exports.every = _every2.default; +exports.everyLimit = _everyLimit2.default; +exports.everySeries = _everySeries2.default; +exports.filter = _filter2.default; +exports.filterLimit = _filterLimit2.default; +exports.filterSeries = _filterSeries2.default; +exports.forever = _forever2.default; +exports.groupBy = _groupBy2.default; +exports.groupByLimit = _groupByLimit2.default; +exports.groupBySeries = _groupBySeries2.default; +exports.log = _log2.default; +exports.map = _map2.default; +exports.mapLimit = _mapLimit2.default; +exports.mapSeries = _mapSeries2.default; +exports.mapValues = _mapValues2.default; +exports.mapValuesLimit = _mapValuesLimit2.default; +exports.mapValuesSeries = _mapValuesSeries2.default; +exports.memoize = _memoize2.default; +exports.nextTick = _nextTick2.default; +exports.parallel = _parallel2.default; +exports.parallelLimit = _parallelLimit2.default; +exports.priorityQueue = _priorityQueue2.default; +exports.queue = _queue2.default; +exports.race = _race2.default; +exports.reduce = _reduce2.default; +exports.reduceRight = _reduceRight2.default; +exports.reflect = _reflect2.default; +exports.reflectAll = _reflectAll2.default; +exports.reject = _reject2.default; +exports.rejectLimit = _rejectLimit2.default; +exports.rejectSeries = _rejectSeries2.default; +exports.retry = _retry2.default; +exports.retryable = _retryable2.default; +exports.seq = _seq2.default; +exports.series = _series2.default; +exports.setImmediate = _setImmediate2.default; +exports.some = _some2.default; +exports.someLimit = _someLimit2.default; +exports.someSeries = _someSeries2.default; +exports.sortBy = _sortBy2.default; +exports.timeout = _timeout2.default; +exports.times = _times2.default; +exports.timesLimit = _timesLimit2.default; +exports.timesSeries = _timesSeries2.default; +exports.transform = _transform2.default; +exports.tryEach = _tryEach2.default; +exports.unmemoize = _unmemoize2.default; +exports.until = _until2.default; +exports.waterfall = _waterfall2.default; +exports.whilst = _whilst2.default; +exports.all = _every2.default; +exports.allLimit = _everyLimit2.default; +exports.allSeries = _everySeries2.default; +exports.any = _some2.default; +exports.anyLimit = _someLimit2.default; +exports.anySeries = _someSeries2.default; +exports.find = _detect2.default; +exports.findLimit = _detectLimit2.default; +exports.findSeries = _detectSeries2.default; +exports.flatMap = _concat2.default; +exports.flatMapLimit = _concatLimit2.default; +exports.flatMapSeries = _concatSeries2.default; +exports.forEach = _each2.default; +exports.forEachSeries = _eachSeries2.default; +exports.forEachLimit = _eachLimit2.default; +exports.forEachOf = _eachOf2.default; +exports.forEachOfSeries = _eachOfSeries2.default; +exports.forEachOfLimit = _eachOfLimit2.default; +exports.inject = _reduce2.default; +exports.foldl = _reduce2.default; +exports.foldr = _reduceRight2.default; +exports.select = _filter2.default; +exports.selectLimit = _filterLimit2.default; +exports.selectSeries = _filterSeries2.default; +exports.wrapSync = _asyncify2.default; +exports.during = _whilst2.default; +exports.doDuring = _doWhilst2.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/inject.js b/nodejs/node_modules/async/inject.js new file mode 100644 index 00000000..8a69548a --- /dev/null +++ b/nodejs/node_modules/async/inject.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/DoublyLinkedList.js b/nodejs/node_modules/async/internal/DoublyLinkedList.js new file mode 100644 index 00000000..419ce44b --- /dev/null +++ b/nodejs/node_modules/async/internal/DoublyLinkedList.js @@ -0,0 +1,92 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty() { + while (this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove(testFn) { + var curr = this.head; + while (curr) { + var { next } = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +exports.default = DLL; +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/Heap.js b/nodejs/node_modules/async/internal/Heap.js new file mode 100644 index 00000000..7867c928 --- /dev/null +++ b/nodejs/node_modules/async/internal/Heap.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty() { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p = parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l = leftChi(index)) < this.heap.length) { + if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) { + l = l + 1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length - 1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove(testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length - 1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +exports.default = Heap; +function leftChi(i) { + return (i << 1) + 1; +} + +function parent(i) { + return (i + 1 >> 1) - 1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } else { + return x.pushCount < y.pushCount; + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/applyEach.js b/nodejs/node_modules/async/internal/applyEach.js new file mode 100644 index 00000000..54449126 --- /dev/null +++ b/nodejs/node_modules/async/internal/applyEach.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = (0, _awaitify2.default)(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + (0, _wrapAsync2.default)(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +}; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/asyncEachOfLimit.js b/nodejs/node_modules/async/internal/asyncEachOfLimit.js new file mode 100644 index 00000000..34dd82bf --- /dev/null +++ b/nodejs/node_modules/async/internal/asyncEachOfLimit.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncEachOfLimit; + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return; + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({ value, done: iterDone }) => { + //console.log('got value', value) + if (canceled || done) return; + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return; + if (err) return handleError(err); + + if (err === false) { + done = true; + canceled = true; + return; + } + + if (result === _breakLoop2.default || done && running <= 0) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/awaitify.js b/nodejs/node_modules/async/internal/awaitify.js new file mode 100644 index 00000000..bb7a609a --- /dev/null +++ b/nodejs/node_modules/async/internal/awaitify.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = awaitify; +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify(asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined'); + function awaitable(...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args); + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err); + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }); + } + + return awaitable; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/breakLoop.js b/nodejs/node_modules/async/internal/breakLoop.js new file mode 100644 index 00000000..87413dd0 --- /dev/null +++ b/nodejs/node_modules/async/internal/breakLoop.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; +exports.default = breakLoop; +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/consoleFunc.js b/nodejs/node_modules/async/internal/consoleFunc.js new file mode 100644 index 00000000..748d54b7 --- /dev/null +++ b/nodejs/node_modules/async/internal/consoleFunc.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = consoleFunc; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function consoleFunc(name) { + return (fn, ...args) => (0, _wrapAsync2.default)(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { + /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/createTester.js b/nodejs/node_modules/async/internal/createTester.js new file mode 100644 index 00000000..cafdf62e --- /dev/null +++ b/nodejs/node_modules/async/internal/createTester.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _createTester; + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = (0, _wrapAsync2.default)(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, _breakLoop2.default); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/eachOfLimit.js b/nodejs/node_modules/async/internal/eachOfLimit.js new file mode 100644 index 00000000..ceed60f4 --- /dev/null +++ b/nodejs/node_modules/async/internal/eachOfLimit.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _iterator = require('./iterator.js'); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _onlyOnce = require('./onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./wrapAsync.js'); + +var _asyncEachOfLimit = require('./asyncEachOfLimit.js'); + +var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = limit => { + return (obj, iteratee, callback) => { + callback = (0, _once2.default)(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1'); + } + if (!obj) { + return callback(null); + } + if ((0, _wrapAsync.isAsyncGenerator)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); + } + if ((0, _wrapAsync.isAsyncIterable)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; + if (err) { + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); + } + } + + function replenish() { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/filter.js b/nodejs/node_modules/async/internal/filter.js new file mode 100644 index 00000000..065c211e --- /dev/null +++ b/nodejs/node_modules/async/internal/filter.js @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _filter; + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({ index, value: x }); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results.sort((a, b) => a.index - b.index).map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/getIterator.js b/nodejs/node_modules/async/internal/getIterator.js new file mode 100644 index 00000000..f518fce8 --- /dev/null +++ b/nodejs/node_modules/async/internal/getIterator.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/initialParams.js b/nodejs/node_modules/async/internal/initialParams.js new file mode 100644 index 00000000..04c0eff7 --- /dev/null +++ b/nodejs/node_modules/async/internal/initialParams.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn) { + return function (...args /*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/isArrayLike.js b/nodejs/node_modules/async/internal/isArrayLike.js new file mode 100644 index 00000000..a4c4c8a5 --- /dev/null +++ b/nodejs/node_modules/async/internal/isArrayLike.js @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isArrayLike; +function isArrayLike(value) { + return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/iterator.js b/nodejs/node_modules/async/internal/iterator.js new file mode 100644 index 00000000..5778b1e8 --- /dev/null +++ b/nodejs/node_modules/async/internal/iterator.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = createIterator; + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _getIterator = require('./getIterator.js'); + +var _getIterator2 = _interopRequireDefault(_getIterator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? { value: obj[key], key } : null; + }; +} + +function createIterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + + var iterator = (0, _getIterator2.default)(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/map.js b/nodejs/node_modules/async/internal/map.js new file mode 100644 index 00000000..acab1e72 --- /dev/null +++ b/nodejs/node_modules/async/internal/map.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _asyncMap; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/once.js b/nodejs/node_modules/async/internal/once.js new file mode 100644 index 00000000..a8b57926 --- /dev/null +++ b/nodejs/node_modules/async/internal/once.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = once; +function once(fn) { + function wrapper(...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/onlyOnce.js b/nodejs/node_modules/async/internal/onlyOnce.js new file mode 100644 index 00000000..c95a92d4 --- /dev/null +++ b/nodejs/node_modules/async/internal/onlyOnce.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onlyOnce; +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/parallel.js b/nodejs/node_modules/async/internal/parallel.js new file mode 100644 index 00000000..57fbd0d0 --- /dev/null +++ b/nodejs/node_modules/async/internal/parallel.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/promiseCallback.js b/nodejs/node_modules/async/internal/promiseCallback.js new file mode 100644 index 00000000..17a83016 --- /dev/null +++ b/nodejs/node_modules/async/internal/promiseCallback.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback() { + let resolve, reject; + function callback(err, ...args) { + if (err) return reject(err); + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, reject = rej; + }); + + return callback; +} + +exports.promiseCallback = promiseCallback; +exports.PROMISE_SYMBOL = PROMISE_SYMBOL; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/queue.js b/nodejs/node_modules/async/internal/queue.js new file mode 100644 index 00000000..7414e03b --- /dev/null +++ b/nodejs/node_modules/async/internal/queue.js @@ -0,0 +1,294 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = queue; + +var _onlyOnce = require('./onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _setImmediate = require('./setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _DoublyLinkedList = require('./DoublyLinkedList.js'); + +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = (0, _wrapAsync2.default)(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on(event, handler) { + events[event].push(handler); + } + + function once(event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off(event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []); + if (!handler) return events[event] = []; + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger(event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback(err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res(); + if (args.length <= 1) return res(args[0]); + res(args); + } + + var item = q._createTaskItem(data, rejectOnError ? promiseCallback : callback || promiseCallback); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + (0, _setImmediate2.default)(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= q.concurrency - q.buffer) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + (0, _setImmediate2.default)(() => trigger('drain')); + return true; + } + return false; + } + + const eventMethod = name => handler => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err); + resolve(data); + }); + }); + } + off(name); + on(name, handler); + }; + + var isProcessing = false; + var q = { + _tasks: new _DoublyLinkedList2.default(), + _createTaskItem(data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator]() { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, false, callback)); + } + return _insert(data, false, false, callback); + }, + pushAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, true, callback)); + } + return _insert(data, false, true, callback); + }, + kill() { + off(); + q._tasks.empty(); + }, + unshift(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, false, callback)); + } + return _insert(data, true, false, callback); + }, + unshiftAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, true, callback)); + } + return _insert(data, true, true, callback); + }, + remove(testFn) { + q._tasks.remove(testFn); + }, + process() { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while (!q.paused && numRunning < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = (0, _onlyOnce2.default)(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length() { + return q._tasks.length; + }, + running() { + return numRunning; + }, + workersList() { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause() { + q.paused = true; + }, + resume() { + if (q.paused === false) { + return; + } + q.paused = false; + (0, _setImmediate2.default)(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + } + }); + return q; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/range.js b/nodejs/node_modules/async/internal/range.js new file mode 100644 index 00000000..cc7b3a9c --- /dev/null +++ b/nodejs/node_modules/async/internal/range.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = range; +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/reject.js b/nodejs/node_modules/async/internal/reject.js new file mode 100644 index 00000000..9d9bc80b --- /dev/null +++ b/nodejs/node_modules/async/internal/reject.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reject; + +var _filter = require('./filter.js'); + +var _filter2 = _interopRequireDefault(_filter); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reject(eachfn, arr, _iteratee, callback) { + const iteratee = (0, _wrapAsync2.default)(_iteratee); + return (0, _filter2.default)(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/setImmediate.js b/nodejs/node_modules/async/internal/setImmediate.js new file mode 100644 index 00000000..513efd13 --- /dev/null +++ b/nodejs/node_modules/async/internal/setImmediate.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fallback = fallback; +exports.wrap = wrap; +/* istanbul ignore file */ + +var hasQueueMicrotask = exports.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer; + +if (hasQueueMicrotask) { + _defer = queueMicrotask; +} else if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +exports.default = wrap(_defer); \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/withoutIndex.js b/nodejs/node_modules/async/internal/withoutIndex.js new file mode 100644 index 00000000..fa91c2d5 --- /dev/null +++ b/nodejs/node_modules/async/internal/withoutIndex.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _withoutIndex; +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/internal/wrapAsync.js b/nodejs/node_modules/async/internal/wrapAsync.js new file mode 100644 index 00000000..ad4d6198 --- /dev/null +++ b/nodejs/node_modules/async/internal/wrapAsync.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined; + +var _asyncify = require('../asyncify.js'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function'); + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; +} + +exports.default = wrapAsync; +exports.isAsync = isAsync; +exports.isAsyncGenerator = isAsyncGenerator; +exports.isAsyncIterable = isAsyncIterable; \ No newline at end of file diff --git a/nodejs/node_modules/async/log.js b/nodejs/node_modules/async/log.js new file mode 100644 index 00000000..332b9da7 --- /dev/null +++ b/nodejs/node_modules/async/log.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc.js'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +exports.default = (0, _consoleFunc2.default)('log'); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/map.js b/nodejs/node_modules/async/map.js new file mode 100644 index 00000000..c4b7a5ac --- /dev/null +++ b/nodejs/node_modules/async/map.js @@ -0,0 +1,142 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function map(coll, iteratee, callback) { + return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(map, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/mapLimit.js b/nodejs/node_modules/async/mapLimit.js new file mode 100644 index 00000000..6ad35724 --- /dev/null +++ b/nodejs/node_modules/async/mapLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit(coll, limit, iteratee, callback) { + return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/mapSeries.js b/nodejs/node_modules/async/mapSeries.js new file mode 100644 index 00000000..8dfdd8aa --- /dev/null +++ b/nodejs/node_modules/async/mapSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries(coll, iteratee, callback) { + return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/mapValues.js b/nodejs/node_modules/async/mapValues.js new file mode 100644 index 00000000..3d0470e3 --- /dev/null +++ b/nodejs/node_modules/async/mapValues.js @@ -0,0 +1,152 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValues; + +var _mapValuesLimit = require('./mapValuesLimit.js'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function mapValues(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/mapValuesLimit.js b/nodejs/node_modules/async/mapValuesLimit.js new file mode 100644 index 00000000..f59e36f2 --- /dev/null +++ b/nodejs/node_modules/async/mapValuesLimit.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = (0, _once2.default)(callback); + var newObj = {}; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfLimit2.default)(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +exports.default = (0, _awaitify2.default)(mapValuesLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/mapValuesSeries.js b/nodejs/node_modules/async/mapValuesSeries.js new file mode 100644 index 00000000..5f05bf21 --- /dev/null +++ b/nodejs/node_modules/async/mapValuesSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValuesSeries; + +var _mapValuesLimit = require('./mapValuesLimit.js'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/memoize.js b/nodejs/node_modules/async/memoize.js new file mode 100644 index 00000000..6535d4e4 --- /dev/null +++ b/nodejs/node_modules/async/memoize.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize; + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = (0, _wrapAsync2.default)(fn); + var memoized = (0, _initialParams2.default)((args, callback) => { + var key = hasher(...args); + if (key in memo) { + (0, _setImmediate2.default)(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/nextTick.js b/nodejs/node_modules/async/nextTick.js new file mode 100644 index 00000000..8ebfda9e --- /dev/null +++ b/nodejs/node_modules/async/nextTick.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate.js'); + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; /* istanbul ignore file */ + + +if (_setImmediate.hasNextTick) { + _defer = process.nextTick; +} else if (_setImmediate.hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = _setImmediate.fallback; +} + +exports.default = (0, _setImmediate.wrap)(_defer); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/package.json b/nodejs/node_modules/async/package.json new file mode 100644 index 00000000..af989051 --- /dev/null +++ b/nodejs/node_modules/async/package.json @@ -0,0 +1,75 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "3.2.5", + "main": "dist/async.js", + "author": "Caolan McMahon", + "homepage": "https://caolan.github.io/async/", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "keywords": [ + "async", + "callback", + "module", + "utility" + ], + "devDependencies": { + "@babel/eslint-parser": "^7.16.5", + "@babel/core": "7.23.2", + "babel-minify": "^0.5.0", + "babel-plugin-add-module-exports": "^1.0.4", + "babel-plugin-istanbul": "^6.1.1", + "babel-plugin-syntax-async-generators": "^6.13.0", + "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", + "babel-preset-es2015": "^6.3.13", + "babel-preset-es2017": "^6.22.0", + "babel-register": "^6.26.0", + "babelify": "^10.0.0", + "benchmark": "^2.1.1", + "bluebird": "^3.4.6", + "browserify": "^17.0.0", + "chai": "^4.2.0", + "cheerio": "^0.22.0", + "es6-promise": "^4.2.8", + "eslint": "^8.6.0", + "eslint-plugin-prefer-arrow": "^1.2.3", + "fs-extra": "^11.1.1", + "jsdoc": "^3.6.2", + "karma": "^6.3.12", + "karma-browserify": "^8.1.0", + "karma-firefox-launcher": "^2.1.2", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.0", + "karma-safari-launcher": "^1.0.0", + "mocha": "^6.1.4", + "native-promise-only": "^0.8.0-a", + "nyc": "^15.1.0", + "rollup": "^4.2.0", + "rollup-plugin-node-resolve": "^5.2.0", + "rollup-plugin-npm": "^2.0.0", + "rsvp": "^4.8.5", + "semver": "^7.3.5", + "yargs": "^17.3.1" + }, + "scripts": { + "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", + "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", + "lint": "eslint --fix .", + "mocha-browser-test": "karma start", + "mocha-node-test": "mocha", + "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", + "test": "npm run lint && npm run mocha-node-test" + }, + "license": "MIT", + "nyc": { + "exclude": [ + "test" + ] + }, + "module": "dist/async.mjs" +} \ No newline at end of file diff --git a/nodejs/node_modules/async/parallel.js b/nodejs/node_modules/async/parallel.js new file mode 100644 index 00000000..2c7976fe --- /dev/null +++ b/nodejs/node_modules/async/parallel.js @@ -0,0 +1,180 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallel; + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _parallel2 = require('./internal/parallel.js'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function parallel(tasks, callback) { + return (0, _parallel3.default)(_eachOf2.default, tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/parallelLimit.js b/nodejs/node_modules/async/parallelLimit.js new file mode 100644 index 00000000..43379572 --- /dev/null +++ b/nodejs/node_modules/async/parallelLimit.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallelLimit; + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _parallel = require('./internal/parallel.js'); + +var _parallel2 = _interopRequireDefault(_parallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/priorityQueue.js b/nodejs/node_modules/async/priorityQueue.js new file mode 100644 index 00000000..16c4daa0 --- /dev/null +++ b/nodejs/node_modules/async/priorityQueue.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + // Start with a normal queue + var q = (0, _queue2.default)(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new _Heap2.default(); + q._createTaskItem = ({ data, priority }, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return { data: tasks, priority }; + } + return tasks.map(data => { + return { data, priority }; + }); + } + + // Override push to accept second parameter representing priority + q.push = function (data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function (data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; +}; + +var _queue = require('./queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +var _Heap = require('./internal/Heap.js'); + +var _Heap2 = _interopRequireDefault(_Heap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/queue.js b/nodejs/node_modules/async/queue.js new file mode 100644 index 00000000..c01340dc --- /dev/null +++ b/nodejs/node_modules/async/queue.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + var _worker = (0, _wrapAsync2.default)(worker); + return (0, _queue2.default)((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +}; + +var _queue = require('./internal/queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/race.js b/nodejs/node_modules/async/race.js new file mode 100644 index 00000000..aa167be3 --- /dev/null +++ b/nodejs/node_modules/async/race.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + (0, _wrapAsync2.default)(tasks[i])(callback); + } +} + +exports.default = (0, _awaitify2.default)(race, 2); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/reduce.js b/nodejs/node_modules/async/reduce.js new file mode 100644 index 00000000..8a69548a --- /dev/null +++ b/nodejs/node_modules/async/reduce.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/reduceRight.js b/nodejs/node_modules/async/reduceRight.js new file mode 100644 index 00000000..5be1b68d --- /dev/null +++ b/nodejs/node_modules/async/reduceRight.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/reflect.js b/nodejs/node_modules/async/reflect.js new file mode 100644 index 00000000..39544956 --- /dev/null +++ b/nodejs/node_modules/async/reflect.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflect; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = (0, _wrapAsync2.default)(fn); + return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0) { + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/reflectAll.js b/nodejs/node_modules/async/reflectAll.js new file mode 100644 index 00000000..b78d598b --- /dev/null +++ b/nodejs/node_modules/async/reflectAll.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflectAll; + +var _reflect = require('./reflect.js'); + +var _reflect2 = _interopRequireDefault(_reflect); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(_reflect2.default); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = _reflect2.default.call(this, tasks[key]); + }); + } + return results; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/reject.js b/nodejs/node_modules/async/reject.js new file mode 100644 index 00000000..895949bd --- /dev/null +++ b/nodejs/node_modules/async/reject.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function reject(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(reject, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/rejectLimit.js b/nodejs/node_modules/async/rejectLimit.js new file mode 100644 index 00000000..ce10edf5 --- /dev/null +++ b/nodejs/node_modules/async/rejectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit(coll, limit, iteratee, callback) { + return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/rejectSeries.js b/nodejs/node_modules/async/rejectSeries.js new file mode 100644 index 00000000..c08e413f --- /dev/null +++ b/nodejs/node_modules/async/rejectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/retry.js b/nodejs/node_modules/async/retry.js new file mode 100644 index 00000000..a4b02356 --- /dev/null +++ b/nodejs/node_modules/async/retry.js @@ -0,0 +1,159 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retry; + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function constant(value) { + return function () { + return value; + }; +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || (0, _promiseCallback.promiseCallback)(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || (0, _promiseCallback.promiseCallback)(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = (0, _wrapAsync2.default)(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return; + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/retryable.js b/nodejs/node_modules/async/retryable.js new file mode 100644 index 00000000..68256c31 --- /dev/null +++ b/nodejs/node_modules/async/retryable.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retryable; + +var _retry = require('./retry.js'); + +var _retry2 = _interopRequireDefault(_retry); + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = opts && opts.arity || task.length; + if ((0, _wrapAsync.isAsync)(task)) { + arity += 1; + } + var _task = (0, _wrapAsync2.default)(task); + return (0, _initialParams2.default)((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = (0, _promiseCallback.promiseCallback)(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); + + return callback[_promiseCallback.PROMISE_SYMBOL]; + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/select.js b/nodejs/node_modules/async/select.js new file mode 100644 index 00000000..2c9a63de --- /dev/null +++ b/nodejs/node_modules/async/select.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/selectLimit.js b/nodejs/node_modules/async/selectLimit.js new file mode 100644 index 00000000..d3b3f50c --- /dev/null +++ b/nodejs/node_modules/async/selectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/selectSeries.js b/nodejs/node_modules/async/selectSeries.js new file mode 100644 index 00000000..019a2d0a --- /dev/null +++ b/nodejs/node_modules/async/selectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/seq.js b/nodejs/node_modules/async/seq.js new file mode 100644 index 00000000..e7881cd0 --- /dev/null +++ b/nodejs/node_modules/async/seq.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = seq; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(_wrapAsync2.default); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = (0, _promiseCallback.promiseCallback)(); + } + + (0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, (err, results) => cb(err, ...results)); + + return cb[_promiseCallback.PROMISE_SYMBOL]; + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/series.js b/nodejs/node_modules/async/series.js new file mode 100644 index 00000000..60c17ed6 --- /dev/null +++ b/nodejs/node_modules/async/series.js @@ -0,0 +1,186 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = series; + +var _parallel2 = require('./internal/parallel.js'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function series(tasks, callback) { + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/setImmediate.js b/nodejs/node_modules/async/setImmediate.js new file mode 100644 index 00000000..eea86771 --- /dev/null +++ b/nodejs/node_modules/async/setImmediate.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `setImmediate`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name setImmediate + * @static + * @memberOf module:Utils + * @method + * @see [async.nextTick]{@link module:Utils.nextTick} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +exports.default = _setImmediate2.default; +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/some.js b/nodejs/node_modules/async/some.js new file mode 100644 index 00000000..a5bd328a --- /dev/null +++ b/nodejs/node_modules/async/some.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/someLimit.js b/nodejs/node_modules/async/someLimit.js new file mode 100644 index 00000000..3a8096fd --- /dev/null +++ b/nodejs/node_modules/async/someLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/someSeries.js b/nodejs/node_modules/async/someSeries.js new file mode 100644 index 00000000..51aad19b --- /dev/null +++ b/nodejs/node_modules/async/someSeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/sortBy.js b/nodejs/node_modules/async/sortBy.js new file mode 100644 index 00000000..0988b612 --- /dev/null +++ b/nodejs/node_modules/async/sortBy.js @@ -0,0 +1,190 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map = require('./map.js'); + +var _map2 = _interopRequireDefault(_map); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function sortBy(coll, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _map2.default)(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, { value: x, criteria }); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +exports.default = (0, _awaitify2.default)(sortBy, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/timeout.js b/nodejs/node_modules/async/timeout.js new file mode 100644 index 00000000..46bb233a --- /dev/null +++ b/nodejs/node_modules/async/timeout.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timeout; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = (0, _wrapAsync2.default)(asyncFn); + + return (0, _initialParams2.default)((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/times.js b/nodejs/node_modules/async/times.js new file mode 100644 index 00000000..ca7df517 --- /dev/null +++ b/nodejs/node_modules/async/times.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = times; + +var _timesLimit = require('./timesLimit.js'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/timesLimit.js b/nodejs/node_modules/async/timesLimit.js new file mode 100644 index 00000000..f76de250 --- /dev/null +++ b/nodejs/node_modules/async/timesLimit.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesLimit; + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _range = require('./internal/range.js'); + +var _range2 = _interopRequireDefault(_range); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/timesSeries.js b/nodejs/node_modules/async/timesSeries.js new file mode 100644 index 00000000..776b4f3a --- /dev/null +++ b/nodejs/node_modules/async/timesSeries.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesSeries; + +var _timesLimit = require('./timesLimit.js'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/transform.js b/nodejs/node_modules/async/transform.js new file mode 100644 index 00000000..75dadea8 --- /dev/null +++ b/nodejs/node_modules/async/transform.js @@ -0,0 +1,173 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = transform; + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function transform(coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + (0, _eachOf2.default)(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/tryEach.js b/nodejs/node_modules/async/tryEach.js new file mode 100644 index 00000000..7e63f9d5 --- /dev/null +++ b/nodejs/node_modules/async/tryEach.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachSeries = require('./eachSeries.js'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return (0, _eachSeries2.default)(tasks, (task, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +exports.default = (0, _awaitify2.default)(tryEach); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/unmemoize.js b/nodejs/node_modules/async/unmemoize.js new file mode 100644 index 00000000..badd7aec --- /dev/null +++ b/nodejs/node_modules/async/unmemoize.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = unmemoize; +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/until.js b/nodejs/node_modules/async/until.js new file mode 100644 index 00000000..4b69b972 --- /dev/null +++ b/nodejs/node_modules/async/until.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = until; + +var _whilst = require('./whilst.js'); + +var _whilst2 = _interopRequireDefault(_whilst); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/waterfall.js b/nodejs/node_modules/async/waterfall.js new file mode 100644 index 00000000..c3242f79 --- /dev/null +++ b/nodejs/node_modules/async/waterfall.js @@ -0,0 +1,105 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); + task(...args, (0, _onlyOnce2.default)(next)); + } + + function next(err, ...args) { + if (err === false) return; + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +exports.default = (0, _awaitify2.default)(waterfall); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/whilst.js b/nodejs/node_modules/async/whilst.js new file mode 100644 index 00000000..4165543f --- /dev/null +++ b/nodejs/node_modules/async/whilst.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/async/wrapSync.js b/nodejs/node_modules/async/wrapSync.js new file mode 100644 index 00000000..ddc3f02f --- /dev/null +++ b/nodejs/node_modules/async/wrapSync.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/nodejs/node_modules/base64-js/LICENSE b/nodejs/node_modules/base64-js/LICENSE new file mode 100644 index 00000000..6d52b8ac --- /dev/null +++ b/nodejs/node_modules/base64-js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/base64-js/README.md b/nodejs/node_modules/base64-js/README.md new file mode 100644 index 00000000..b42a48f4 --- /dev/null +++ b/nodejs/node_modules/base64-js/README.md @@ -0,0 +1,34 @@ +base64-js +========= + +`base64-js` does basic base64 encoding/decoding in pure JS. + +[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) + +Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. + +Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. + +## install + +With [npm](https://npmjs.org) do: + +`npm install base64-js` and `var base64js = require('base64-js')` + +For use in web browsers do: + +`` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/nodejs/node_modules/base64-js/base64js.min.js b/nodejs/node_modules/base64-js/base64js.min.js new file mode 100644 index 00000000..908ac83f --- /dev/null +++ b/nodejs/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/nodejs/node_modules/base64-js/package.json b/nodejs/node_modules/base64-js/package.json new file mode 100644 index 00000000..c3972e39 --- /dev/null +++ b/nodejs/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/nodejs/node_modules/bson/LICENSE.md b/nodejs/node_modules/bson/LICENSE.md new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/nodejs/node_modules/bson/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/nodejs/node_modules/bson/README.md b/nodejs/node_modules/bson/README.md new file mode 100644 index 00000000..7c9c8c71 --- /dev/null +++ b/nodejs/node_modules/bson/README.md @@ -0,0 +1,253 @@ +# BSON parser + +BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. +You can learn more about it in [the specification](http://bsonspec.org). + +### Table of Contents + +- [Usage](#usage) +- [Bugs/Feature Requests](#bugs--feature-requests) +- [Installation](#installation) +- [Documentation](#documentation) +- [FAQ](#faq) + +## Bugs / Feature Requests + +Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA: + +1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org) +2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE) +3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it. + +Bug reports in JIRA for the NODE driver project are **public**. + +## Usage + +To build a new version perform the following operations: + +``` +npm install +npm run build +``` + +### Node.js or Bundling Usage + +When using a bundler or Node.js you can import bson using the package name: + +```js +import { BSON, EJSON, ObjectId } from 'bson'; +// or: +// const { BSON, EJSON, ObjectId } = require('bson'); + +const bytes = BSON.serialize({ _id: new ObjectId() }); +console.log(bytes); +const doc = BSON.deserialize(bytes); +console.log(EJSON.stringify(doc)); +// {"_id":{"$oid":"..."}} +``` + +### Browser Usage + +If you are working directly in the browser without a bundler please use the `.mjs` bundle like so: + +```html + +``` + +## Installation + +```sh +npm install bson +``` + +### MongoDB Node.js Driver Version Compatibility + +Only the following version combinations with the [MongoDB Node.js Driver](https://github.com/mongodb/node-mongodb-native) are considered stable. + +| | `bson@1.x` | `bson@4.x` | `bson@5.x` | `bson@6.x` | +| ------------- | ---------- | ---------- | ---------- | ---------- | +| `mongodb@6.x` | N/A | N/A | N/A | ✓ | +| `mongodb@5.x` | N/A | N/A | ✓ | N/A | +| `mongodb@4.x` | N/A | ✓ | N/A | N/A | +| `mongodb@3.x` | ✓ | N/A | N/A | N/A | + +## Documentation + +### BSON + +[API documentation](https://mongodb.github.io/node-mongodb-native/Next/modules/BSON.html) + + + +### EJSON + +- [EJSON](#EJSON) + + - [.parse(text, [options])](#EJSON.parse) + + - [.stringify(value, [replacer], [space], [options])](#EJSON.stringify) + + - [.serialize(bson, [options])](#EJSON.serialize) + + - [.deserialize(ejson, [options])](#EJSON.deserialize) + + + +#### _EJSON_.parse(text, [options]) + +| Param | Type | Default | Description | +| ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- | +| text | string | | | +| [options] | object | | Optional settings | +| [options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) | + +Parse an Extended JSON string, constructing the JavaScript value or object described by that +string. + +**Example** + +```js +const { EJSON } = require('bson'); +const text = '{ "int32": { "$numberInt": "10" } }'; + +// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } +console.log(EJSON.parse(text, { relaxed: false })); + +// prints { int32: 10 } +console.log(EJSON.parse(text)); +``` + + + +#### _EJSON_.stringify(value, [replacer], [space], [options]) + +| Param | Type | Default | Description | +| ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| value | object | | The value to convert to extended JSON | +| [replacer] | function \| array | | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | +| [space] | string \| number | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | +| [options] | object | | Optional settings | +| [options.relaxed] | boolean | true | Enabled Extended JSON's `relaxed` mode | +| [options.legacy] | boolean | true | Output in Extended JSON v1 | + +Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer +function is specified or optionally including only the specified properties if a replacer array +is specified. + +**Example** + +```js +const { EJSON } = require('bson'); +const Int32 = require('mongodb').Int32; +const doc = { int32: new Int32(10) }; + +// prints '{"int32":{"$numberInt":"10"}}' +console.log(EJSON.stringify(doc, { relaxed: false })); + +// prints '{"int32":10}' +console.log(EJSON.stringify(doc)); +``` + + + +#### _EJSON_.serialize(bson, [options]) + +| Param | Type | Description | +| --------- | ------------------- | ---------------------------------------------------- | +| bson | object | The object to serialize | +| [options] | object | Optional settings passed to the `stringify` function | + +Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + + + +#### _EJSON_.deserialize(ejson, [options]) + +| Param | Type | Description | +| --------- | ------------------- | -------------------------------------------- | +| ejson | object | The Extended JSON object to deserialize | +| [options] | object | Optional settings passed to the parse method | + +Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + +## Error Handling + +It is our recommendation to use `BSONError.isBSONError()` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. We guarantee `BSONError.isBSONError()` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors. + +Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. +This means `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws. + +Hypothetical example: A collection in our Db has an issue with UTF-8 data: + +```ts +let documentCount = 0; +const cursor = collection.find({}, { utf8Validation: true }); +try { + for await (const doc of cursor) documentCount += 1; +} catch (error) { + if (BSONError.isBSONError(error)) { + console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`); + return documentCount; + } + throw error; +} +``` + +## React Native + +BSON vendors the required polyfills for `TextEncoder`, `TextDecoder`, `atob`, `btoa` imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill, `crypto.getRandomValues` is recommended and can be installed with the following command: + +```sh +npm install --save react-native-get-random-values +``` + +The following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`. + +```typescript +// Required Polyfills For ReactNative +import 'react-native-get-random-values'; +``` + +Finally, import the `BSON` library like so: + +```typescript +import { BSON, EJSON } from 'bson'; +``` + +This will cause React Native to import the `node_modules/bson/lib/bson.rn.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).) + +### Technical Note about React Native module import + +The `"exports"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/). + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +const BSON = require('bson'); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(BSON.deserialize(BSON.serialize(obj))); +``` diff --git a/nodejs/node_modules/bson/bson.d.ts b/nodejs/node_modules/bson/bson.d.ts new file mode 100644 index 00000000..e41feef9 --- /dev/null +++ b/nodejs/node_modules/bson/bson.d.ts @@ -0,0 +1,1390 @@ +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +export declare class Binary extends BSONValue { + get _bsontype(): 'Binary'; + /* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */ + /** Initial buffer default size */ + static readonly BUFFER_SIZE = 256; + /** Default BSON type */ + static readonly SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + static readonly SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + static readonly SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + static readonly SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + static readonly SUBTYPE_UUID = 4; + /** MD5 BSON type */ + static readonly SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + static readonly SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + static readonly SUBTYPE_COLUMN = 7; + /** Sensitive BSON type */ + static readonly SUBTYPE_SENSITIVE = 8; + /** User BSON type */ + static readonly SUBTYPE_USER_DEFINED = 128; + buffer: Uint8Array; + sub_type: number; + position: number; + /** + * Create a new Binary instance. + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + constructor(buffer?: BinarySequence, subType?: number); + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + put(byteValue: string | number | Uint8Array | number[]): void; + /** + * Writes a buffer to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + write(sequence: BinarySequence, offset: number): void; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + read(position: number, length: number): BinarySequence; + /** returns a view of the binary value as a Uint8Array */ + value(): Uint8Array; + /** the length of the binary sequence */ + length(): number; + toJSON(): string; + toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string; + /* Excluded from this release type: toExtendedJSON */ + toUUID(): UUID; + /** Creates an Binary instance from a hex digit string */ + static createFromHexString(hex: string, subType?: number): Binary; + /** Creates an Binary instance from a base64 string */ + static createFromBase64(base64: string, subType?: number): Binary; + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface BinaryExtended { + $binary: { + subType: string; + base64: string; + }; +} + +/** @public */ +export declare interface BinaryExtendedLegacy { + $type: string; + $binary: string; +} + +/** @public */ +export declare type BinarySequence = Uint8Array | number[]; + +declare namespace BSON { + export { + setInternalBufferSize, + serialize, + serializeWithBufferAndIndex, + deserialize, + calculateObjectSize, + deserializeStream, + UUIDExtended, + BinaryExtended, + BinaryExtendedLegacy, + BinarySequence, + CodeExtended, + DBRefLike, + Decimal128Extended, + DoubleExtended, + EJSONOptions, + Int32Extended, + LongExtended, + MaxKeyExtended, + MinKeyExtended, + ObjectIdExtended, + ObjectIdLike, + BSONRegExpExtended, + BSONRegExpExtendedLegacy, + BSONSymbolExtended, + LongWithoutOverrides, + TimestampExtended, + TimestampOverrides, + LongWithoutOverridesClass, + SerializeOptions, + DeserializeOptions, + Code, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128, + BSONValue, + BSONError, + BSONVersionError, + BSONRuntimeError, + BSONType, + EJSON, + onDemand, + Document, + CalculateObjectSizeOptions + } +} +export { BSON } + +/** + * @public + * @experimental + */ +declare type BSONElement = [ +type: number, +nameOffset: number, +nameLength: number, +offset: number, +length: number +]; + +/** + * @public + * @category Error + * + * `BSONError` objects are thrown when BSON encounters an error. + * + * This is the parent class for all the other errors thrown by this library. + */ +export declare class BSONError extends Error { + /* Excluded from this release type: bsonError */ + get name(): string; + constructor(message: string, options?: { + cause?: unknown; + }); + /** + * @public + * + * All errors thrown from the BSON library inherit from `BSONError`. + * This method can assist with determining if an error originates from the BSON library + * even if it does not pass an `instanceof` check against this class' constructor. + * + * @param value - any javascript value that needs type checking + */ + static isBSONError(value: unknown): value is BSONError; +} + +/** + * @public + * @category Error + * + * @experimental + * + * An error generated when BSON bytes are invalid. + * Reports the offset the parser was able to reach before encountering the error. + */ +declare class BSONOffsetError extends BSONError { + get name(): 'BSONOffsetError'; + offset: number; + constructor(message: string, offset: number); +} + +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +export declare class BSONRegExp extends BSONValue { + get _bsontype(): 'BSONRegExp'; + pattern: string; + options: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string); + static parseOptions(options?: string): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} + +/** @public */ +export declare interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} + +/** + * @public + * @category Error + * + * An error generated when BSON functions encounter an unexpected input + * or reaches an unexpected/invalid internal state + * + */ +export declare class BSONRuntimeError extends BSONError { + get name(): 'BSONRuntimeError'; + constructor(message: string); +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export declare class BSONSymbol extends BSONValue { + get _bsontype(): 'BSONSymbol'; + value: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string); + /** Access the wrapped string value. */ + valueOf(): string; + toString(): string; + toJSON(): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface BSONSymbolExtended { + $symbol: string; +} + +/** @public */ +export declare const BSONType: Readonly<{ + readonly double: 1; + readonly string: 2; + readonly object: 3; + readonly array: 4; + readonly binData: 5; + readonly undefined: 6; + readonly objectId: 7; + readonly bool: 8; + readonly date: 9; + readonly null: 10; + readonly regex: 11; + readonly dbPointer: 12; + readonly javascript: 13; + readonly symbol: 14; + readonly javascriptWithScope: 15; + readonly int: 16; + readonly timestamp: 17; + readonly long: 18; + readonly decimal: 19; + readonly minKey: -1; + readonly maxKey: 127; +}>; + +/** @public */ +export declare type BSONType = (typeof BSONType)[keyof typeof BSONType]; + +/** @public */ +export declare abstract class BSONValue { + /** @public */ + abstract get _bsontype(): string; + /** + * @public + * Prints a human-readable string of BSON value information + * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify + */ + abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; + /* Excluded from this release type: toExtendedJSON */ +} + +/** + * @public + * @category Error + */ +export declare class BSONVersionError extends BSONError { + get name(): 'BSONVersionError'; + constructor(); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +export declare function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number; + +/** @public */ +export declare type CalculateObjectSizeOptions = Pick; + +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +export declare class Code extends BSONValue { + get _bsontype(): 'Code'; + code: string; + scope: Document | null; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document | null); + toJSON(): { + code: string; + scope?: Document; + }; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface CodeExtended { + $code: string; + $scope?: Document; +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export declare class DBRef extends BSONValue { + get _bsontype(): 'DBRef'; + collection: string; + oid: ObjectId; + db?: string; + fields: Document; + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + constructor(collection: string, oid: ObjectId, db?: string, fields?: Document); + /* Excluded from this release type: namespace */ + /* Excluded from this release type: namespace */ + toJSON(): DBRefLike & Document; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** + * A class representation of the BSON Decimal128 type. + * @public + * @category BSONType + */ +export declare class Decimal128 extends BSONValue { + get _bsontype(): 'Decimal128'; + readonly bytes: Uint8Array; + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Uint8Array | string); + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + static fromString(representation: string): Decimal128; + /** + * Create a Decimal128 instance from a string representation, allowing for rounding to 34 + * significant digits + * + * @example Example of a number that will be rounded + * ```ts + * > let d = Decimal128.fromString('37.499999999999999196428571428571375') + * Uncaught: + * BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding + * at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11) + * at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25) + * at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27) + * + * > d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375') + * new Decimal128("37.49999999999999919642857142857138") + * ``` + * @param representation - a numeric string representation. + */ + static fromStringWithRounding(representation: string): Decimal128; + private static _fromString; + /** Create a string representation of the raw Decimal128 value */ + toString(): string; + toJSON(): Decimal128Extended; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface Decimal128Extended { + $numberDecimal: string; +} + +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +export declare function deserialize(buffer: Uint8Array, options?: DeserializeOptions): Document; + +/** @public */ +export declare interface DeserializeOptions { + /** + * when deserializing a Long return as a BigInt. + * @defaultValue `false` + */ + useBigInt64?: boolean; + /** + * when deserializing a Long will fit it into a Number if it's smaller than 53 bits. + * @defaultValue `true` + */ + promoteLongs?: boolean; + /** + * when deserializing a Binary will return it as a node.js Buffer instance. + * @defaultValue `false` + */ + promoteBuffers?: boolean; + /** + * when deserializing will promote BSON values to their Node.js closest equivalent types. + * @defaultValue `true` + */ + promoteValues?: boolean; + /** + * allow to specify if there what fields we wish to return as unserialized raw buffer. + * @defaultValue `null` + */ + fieldsAsRaw?: Document; + /** + * return BSON regular expressions as BSONRegExp instances. + * @defaultValue `false` + */ + bsonRegExp?: boolean; + /** + * allows the buffer to be larger than the parsed BSON object. + * @defaultValue `false` + */ + allowObjectSmallerThanBufferSize?: boolean; + /** + * Offset into buffer to begin reading document from + * @defaultValue `0` + */ + index?: number; + raw?: boolean; + /** Allows for opt-out utf-8 validation for all keys or + * specified keys. Must be all true or all false. + * + * @example + * ```js + * // disables validation on all keys + * validation: { utf8: false } + * + * // enables validation only on specified keys a, b, and c + * validation: { utf8: { a: true, b: true, c: true } } + * + * // disables validation only on specified keys a, b + * validation: { utf8: { a: false, b: false } } + * ``` + */ + validation?: { + utf8: boolean | Record | Record; + }; +} + +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +export declare function deserializeStream(data: Uint8Array | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number; + +/** @public */ +export declare interface Document { + [key: string]: any; +} + +/** + * A class representation of the BSON Double type. + * @public + * @category BSONType + */ +export declare class Double extends BSONValue { + get _bsontype(): 'Double'; + value: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number); + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + valueOf(): number; + toJSON(): number; + toString(radix?: number): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface DoubleExtended { + $numberDouble: string; +} + +/** @public */ +export declare const EJSON: { + parse: typeof parse; + stringify: typeof stringify; + serialize: typeof EJSONserialize; + deserialize: typeof EJSONdeserialize; +}; + +/** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ +declare function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any; + +/** @public */ +export declare type EJSONOptions = { + /** + * Output using the Extended JSON v1 spec + * @defaultValue `false` + */ + legacy?: boolean; + /** + * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types + * @defaultValue `false` */ + relaxed?: boolean; + /** + * Enable native bigint support + * @defaultValue `false` + */ + useBigInt64?: boolean; +}; + +/** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ +declare function EJSONserialize(value: any, options?: EJSONOptions): Document; + +declare type InspectFn = (x: unknown, options?: unknown) => string; + +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +export declare class Int32 extends BSONValue { + get _bsontype(): 'Int32'; + value: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string); + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + valueOf(): number; + toString(radix?: number): string; + toJSON(): number; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface Int32Extended { + $numberInt: string; +} + +/** + * A class representing a 64-bit integer + * @public + * @category BSONType + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +export declare class Long extends BSONValue { + get _bsontype(): 'Long'; + /** An indicator used to reliably determine if an object is a Long or not. */ + get __isLong__(): boolean; + /** + * The high 32 bits as a signed value. + */ + high: number; + /** + * The low 32 bits as a signed value. + */ + low: number; + /** + * Whether unsigned or not. + */ + unsigned: boolean; + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + constructor(low?: number | bigint | string, high?: number | boolean, unsigned?: boolean); + static TWO_PWR_24: Long; + /** Maximum unsigned value. */ + static MAX_UNSIGNED_VALUE: Long; + /** Signed zero */ + static ZERO: Long; + /** Unsigned zero. */ + static UZERO: Long; + /** Signed one. */ + static ONE: Long; + /** Unsigned one. */ + static UONE: Long; + /** Signed negative one. */ + static NEG_ONE: Long; + /** Maximum signed value. */ + static MAX_VALUE: Long; + /** Minimum signed value. */ + static MIN_VALUE: Long; + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromInt(value: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromNumber(value: number, unsigned?: boolean): Long; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long; + /** + * Tests if the specified object is a Long. + */ + static isLong(value: unknown): value is Long; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + static fromValue(val: number | string | { + low: number; + high: number; + unsigned?: boolean; + }, unsigned?: boolean): Long; + /** Returns the sum of this and the specified Long. */ + add(addend: string | number | Long | Timestamp): Long; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + and(other: string | number | Long | Timestamp): Long; + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: string | number | Long | Timestamp): 0 | 1 | -1; + /** This is an alias of {@link Long.compare} */ + comp(other: string | number | Long | Timestamp): 0 | 1 | -1; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + divide(divisor: string | number | Long | Timestamp): Long; + /**This is an alias of {@link Long.divide} */ + div(divisor: string | number | Long | Timestamp): Long; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + equals(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.equals} */ + eq(other: string | number | Long | Timestamp): boolean; + /** Gets the high 32 bits as a signed integer. */ + getHighBits(): number; + /** Gets the high 32 bits as an unsigned integer. */ + getHighBitsUnsigned(): number; + /** Gets the low 32 bits as a signed integer. */ + getLowBits(): number; + /** Gets the low 32 bits as an unsigned integer. */ + getLowBitsUnsigned(): number; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + getNumBitsAbs(): number; + /** Tests if this Long's value is greater than the specified's. */ + greaterThan(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThan} */ + gt(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is greater than or equal the specified's. */ + greaterThanOrEqual(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + gte(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + ge(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is even. */ + isEven(): boolean; + /** Tests if this Long's value is negative. */ + isNegative(): boolean; + /** Tests if this Long's value is odd. */ + isOdd(): boolean; + /** Tests if this Long's value is positive. */ + isPositive(): boolean; + /** Tests if this Long's value equals zero. */ + isZero(): boolean; + /** Tests if this Long's value is less than the specified's. */ + lessThan(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long#lessThan}. */ + lt(other: string | number | Long | Timestamp): boolean; + /** Tests if this Long's value is less than or equal the specified's. */ + lessThanOrEqual(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.lessThanOrEqual} */ + lte(other: string | number | Long | Timestamp): boolean; + /** Returns this Long modulo the specified. */ + modulo(divisor: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.modulo} */ + mod(divisor: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.modulo} */ + rem(divisor: string | number | Long | Timestamp): Long; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + multiply(multiplier: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.multiply} */ + mul(multiplier: string | number | Long | Timestamp): Long; + /** Returns the Negation of this Long's value. */ + negate(): Long; + /** This is an alias of {@link Long.negate} */ + neg(): Long; + /** Returns the bitwise NOT of this Long. */ + not(): Long; + /** Tests if this Long's value differs from the specified's. */ + notEquals(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.notEquals} */ + neq(other: string | number | Long | Timestamp): boolean; + /** This is an alias of {@link Long.notEquals} */ + ne(other: string | number | Long | Timestamp): boolean; + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: number | string | Long): Long; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftLeft(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftLeft} */ + shl(numBits: number | Long): Long; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRight(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftRight} */ + shr(numBits: number | Long): Long; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRightUnsigned(numBits: Long | number): Long; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shr_u(numBits: number | Long): Long; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shru(numBits: number | Long): Long; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + subtract(subtrahend: string | number | Long | Timestamp): Long; + /** This is an alias of {@link Long.subtract} */ + sub(subtrahend: string | number | Long | Timestamp): Long; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + toInt(): number; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + toNumber(): number; + /** Converts the Long to a BigInt (arbitrary precision). */ + toBigInt(): bigint; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + toBytes(le?: boolean): number[]; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + toBytesLE(): number[]; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + toBytesBE(): number[]; + /** + * Converts this Long to signed. + */ + toSigned(): Long; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + toString(radix?: number): string; + /** Converts this Long to unsigned. */ + toUnsigned(): Long; + /** Returns the bitwise XOR of this Long and the given one. */ + xor(other: Long | number | string): Long; + /** This is an alias of {@link Long.isZero} */ + eqz(): boolean; + /** This is an alias of {@link Long.lessThanOrEqual} */ + le(other: string | number | Long | Timestamp): boolean; + toExtendedJSON(options?: EJSONOptions): number | LongExtended; + static fromExtendedJSON(doc: { + $numberLong: string; + }, options?: EJSONOptions): number | Long | bigint; + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface LongExtended { + $numberLong: string; +} + +/** @public */ +export declare type LongWithoutOverrides = new (low: unknown, high?: number | boolean, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; + +/** @public */ +export declare const LongWithoutOverridesClass: LongWithoutOverrides; + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export declare class MaxKey extends BSONValue { + get _bsontype(): 'MaxKey'; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +export declare class MinKey extends BSONValue { + get _bsontype(): 'MinKey'; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON ObjectId type. + * @public + * @category BSONType + */ +export declare class ObjectId extends BSONValue { + get _bsontype(): 'ObjectId'; + /* Excluded from this release type: index */ + static cacheHexString: boolean; + /* Excluded from this release type: buffer */ + /* Excluded from this release type: __id */ + /** + * Create ObjectId from a number. + * + * @param inputId - A number. + * @deprecated Instead, use `static createFromTime()` to set a numeric value for the new ObjectId. + */ + constructor(inputId: number); + /** + * Create ObjectId from a 24 character hex string. + * + * @param inputId - A 24 character hex string. + */ + constructor(inputId: string); + /** + * Create ObjectId from the BSON ObjectId type. + * + * @param inputId - The BSON ObjectId type. + */ + constructor(inputId: ObjectId); + /** + * Create ObjectId from the object type that has the toHexString method. + * + * @param inputId - The ObjectIdLike type. + */ + constructor(inputId: ObjectIdLike); + /** + * Create ObjectId from a 12 byte binary Buffer. + * + * @param inputId - A 12 byte binary Buffer. + */ + constructor(inputId: Uint8Array); + /** To generate a new ObjectId, use ObjectId() with no argument. */ + constructor(); + /** + * Implementation overload. + * + * @param inputId - All input types that are used in the constructor implementation. + */ + constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array); + /** + * The ObjectId bytes + * @readonly + */ + get id(): Uint8Array; + set id(value: Uint8Array); + /** Returns the ObjectId id as a 24 lowercase character hex string representation */ + toHexString(): string; + /* Excluded from this release type: getInc */ + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + static generate(time?: number): Uint8Array; + /** + * Converts the id into a 24 character hex string for printing, unless encoding is provided. + * @param encoding - hex or base64 + */ + toString(encoding?: 'hex' | 'base64'): string; + /** Converts to its JSON the 24 character hex string representation. */ + toJSON(): string; + /* Excluded from this release type: is */ + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + getTimestamp(): Date; + /* Excluded from this release type: createPk */ + /* Excluded from this release type: serializeInto */ + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + static createFromTime(time: number): ObjectId; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + static createFromHexString(hexString: string): ObjectId; + /** Creates an ObjectId instance from a base64 string */ + static createFromBase64(base64: string): ObjectId; + /** + * Checks if a value can be used to create a valid bson ObjectId + * @param id - any JS value + */ + static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface ObjectIdExtended { + $oid: string; +} + +/** @public */ +export declare interface ObjectIdLike { + id: string | Uint8Array; + __id?: string; + toHexString(): string; +} + +/** + * @experimental + * @public + * + * A new set of BSON APIs that are currently experimental and not intended for production use. + */ +declare type OnDemand = { + BSONOffsetError: { + new (message: string, offset: number): BSONOffsetError; + isBSONError(value: unknown): value is BSONError; + }; + parseToElements: (this: void, bytes: Uint8Array, startOffset?: number) => Iterable; +}; + +/** + * @experimental + * @public + */ +export declare const onDemand: OnDemand; + +/** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ +declare function parse(text: string, options?: EJSONOptions): any; + +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +export declare function serialize(object: Document, options?: SerializeOptions): Uint8Array; + +/** @public */ +export declare interface SerializeOptions { + /** + * the serializer will check if keys are valid. + * @defaultValue `false` + */ + checkKeys?: boolean; + /** + * serialize the javascript functions + * @defaultValue `false` + */ + serializeFunctions?: boolean; + /** + * serialize will not emit undefined fields + * note that the driver sets this to `false` + * @defaultValue `true` + */ + ignoreUndefined?: boolean; + /* Excluded from this release type: minInternalBufferSize */ + /** + * the index in the buffer where we wish to start serializing into + * @defaultValue `0` + */ + index?: number; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +export declare function serializeWithBufferAndIndex(object: Document, finalBuffer: Uint8Array, options?: SerializeOptions): number; + +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer in bytes + * @public + */ +export declare function setInternalBufferSize(size: number): void; + +/** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ +declare function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, space?: string | number, options?: EJSONOptions): string; + +/** + * @public + * @category BSONType + */ +export declare class Timestamp extends LongWithoutOverridesClass { + get _bsontype(): 'Timestamp'; + static readonly MAX_VALUE: Long; + /** + * @param int - A 64-bit bigint representing the Timestamp. + */ + constructor(int: bigint); + /** + * @param long - A 64-bit Long representing the Timestamp. + */ + constructor(long: Long); + /** + * @param value - A pair of two values indicating timestamp and increment. + */ + constructor(value: { + t: number; + i: number; + }); + toJSON(): { + $timestamp: string; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + static fromInt(value: number): Timestamp; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + static fromNumber(value: number): Timestamp; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + static fromBits(lowBits: number, highBits: number): Timestamp; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + static fromString(str: string, optRadix: number): Timestamp; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare interface TimestampExtended { + $timestamp: { + t: number; + i: number; + }; +} + +/** @public */ +export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; + +/** + * A class representation of the BSON UUID type. + * @public + */ +export declare class UUID extends Binary { + /** + * Create a UUID type + * + * When the argument to the constructor is omitted a random v4 UUID will be generated. + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + constructor(input?: string | Uint8Array | UUID); + /** + * The UUID bytes + * @readonly + */ + get id(): Uint8Array; + set id(value: Uint8Array); + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + */ + toHexString(includeDashes?: boolean): string; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + toString(encoding?: 'hex' | 'base64'): string; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + toJSON(): string; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + equals(otherId: string | Uint8Array | UUID): boolean; + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary; + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Uint8Array; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Uint8Array | UUID | Binary): boolean; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + static createFromHexString(hexString: string): UUID; + /** Creates an UUID from a base64 string representation of an UUID. */ + static createFromBase64(base64: string): UUID; + /* Excluded from this release type: bytesFromString */ + /* Excluded from this release type: isValidUUIDString */ + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * + */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; +} + +/** @public */ +export declare type UUIDExtended = { + $uuid: string; +}; + +export { } diff --git a/nodejs/node_modules/bson/etc/prepare.js b/nodejs/node_modules/bson/etc/prepare.js new file mode 100755 index 00000000..91e6f3a9 --- /dev/null +++ b/nodejs/node_modules/bson/etc/prepare.js @@ -0,0 +1,19 @@ +#! /usr/bin/env node +var cp = require('child_process'); +var fs = require('fs'); + +var nodeMajorVersion = +process.version.match(/^v(\d+)\.\d+/)[1]; + +if (fs.existsSync('src') && nodeMajorVersion >= 10) { + cp.spawnSync('npm', ['run', 'build'], { stdio: 'inherit', shell: true }); +} else { + if (!fs.existsSync('lib')) { + console.warn('BSON: No compiled javascript present, the library is not installed correctly.'); + if (nodeMajorVersion < 10) { + console.warn( + 'This library can only be compiled in nodejs version 10 or later, currently running: ' + + nodeMajorVersion + ); + } + } +} diff --git a/nodejs/node_modules/bson/lib/bson.bundle.js b/nodejs/node_modules/bson/lib/bson.bundle.js new file mode 100644 index 00000000..3549424b --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.bundle.js @@ -0,0 +1,4342 @@ +var BSON = (function (exports) { +'use strict'; + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} +function defaultInspect(x, _options) { + return JSON.stringify(x, (k, v) => { + if (typeof v === 'bigint') { + return { $numberLong: `${v}` }; + } + else if (isMap(v)) { + return Object.fromEntries(v); + } + return v; + }); +} +function getStylizeFunction(options) { + const stylizeExists = options != null && + typeof options === 'object' && + 'stylize' in options && + typeof options.stylize === 'function'; + if (stylizeExists) { + return options.stylize; + } +} + +const BSON_MAJOR_VERSION = 6; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message, options) { + super(message, options); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} +class BSONOffsetError extends BSONError { + get name() { + return 'BSONOffsetError'; + } + constructor(message, offset) { + super(`${message}. offset: ${offset}`); + this.offset = offset; + } +} + +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; +function validateUtf8(bytes, start, end) { + let continuation = 0; + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} + +function tryReadBasicLatin(uint8array, start, end) { + if (uint8array.length === 0) { + return ''; + } + const stringByteLength = end - start; + if (stringByteLength === 0) { + return ''; + } + if (stringByteLength > 20) { + return null; + } + if (stringByteLength === 1 && uint8array[start] < 128) { + return String.fromCharCode(uint8array[start]); + } + if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + if (stringByteLength === 3 && + uint8array[start] < 128 && + uint8array[start + 1] < 128 && + uint8array[start + 2] < 128) { + return (String.fromCharCode(uint8array[start]) + + String.fromCharCode(uint8array[start + 1]) + + String.fromCharCode(uint8array[start + 2])); + } + const latinBytes = []; + for (let i = start; i < end; i++) { + const byte = uint8array[i]; + if (byte > 127) { + return null; + } + latinBytes.push(byte); + } + return String.fromCharCode(...latinBytes); +} +function tryWriteBasicLatin(destination, source, offset) { + if (source.length === 0) + return 0; + if (source.length > 25) + return null; + if (destination.length - offset < source.length) + return null; + for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) { + const char = source.charCodeAt(charOffset); + if (char > 127) + return null; + destination[destinationOffset] = char; + } + return source.length; +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + allocateUnsafe(size) { + return Buffer.allocUnsafe(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + toUTF8(buffer, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end); + if (fatal) { + for (let i = 0; i < string.length; i++) { + if (string.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return string; + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset); + if (latinBytesWritten != null) { + return latinBytesWritten; + } + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + allocateUnsafe(size) { + return webByteUtils.allocate(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + toUTF8(uint8array, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + if (fatal) { + try { + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + } + catch (cause) { + throw new BSONError('Invalid UTF-8 string in BSON document', { cause }); + } + } + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + }, + utf8ByteLength(input) { + return new TextEncoder().encode(input).byteLength; + }, + encodeUTF8Into(uint8array, source, byteOffset) { + const bytes = new TextEncoder().encode(source); + uint8array.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } + [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) { + return this.inspect(depth, options, inspect); + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + typeof buffer === 'string' && + !ArrayBuffer.isView(buffer) && + !isAnyArrayBuffer(buffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from Uint8Array or number[]'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + this.buffer = Array.isArray(buffer) + ? ByteUtils.fromNumberArray(buffer) + : ByteUtils.toLocalBufferType(buffer); + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + throw new BSONError('input cannot be string'); + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value() { + return this.buffer.length === this.position + ? this.buffer + : this.buffer.subarray(0, this.position); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + toUUID() { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); + } + static createFromHexString(hex, subType) { + return new Binary(ByteUtils.fromHex(hex), subType); + } + static createFromBase64(base64, subType) { + return new Binary(ByteUtils.fromBase64(base64), subType); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = UUID.bytesFromString(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + const base64Arg = inspect(base64, options); + const subTypeArg = inspect(this.sub_type, options); + return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_SENSITIVE = 8; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; +const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; +class UUID extends Binary { + constructor(input) { + let bytes; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = UUID.bytesFromString(input); + } + else { + throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + } + toHexString(includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(this.buffer.subarray(0, 4)), + ByteUtils.toHex(this.buffer.subarray(4, 6)), + ByteUtils.toHex(this.buffer.subarray(6, 8)), + ByteUtils.toHex(this.buffer.subarray(8, 10)), + ByteUtils.toHex(this.buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (typeof input === 'string') { + return UUID.isValidUUIDString(input); + } + if (isUint8Array(input)) { + return input.byteLength === UUID_BYTE_LENGTH; + } + return (input._bsontype === 'Binary' && + input.sub_type === this.SUBTYPE_UUID && + input.buffer.byteLength === 16); + } + static createFromHexString(hexString) { + const buffer = UUID.bytesFromString(hexString); + return new UUID(buffer); + } + static createFromBase64(base64) { + return new UUID(ByteUtils.fromBase64(base64)); + } + static bytesFromString(representation) { + if (!UUID.isValidUUIDString(representation)) { + throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation'); + } + return ByteUtils.fromHex(representation.replace(/-/g, '')); + } + static isValidUUIDString(representation) { + return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new UUID(${inspect(this.toHexString(), options)})`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + let parametersString = inspect(this.code, options); + const multiLineFn = parametersString.includes('\n'); + if (this.scope != null) { + parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`; + } + const endingNewline = multiLineFn && this.scope === null; + return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const args = [ + inspect(this.namespace, options), + inspect(this.oid, options), + ...(this.db ? [inspect(this.db, options)] : []), + ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []) + ]; + args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; + return `new DBRef(${args.join(', ')})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch { +} +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + static fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + } + static fromBytesBE(bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + const thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + const hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + toBytesBE() { + const hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const longVal = inspect(this.toString(), options); + const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ''; + return `new Long(${longVal}${unsignedVal})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (let i = 0; i <= 3; i++) { + _rem = _rem.shiftLeft(32); + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + return Decimal128._fromString(representation, { allowRounding: false }); + } + static fromStringWithRounding(representation) { + return Decimal128._fromString(representation, { allowRounding: true }); + } + static _fromString(representation, options) { + let isNegative = false; + let sawSign = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let lastDigit = 0; + let exponent = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + sawSign = true; + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < MAX_DIGITS) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + if (!nDigitsStored) { + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') { + significantDigits = significantDigits - 1; + } + } + } + if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit >= MAX_DIGITS) { + if (significantDigits === 0) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + if (options.allowRounding) { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + let dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + else { + break; + } + } + } + } + } + else { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0) { + if (significantDigits === 0) { + exponent = EXPONENT_MIN; + break; + } + invalidErr(representation, 'exponent underflow'); + } + if (nDigitsStored < nDigits) { + if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' && + significantDigits !== 0) { + invalidErr(representation, 'inexact rounding'); + } + nDigits = nDigits - 1; + } + else { + if (digits[lastDigit] !== 0) { + invalidErr(representation, 'inexact rounding'); + } + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + if (sawRadix) { + firstNonZero = firstNonZero + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + if (roundDigit !== 0) { + invalidErr(representation, 'inexact rounding'); + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit < 17) { + let dIdx = 0; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + let dIdx = 0; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocateUnsafe(16); + index = 0; + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + return new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + const exponent = biased_exponent - EXPONENT_BIAS; + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) + string.push(`E+${exponent}`); + else if (exponent < 0) + string.push(`E${exponent}`); + return string.join(''); + } + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + while (radix_position++ < 0) { + string.push('0'); + } + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + return string.join(''); + } + toJSON() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const d128string = inspect(this.toString(), options); + return `new Decimal128(${d128string})`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Double(${inspect(this.value, options)})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Int32(${inspect(this.value, options)})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + inspect() { + return 'new MinKey()'; + } +} + +const FLOAT = new Float64Array(1); +const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); +FLOAT[0] = -1; +const isBigEndian = FLOAT_BYTES[7] === 0; +const NumberUtils = { + getInt32LE(source, offset) { + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); + }, + getUint32LE(source, offset) { + return (source[offset] + + source[offset + 1] * 256 + + source[offset + 2] * 65536 + + source[offset + 3] * 16777216); + }, + getUint32BE(source, offset) { + return (source[offset + 3] + + source[offset + 2] * 256 + + source[offset + 1] * 65536 + + source[offset] * 16777216); + }, + getBigInt64LE(source, offset) { + const lo = NumberUtils.getUint32LE(source, offset); + const hi = NumberUtils.getUint32LE(source, offset + 4); + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }, + getFloat64LE: isBigEndian + ? (source, offset) => { + FLOAT_BYTES[7] = source[offset]; + FLOAT_BYTES[6] = source[offset + 1]; + FLOAT_BYTES[5] = source[offset + 2]; + FLOAT_BYTES[4] = source[offset + 3]; + FLOAT_BYTES[3] = source[offset + 4]; + FLOAT_BYTES[2] = source[offset + 5]; + FLOAT_BYTES[1] = source[offset + 6]; + FLOAT_BYTES[0] = source[offset + 7]; + return FLOAT[0]; + } + : (source, offset) => { + FLOAT_BYTES[0] = source[offset]; + FLOAT_BYTES[1] = source[offset + 1]; + FLOAT_BYTES[2] = source[offset + 2]; + FLOAT_BYTES[3] = source[offset + 3]; + FLOAT_BYTES[4] = source[offset + 4]; + FLOAT_BYTES[5] = source[offset + 5]; + FLOAT_BYTES[6] = source[offset + 6]; + FLOAT_BYTES[7] = source[offset + 7]; + return FLOAT[0]; + }, + setInt32BE(destination, offset, value) { + destination[offset + 3] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset] = value; + return 4; + }, + setInt32LE(destination, offset, value) { + destination[offset] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 3] = value; + return 4; + }, + setBigInt64LE(destination, offset, value) { + const mask32bits = BigInt(4294967295); + let lo = Number(value & mask32bits); + destination[offset] = lo; + lo >>= 8; + destination[offset + 1] = lo; + lo >>= 8; + destination[offset + 2] = lo; + lo >>= 8; + destination[offset + 3] = lo; + let hi = Number((value >> BigInt(32)) & mask32bits); + destination[offset + 4] = hi; + hi >>= 8; + destination[offset + 5] = hi; + hi >>= 8; + destination[offset + 6] = hi; + hi >>= 8; + destination[offset + 7] = hi; + return 8; + }, + setFloat64LE: isBigEndian + ? (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[7]; + destination[offset + 1] = FLOAT_BYTES[6]; + destination[offset + 2] = FLOAT_BYTES[5]; + destination[offset + 3] = FLOAT_BYTES[4]; + destination[offset + 4] = FLOAT_BYTES[3]; + destination[offset + 5] = FLOAT_BYTES[2]; + destination[offset + 6] = FLOAT_BYTES[1]; + destination[offset + 7] = FLOAT_BYTES[0]; + return 8; + } + : (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[0]; + destination[offset + 1] = FLOAT_BYTES[1]; + destination[offset + 2] = FLOAT_BYTES[2]; + destination[offset + 3] = FLOAT_BYTES[3]; + destination[offset + 4] = FLOAT_BYTES[4]; + destination[offset + 5] = FLOAT_BYTES[5]; + destination[offset + 6] = FLOAT_BYTES[6]; + destination[offset + 7] = FLOAT_BYTES[7]; + return 8; + } +}; + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this.buffer = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this.buffer = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this.buffer = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocateUnsafe(12); + NumberUtils.setInt32BE(buffer, 0, time); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + static is(variable) { + return (variable != null && + typeof variable === 'object' && + '_bsontype' in variable && + variable._bsontype === 'ObjectId'); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (ObjectId.is(otherId)) { + return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer)); + } + if (typeof otherId === 'string') { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + return false; + } + getTimestamp() { + const timestamp = new Date(); + const time = NumberUtils.getUint32BE(this.buffer, 0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + serializeInto(uint8array, index) { + uint8array[index] = this.buffer[0]; + uint8array[index + 1] = this.buffer[1]; + uint8array[index + 2] = this.buffer[2]; + uint8array[index + 3] = this.buffer[3]; + uint8array[index + 4] = this.buffer[4]; + uint8array[index + 5] = this.buffer[5]; + uint8array[index + 6] = this.buffer[6]; + uint8array[index + 7] = this.buffer[7]; + uint8array[index + 8] = this.buffer[8]; + uint8array[index + 9] = this.buffer[9]; + uint8array[index + 10] = this.buffer[10]; + uint8array[index + 11] = this.buffer[11]; + return 12; + } + static createFromTime(time) { + const buffer = ByteUtils.allocate(12); + for (let i = 11; i >= 4; i--) + buffer[i] = 0; + NumberUtils.setInt32BE(buffer, 0, time); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (hexString?.length !== 24) { + throw new BSONError('hex string must be 24 characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static createFromBase64(base64) { + if (base64?.length !== 16) { + throw new BSONError('base64 string must be 16 characters'); + } + return new ObjectId(ByteUtils.fromBase64(base64)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new ObjectId(${inspect(this.toHexString(), options)})`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + let totalLength = 4 + 1; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); + } + for (let i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + static parseOptions(options) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + inspect(depth, options, inspect) { + const stylize = getStylizeFunction(options) ?? (v => v); + inspect ??= defaultInspect; + const pattern = stylize(inspect(this.pattern), 'regexp'); + const flags = stylize(inspect(this.options), 'regexp'); + return `new BSONRegExp(${pattern}, ${flags})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new BSONSymbol(${inspect(this.value, options)})`; + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + const t = Number(low.t); + const i = Number(low.i); + if (t < 0 || Number.isNaN(t)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (i < 0 || Number.isNaN(i)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(i, t, true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const t = inspect(this.high >>> 0, options); + const i = inspect(this.low >>> 0, options); + return `new Timestamp({ t: ${t}, i: ${i} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + const size = NumberUtils.getInt32LE(buffer, index); + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + if (size + index > buffer.byteLength) { + throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`); + } + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + let utf8KeysSet; + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } + else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + utf8KeysSet = new Set(); + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet?.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + const oid = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oid[i] = buffer[index + i]; + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(NumberUtils.getInt32LE(buffer, index)); + index += 4; + } + else if (elementType === BSON_DATA_INT) { + value = NumberUtils.getInt32LE(buffer, index); + index += 4; + } + else if (elementType === BSON_DATA_NUMBER) { + value = NumberUtils.getFloat64LE(buffer, index); + index += 8; + if (promoteValues === false) + value = new Double(value); + } + else if (elementType === BSON_DATA_DATE) { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + let arrayOptions = options; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, raw: true }; + } + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + if (useBigInt64) { + value = NumberUtils.getBigInt64LE(buffer, index); + index += 8; + } + else { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + const long = new Long(lowBits, highBits); + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocateUnsafe(16); + for (let i = 0; i < 16; i++) + bytes[i] = buffer[index + i]; + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + else { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.allocateUnsafe(binarySize); + for (i = 0; i < binarySize; i++) { + value[i] = buffer[index + i]; + } + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + value = new Timestamp({ + i: NumberUtils.getUint32LE(buffer, index), + t: NumberUtils.getUint32LE(buffer, index + 4) + }); + index += 8; + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, false); + index = index + stringSize; + const oidBuffer = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oidBuffer[i] = buffer[index + i]; + const oid = new ObjectId(oidBuffer); + index = index + 12; + value = new DBRef(namespace, oid); + } + else { + throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + NumberUtils.setInt32LE(buffer, index, size + 1); + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + if (type === BSON_DATA_INT) { + index += NumberUtils.setInt32LE(buffer, index, value); + } + else { + index += NumberUtils.setFloat64LE(buffer, index, value); + } + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setBigInt64LE(buffer, index, value); + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += value.serializeInto(buffer, index); + return index; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = value[i]; + } + else { + buffer.set(value, index); + } + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + for (let i = 0; i < 16; i++) + buffer[index + i] = value.bytes[i]; + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeInt32(buffer, key, value, index) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setInt32LE(buffer, index, value); + return index; +} +function serializeDouble(buffer, key, value, index) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setFloat64LE(buffer, index, value.value); + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, codeSize); + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize); + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = value.sub_type; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + index += NumberUtils.setInt32LE(buffer, index, size); + } + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = data[i]; + } + else { + buffer.set(data, index); + } + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path); + const size = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, index, size); + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size); + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + return date; + } + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + if (v instanceof DBRef) + return v; + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid = false; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + if (value instanceof Map || isMap(value)) { + const obj = Object.create(null); + for (const [k, v] of value) { + if (typeof k !== 'string') { + throw new BSONError('Can only serialize maps with string keys'); + } + obj[k] = v; + } + return serializeValue(obj, options); + } + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONError('Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/`); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +const BSON_TYPE_MAPPINGS = { + Binary: (o) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectId: (o) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(doc)) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + _doc[name] = value; + } + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); + } + return deserializeValue(value, ejsonOptions); + }); +} +function stringify(value, replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +function getSize(source, offset) { + if (source[offset + 3] > 127) { + throw new BSONOffsetError('BSON size cannot be negative', offset); + } + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); +} +function findNull(bytes, offset) { + let nullTerminatorOffset = offset; + for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++) + ; + if (nullTerminatorOffset === bytes.length - 1) { + throw new BSONOffsetError('Null terminator not found', offset); + } + return nullTerminatorOffset; +} +function parseToElements(bytes, startOffset = 0) { + if (bytes.length < 5) { + throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); + } + const documentSize = getSize(bytes, startOffset); + if (documentSize > bytes.length - startOffset) { + throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); + } + if (bytes[startOffset + documentSize - 1] !== 0x00) { + throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize); + } + const elements = []; + let offset = startOffset + 4; + while (offset <= documentSize + startOffset) { + const type = bytes[offset]; + offset += 1; + if (type === 0) { + if (offset - startOffset !== documentSize) { + throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); + } + break; + } + const nameOffset = offset; + const nameLength = findNull(bytes, offset) - nameOffset; + offset += nameLength + 1; + let length; + if (type === 1 || type === 18 || type === 9 || type === 17) { + length = 8; + } + else if (type === 16) { + length = 4; + } + else if (type === 7) { + length = 12; + } + else if (type === 19) { + length = 16; + } + else if (type === 8) { + length = 1; + } + else if (type === 10 || type === 6 || type === 127 || type === 255) { + length = 0; + } + else if (type === 11) { + length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; + } + else if (type === 3 || type === 4 || type === 15) { + length = getSize(bytes, offset); + } + else if (type === 2 || + type === 5 || + type === 12 || + type === 13 || + type === 14) { + length = getSize(bytes, offset) + 4; + if (type === 5) { + length += 1; + } + if (type === 12) { + length += 12; + } + } + else { + throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset); + } + if (length > documentSize) { + throw new BSONOffsetError('value reports length larger than document', offset); + } + elements.push([type, nameOffset, nameLength, offset, length]); + offset += length; + } + return elements; +} + +const onDemand = Object.create(null); +onDemand.parseToElements = parseToElements; +onDemand.BSONOffsetError = BSONOffsetError; +Object.freeze(onDemand); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + options = options || {}; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = NumberUtils.getInt32LE(bufferData, index); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ +__proto__: null, +BSONError: BSONError, +BSONRegExp: BSONRegExp, +BSONRuntimeError: BSONRuntimeError, +BSONSymbol: BSONSymbol, +BSONType: BSONType, +BSONValue: BSONValue, +BSONVersionError: BSONVersionError, +Binary: Binary, +Code: Code, +DBRef: DBRef, +Decimal128: Decimal128, +Double: Double, +EJSON: EJSON, +Int32: Int32, +Long: Long, +MaxKey: MaxKey, +MinKey: MinKey, +ObjectId: ObjectId, +Timestamp: Timestamp, +UUID: UUID, +calculateObjectSize: calculateObjectSize, +deserialize: deserialize, +deserializeStream: deserializeStream, +onDemand: onDemand, +serialize: serialize, +serializeWithBufferAndIndex: serializeWithBufferAndIndex, +setInternalBufferSize: setInternalBufferSize +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONRuntimeError = BSONRuntimeError; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.onDemand = onDemand; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; + +return exports; + +})({}); +//# sourceMappingURL=bson.bundle.js.map diff --git a/nodejs/node_modules/bson/lib/bson.bundle.js.map b/nodejs/node_modules/bson/lib/bson.bundle.js.map new file mode 100644 index 00000000..49500463 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.bundle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.bundle.js","sources":["../src/parser/utils.ts","../src/constants.ts","../src/error.ts","../src/validate_utf8.ts","../src/utils/latin.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/utils/number_utils.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/parser/on_demand/parse_to_elements.ts","../src/parser/on_demand/index.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;;AAAM,SAAU,gBAAgB,CAAC,KAAc,EAAA;AAC7C,IAAA,O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K,GAAG,IAAI,CAAC;KACtB;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/bson/lib/bson.cjs b/nodejs/node_modules/bson/lib/bson.cjs new file mode 100644 index 00000000..5da4e7a8 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.cjs @@ -0,0 +1,4337 @@ +'use strict'; + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} +function defaultInspect(x, _options) { + return JSON.stringify(x, (k, v) => { + if (typeof v === 'bigint') { + return { $numberLong: `${v}` }; + } + else if (isMap(v)) { + return Object.fromEntries(v); + } + return v; + }); +} +function getStylizeFunction(options) { + const stylizeExists = options != null && + typeof options === 'object' && + 'stylize' in options && + typeof options.stylize === 'function'; + if (stylizeExists) { + return options.stylize; + } +} + +const BSON_MAJOR_VERSION = 6; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message, options) { + super(message, options); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} +class BSONOffsetError extends BSONError { + get name() { + return 'BSONOffsetError'; + } + constructor(message, offset) { + super(`${message}. offset: ${offset}`); + this.offset = offset; + } +} + +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; +function validateUtf8(bytes, start, end) { + let continuation = 0; + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} + +function tryReadBasicLatin(uint8array, start, end) { + if (uint8array.length === 0) { + return ''; + } + const stringByteLength = end - start; + if (stringByteLength === 0) { + return ''; + } + if (stringByteLength > 20) { + return null; + } + if (stringByteLength === 1 && uint8array[start] < 128) { + return String.fromCharCode(uint8array[start]); + } + if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + if (stringByteLength === 3 && + uint8array[start] < 128 && + uint8array[start + 1] < 128 && + uint8array[start + 2] < 128) { + return (String.fromCharCode(uint8array[start]) + + String.fromCharCode(uint8array[start + 1]) + + String.fromCharCode(uint8array[start + 2])); + } + const latinBytes = []; + for (let i = start; i < end; i++) { + const byte = uint8array[i]; + if (byte > 127) { + return null; + } + latinBytes.push(byte); + } + return String.fromCharCode(...latinBytes); +} +function tryWriteBasicLatin(destination, source, offset) { + if (source.length === 0) + return 0; + if (source.length > 25) + return null; + if (destination.length - offset < source.length) + return null; + for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) { + const char = source.charCodeAt(charOffset); + if (char > 127) + return null; + destination[destinationOffset] = char; + } + return source.length; +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + allocateUnsafe(size) { + return Buffer.allocUnsafe(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + toUTF8(buffer, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end); + if (fatal) { + for (let i = 0; i < string.length; i++) { + if (string.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return string; + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset); + if (latinBytesWritten != null) { + return latinBytesWritten; + } + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + allocateUnsafe(size) { + return webByteUtils.allocate(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + toUTF8(uint8array, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + if (fatal) { + try { + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + } + catch (cause) { + throw new BSONError('Invalid UTF-8 string in BSON document', { cause }); + } + } + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + }, + utf8ByteLength(input) { + return new TextEncoder().encode(input).byteLength; + }, + encodeUTF8Into(uint8array, source, byteOffset) { + const bytes = new TextEncoder().encode(source); + uint8array.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } + [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) { + return this.inspect(depth, options, inspect); + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + typeof buffer === 'string' && + !ArrayBuffer.isView(buffer) && + !isAnyArrayBuffer(buffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from Uint8Array or number[]'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + this.buffer = Array.isArray(buffer) + ? ByteUtils.fromNumberArray(buffer) + : ByteUtils.toLocalBufferType(buffer); + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + throw new BSONError('input cannot be string'); + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value() { + return this.buffer.length === this.position + ? this.buffer + : this.buffer.subarray(0, this.position); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + toUUID() { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); + } + static createFromHexString(hex, subType) { + return new Binary(ByteUtils.fromHex(hex), subType); + } + static createFromBase64(base64, subType) { + return new Binary(ByteUtils.fromBase64(base64), subType); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = UUID.bytesFromString(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + const base64Arg = inspect(base64, options); + const subTypeArg = inspect(this.sub_type, options); + return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_SENSITIVE = 8; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; +const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; +class UUID extends Binary { + constructor(input) { + let bytes; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = UUID.bytesFromString(input); + } + else { + throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + } + toHexString(includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(this.buffer.subarray(0, 4)), + ByteUtils.toHex(this.buffer.subarray(4, 6)), + ByteUtils.toHex(this.buffer.subarray(6, 8)), + ByteUtils.toHex(this.buffer.subarray(8, 10)), + ByteUtils.toHex(this.buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (typeof input === 'string') { + return UUID.isValidUUIDString(input); + } + if (isUint8Array(input)) { + return input.byteLength === UUID_BYTE_LENGTH; + } + return (input._bsontype === 'Binary' && + input.sub_type === this.SUBTYPE_UUID && + input.buffer.byteLength === 16); + } + static createFromHexString(hexString) { + const buffer = UUID.bytesFromString(hexString); + return new UUID(buffer); + } + static createFromBase64(base64) { + return new UUID(ByteUtils.fromBase64(base64)); + } + static bytesFromString(representation) { + if (!UUID.isValidUUIDString(representation)) { + throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation'); + } + return ByteUtils.fromHex(representation.replace(/-/g, '')); + } + static isValidUUIDString(representation) { + return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new UUID(${inspect(this.toHexString(), options)})`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + let parametersString = inspect(this.code, options); + const multiLineFn = parametersString.includes('\n'); + if (this.scope != null) { + parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`; + } + const endingNewline = multiLineFn && this.scope === null; + return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const args = [ + inspect(this.namespace, options), + inspect(this.oid, options), + ...(this.db ? [inspect(this.db, options)] : []), + ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []) + ]; + args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; + return `new DBRef(${args.join(', ')})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch { +} +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + static fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + } + static fromBytesBE(bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + const thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + const hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + toBytesBE() { + const hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const longVal = inspect(this.toString(), options); + const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ''; + return `new Long(${longVal}${unsignedVal})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (let i = 0; i <= 3; i++) { + _rem = _rem.shiftLeft(32); + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + return Decimal128._fromString(representation, { allowRounding: false }); + } + static fromStringWithRounding(representation) { + return Decimal128._fromString(representation, { allowRounding: true }); + } + static _fromString(representation, options) { + let isNegative = false; + let sawSign = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let lastDigit = 0; + let exponent = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + sawSign = true; + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < MAX_DIGITS) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + if (!nDigitsStored) { + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') { + significantDigits = significantDigits - 1; + } + } + } + if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit >= MAX_DIGITS) { + if (significantDigits === 0) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + if (options.allowRounding) { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + let dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + else { + break; + } + } + } + } + } + else { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0) { + if (significantDigits === 0) { + exponent = EXPONENT_MIN; + break; + } + invalidErr(representation, 'exponent underflow'); + } + if (nDigitsStored < nDigits) { + if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' && + significantDigits !== 0) { + invalidErr(representation, 'inexact rounding'); + } + nDigits = nDigits - 1; + } + else { + if (digits[lastDigit] !== 0) { + invalidErr(representation, 'inexact rounding'); + } + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + if (sawRadix) { + firstNonZero = firstNonZero + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + if (roundDigit !== 0) { + invalidErr(representation, 'inexact rounding'); + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit < 17) { + let dIdx = 0; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + let dIdx = 0; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocateUnsafe(16); + index = 0; + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + return new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + const exponent = biased_exponent - EXPONENT_BIAS; + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) + string.push(`E+${exponent}`); + else if (exponent < 0) + string.push(`E${exponent}`); + return string.join(''); + } + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + while (radix_position++ < 0) { + string.push('0'); + } + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + return string.join(''); + } + toJSON() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const d128string = inspect(this.toString(), options); + return `new Decimal128(${d128string})`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Double(${inspect(this.value, options)})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Int32(${inspect(this.value, options)})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + inspect() { + return 'new MinKey()'; + } +} + +const FLOAT = new Float64Array(1); +const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); +FLOAT[0] = -1; +const isBigEndian = FLOAT_BYTES[7] === 0; +const NumberUtils = { + getInt32LE(source, offset) { + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); + }, + getUint32LE(source, offset) { + return (source[offset] + + source[offset + 1] * 256 + + source[offset + 2] * 65536 + + source[offset + 3] * 16777216); + }, + getUint32BE(source, offset) { + return (source[offset + 3] + + source[offset + 2] * 256 + + source[offset + 1] * 65536 + + source[offset] * 16777216); + }, + getBigInt64LE(source, offset) { + const lo = NumberUtils.getUint32LE(source, offset); + const hi = NumberUtils.getUint32LE(source, offset + 4); + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }, + getFloat64LE: isBigEndian + ? (source, offset) => { + FLOAT_BYTES[7] = source[offset]; + FLOAT_BYTES[6] = source[offset + 1]; + FLOAT_BYTES[5] = source[offset + 2]; + FLOAT_BYTES[4] = source[offset + 3]; + FLOAT_BYTES[3] = source[offset + 4]; + FLOAT_BYTES[2] = source[offset + 5]; + FLOAT_BYTES[1] = source[offset + 6]; + FLOAT_BYTES[0] = source[offset + 7]; + return FLOAT[0]; + } + : (source, offset) => { + FLOAT_BYTES[0] = source[offset]; + FLOAT_BYTES[1] = source[offset + 1]; + FLOAT_BYTES[2] = source[offset + 2]; + FLOAT_BYTES[3] = source[offset + 3]; + FLOAT_BYTES[4] = source[offset + 4]; + FLOAT_BYTES[5] = source[offset + 5]; + FLOAT_BYTES[6] = source[offset + 6]; + FLOAT_BYTES[7] = source[offset + 7]; + return FLOAT[0]; + }, + setInt32BE(destination, offset, value) { + destination[offset + 3] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset] = value; + return 4; + }, + setInt32LE(destination, offset, value) { + destination[offset] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 3] = value; + return 4; + }, + setBigInt64LE(destination, offset, value) { + const mask32bits = BigInt(4294967295); + let lo = Number(value & mask32bits); + destination[offset] = lo; + lo >>= 8; + destination[offset + 1] = lo; + lo >>= 8; + destination[offset + 2] = lo; + lo >>= 8; + destination[offset + 3] = lo; + let hi = Number((value >> BigInt(32)) & mask32bits); + destination[offset + 4] = hi; + hi >>= 8; + destination[offset + 5] = hi; + hi >>= 8; + destination[offset + 6] = hi; + hi >>= 8; + destination[offset + 7] = hi; + return 8; + }, + setFloat64LE: isBigEndian + ? (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[7]; + destination[offset + 1] = FLOAT_BYTES[6]; + destination[offset + 2] = FLOAT_BYTES[5]; + destination[offset + 3] = FLOAT_BYTES[4]; + destination[offset + 4] = FLOAT_BYTES[3]; + destination[offset + 5] = FLOAT_BYTES[2]; + destination[offset + 6] = FLOAT_BYTES[1]; + destination[offset + 7] = FLOAT_BYTES[0]; + return 8; + } + : (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[0]; + destination[offset + 1] = FLOAT_BYTES[1]; + destination[offset + 2] = FLOAT_BYTES[2]; + destination[offset + 3] = FLOAT_BYTES[3]; + destination[offset + 4] = FLOAT_BYTES[4]; + destination[offset + 5] = FLOAT_BYTES[5]; + destination[offset + 6] = FLOAT_BYTES[6]; + destination[offset + 7] = FLOAT_BYTES[7]; + return 8; + } +}; + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this.buffer = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this.buffer = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this.buffer = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocateUnsafe(12); + NumberUtils.setInt32BE(buffer, 0, time); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + static is(variable) { + return (variable != null && + typeof variable === 'object' && + '_bsontype' in variable && + variable._bsontype === 'ObjectId'); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (ObjectId.is(otherId)) { + return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer)); + } + if (typeof otherId === 'string') { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + return false; + } + getTimestamp() { + const timestamp = new Date(); + const time = NumberUtils.getUint32BE(this.buffer, 0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + serializeInto(uint8array, index) { + uint8array[index] = this.buffer[0]; + uint8array[index + 1] = this.buffer[1]; + uint8array[index + 2] = this.buffer[2]; + uint8array[index + 3] = this.buffer[3]; + uint8array[index + 4] = this.buffer[4]; + uint8array[index + 5] = this.buffer[5]; + uint8array[index + 6] = this.buffer[6]; + uint8array[index + 7] = this.buffer[7]; + uint8array[index + 8] = this.buffer[8]; + uint8array[index + 9] = this.buffer[9]; + uint8array[index + 10] = this.buffer[10]; + uint8array[index + 11] = this.buffer[11]; + return 12; + } + static createFromTime(time) { + const buffer = ByteUtils.allocate(12); + for (let i = 11; i >= 4; i--) + buffer[i] = 0; + NumberUtils.setInt32BE(buffer, 0, time); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (hexString?.length !== 24) { + throw new BSONError('hex string must be 24 characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static createFromBase64(base64) { + if (base64?.length !== 16) { + throw new BSONError('base64 string must be 16 characters'); + } + return new ObjectId(ByteUtils.fromBase64(base64)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new ObjectId(${inspect(this.toHexString(), options)})`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + let totalLength = 4 + 1; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); + } + for (let i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + static parseOptions(options) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + inspect(depth, options, inspect) { + const stylize = getStylizeFunction(options) ?? (v => v); + inspect ??= defaultInspect; + const pattern = stylize(inspect(this.pattern), 'regexp'); + const flags = stylize(inspect(this.options), 'regexp'); + return `new BSONRegExp(${pattern}, ${flags})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new BSONSymbol(${inspect(this.value, options)})`; + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + const t = Number(low.t); + const i = Number(low.i); + if (t < 0 || Number.isNaN(t)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (i < 0 || Number.isNaN(i)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(i, t, true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const t = inspect(this.high >>> 0, options); + const i = inspect(this.low >>> 0, options); + return `new Timestamp({ t: ${t}, i: ${i} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + const size = NumberUtils.getInt32LE(buffer, index); + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + if (size + index > buffer.byteLength) { + throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`); + } + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + let utf8KeysSet; + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } + else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + utf8KeysSet = new Set(); + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet?.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + const oid = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oid[i] = buffer[index + i]; + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(NumberUtils.getInt32LE(buffer, index)); + index += 4; + } + else if (elementType === BSON_DATA_INT) { + value = NumberUtils.getInt32LE(buffer, index); + index += 4; + } + else if (elementType === BSON_DATA_NUMBER) { + value = NumberUtils.getFloat64LE(buffer, index); + index += 8; + if (promoteValues === false) + value = new Double(value); + } + else if (elementType === BSON_DATA_DATE) { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + let arrayOptions = options; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, raw: true }; + } + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + if (useBigInt64) { + value = NumberUtils.getBigInt64LE(buffer, index); + index += 8; + } + else { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + const long = new Long(lowBits, highBits); + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocateUnsafe(16); + for (let i = 0; i < 16; i++) + bytes[i] = buffer[index + i]; + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + else { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.allocateUnsafe(binarySize); + for (i = 0; i < binarySize; i++) { + value[i] = buffer[index + i]; + } + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + value = new Timestamp({ + i: NumberUtils.getUint32LE(buffer, index), + t: NumberUtils.getUint32LE(buffer, index + 4) + }); + index += 8; + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, false); + index = index + stringSize; + const oidBuffer = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oidBuffer[i] = buffer[index + i]; + const oid = new ObjectId(oidBuffer); + index = index + 12; + value = new DBRef(namespace, oid); + } + else { + throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + NumberUtils.setInt32LE(buffer, index, size + 1); + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + if (type === BSON_DATA_INT) { + index += NumberUtils.setInt32LE(buffer, index, value); + } + else { + index += NumberUtils.setFloat64LE(buffer, index, value); + } + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setBigInt64LE(buffer, index, value); + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += value.serializeInto(buffer, index); + return index; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = value[i]; + } + else { + buffer.set(value, index); + } + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + for (let i = 0; i < 16; i++) + buffer[index + i] = value.bytes[i]; + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeInt32(buffer, key, value, index) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setInt32LE(buffer, index, value); + return index; +} +function serializeDouble(buffer, key, value, index) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setFloat64LE(buffer, index, value.value); + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, codeSize); + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize); + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = value.sub_type; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + index += NumberUtils.setInt32LE(buffer, index, size); + } + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = data[i]; + } + else { + buffer.set(data, index); + } + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path); + const size = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, index, size); + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size); + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + return date; + } + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + if (v instanceof DBRef) + return v; + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid = false; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + if (value instanceof Map || isMap(value)) { + const obj = Object.create(null); + for (const [k, v] of value) { + if (typeof k !== 'string') { + throw new BSONError('Can only serialize maps with string keys'); + } + obj[k] = v; + } + return serializeValue(obj, options); + } + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONError('Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/`); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +const BSON_TYPE_MAPPINGS = { + Binary: (o) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectId: (o) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(doc)) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + _doc[name] = value; + } + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); + } + return deserializeValue(value, ejsonOptions); + }); +} +function stringify(value, replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +function getSize(source, offset) { + if (source[offset + 3] > 127) { + throw new BSONOffsetError('BSON size cannot be negative', offset); + } + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); +} +function findNull(bytes, offset) { + let nullTerminatorOffset = offset; + for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++) + ; + if (nullTerminatorOffset === bytes.length - 1) { + throw new BSONOffsetError('Null terminator not found', offset); + } + return nullTerminatorOffset; +} +function parseToElements(bytes, startOffset = 0) { + if (bytes.length < 5) { + throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); + } + const documentSize = getSize(bytes, startOffset); + if (documentSize > bytes.length - startOffset) { + throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); + } + if (bytes[startOffset + documentSize - 1] !== 0x00) { + throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize); + } + const elements = []; + let offset = startOffset + 4; + while (offset <= documentSize + startOffset) { + const type = bytes[offset]; + offset += 1; + if (type === 0) { + if (offset - startOffset !== documentSize) { + throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); + } + break; + } + const nameOffset = offset; + const nameLength = findNull(bytes, offset) - nameOffset; + offset += nameLength + 1; + let length; + if (type === 1 || type === 18 || type === 9 || type === 17) { + length = 8; + } + else if (type === 16) { + length = 4; + } + else if (type === 7) { + length = 12; + } + else if (type === 19) { + length = 16; + } + else if (type === 8) { + length = 1; + } + else if (type === 10 || type === 6 || type === 127 || type === 255) { + length = 0; + } + else if (type === 11) { + length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; + } + else if (type === 3 || type === 4 || type === 15) { + length = getSize(bytes, offset); + } + else if (type === 2 || + type === 5 || + type === 12 || + type === 13 || + type === 14) { + length = getSize(bytes, offset) + 4; + if (type === 5) { + length += 1; + } + if (type === 12) { + length += 12; + } + } + else { + throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset); + } + if (length > documentSize) { + throw new BSONOffsetError('value reports length larger than document', offset); + } + elements.push([type, nameOffset, nameLength, offset, length]); + offset += length; + } + return elements; +} + +const onDemand = Object.create(null); +onDemand.parseToElements = parseToElements; +onDemand.BSONOffsetError = BSONOffsetError; +Object.freeze(onDemand); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + options = options || {}; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = NumberUtils.getInt32LE(bufferData, index); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + BSONError: BSONError, + BSONRegExp: BSONRegExp, + BSONRuntimeError: BSONRuntimeError, + BSONSymbol: BSONSymbol, + BSONType: BSONType, + BSONValue: BSONValue, + BSONVersionError: BSONVersionError, + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + EJSON: EJSON, + Int32: Int32, + Long: Long, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + Timestamp: Timestamp, + UUID: UUID, + calculateObjectSize: calculateObjectSize, + deserialize: deserialize, + deserializeStream: deserializeStream, + onDemand: onDemand, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + setInternalBufferSize: setInternalBufferSize +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONRuntimeError = BSONRuntimeError; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.onDemand = onDemand; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; +//# sourceMappingURL=bson.cjs.map diff --git a/nodejs/node_modules/bson/lib/bson.cjs.map b/nodejs/node_modules/bson/lib/bson.cjs.map new file mode 100644 index 00000000..215dfe55 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.cjs","sources":["../src/parser/utils.ts","../src/constants.ts","../src/error.ts","../src/validate_utf8.ts","../src/utils/latin.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/utils/number_utils.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/parser/on_demand/parse_to_elements.ts","../src/parser/on_demand/index.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;AAAM,SAAU,gBAAgB,CAAC,KAAc,EAAA;AAC7C,IAAA,OAAO,CAAC,sBAAsB,EAAE,4BAA4B,CAAC,CAAC,QAAQ,CACpE,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CACtC,CAAC;AACJ,CAAC;AAEK,SAAU,YAAY,CAAC,KAAc,EAAA;AACzC,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,qBAA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CAAC,kBAAkB,KAAK,SAAS,GAAG,OAAO,CAAC,kBAAkB,GAAG,KAAK,CAAC;AACvF,IAAA,MAAM,eAAe,GACnB,OAAO,OAAO,CAAC,eAAe,KAAK,SAAS,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAEhF,OAAO,2BAA2B,CAAC,MAAM,EAAE,kBAAkB,EAAE,eAAe,CAAC,CAAC;AAClF,CAAC;AAce,SAAA,iBAAiB,CAC/B,IAA8B,EAC9B,UAAkB,EAClB,iBAAyB,EACzB,SAAqB,EACrB,aAAqB,EACrB,OAA2B,EAAA;AAE3B,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CACnC,EAAE,gCAAgC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,EACpD,OAAO,CACR,CAAC;IACF,MAAM,UAAU,GAAG,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAErD,IAAI,KAAK,GAAG,UAAU,CAAC;AAEvB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;QAE1C,MAAM,IAAI,GAAG,WAAW,CAAC,UAAU,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;AAEvD,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;KACtB;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/bson/lib/bson.mjs b/nodejs/node_modules/bson/lib/bson.mjs new file mode 100644 index 00000000..d594b3c9 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.mjs @@ -0,0 +1,4308 @@ +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} +function defaultInspect(x, _options) { + return JSON.stringify(x, (k, v) => { + if (typeof v === 'bigint') { + return { $numberLong: `${v}` }; + } + else if (isMap(v)) { + return Object.fromEntries(v); + } + return v; + }); +} +function getStylizeFunction(options) { + const stylizeExists = options != null && + typeof options === 'object' && + 'stylize' in options && + typeof options.stylize === 'function'; + if (stylizeExists) { + return options.stylize; + } +} + +const BSON_MAJOR_VERSION = 6; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message, options) { + super(message, options); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} +class BSONOffsetError extends BSONError { + get name() { + return 'BSONOffsetError'; + } + constructor(message, offset) { + super(`${message}. offset: ${offset}`); + this.offset = offset; + } +} + +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; +function validateUtf8(bytes, start, end) { + let continuation = 0; + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} + +function tryReadBasicLatin(uint8array, start, end) { + if (uint8array.length === 0) { + return ''; + } + const stringByteLength = end - start; + if (stringByteLength === 0) { + return ''; + } + if (stringByteLength > 20) { + return null; + } + if (stringByteLength === 1 && uint8array[start] < 128) { + return String.fromCharCode(uint8array[start]); + } + if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + if (stringByteLength === 3 && + uint8array[start] < 128 && + uint8array[start + 1] < 128 && + uint8array[start + 2] < 128) { + return (String.fromCharCode(uint8array[start]) + + String.fromCharCode(uint8array[start + 1]) + + String.fromCharCode(uint8array[start + 2])); + } + const latinBytes = []; + for (let i = start; i < end; i++) { + const byte = uint8array[i]; + if (byte > 127) { + return null; + } + latinBytes.push(byte); + } + return String.fromCharCode(...latinBytes); +} +function tryWriteBasicLatin(destination, source, offset) { + if (source.length === 0) + return 0; + if (source.length > 25) + return null; + if (destination.length - offset < source.length) + return null; + for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) { + const char = source.charCodeAt(charOffset); + if (char > 127) + return null; + destination[destinationOffset] = char; + } + return source.length; +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = await (async () => { + try { + return (await import('crypto')).randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + allocateUnsafe(size) { + return Buffer.allocUnsafe(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + toUTF8(buffer, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end); + if (fatal) { + for (let i = 0; i < string.length; i++) { + if (string.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return string; + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset); + if (latinBytesWritten != null) { + return latinBytesWritten; + } + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + allocateUnsafe(size) { + return webByteUtils.allocate(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + toUTF8(uint8array, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + if (fatal) { + try { + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + } + catch (cause) { + throw new BSONError('Invalid UTF-8 string in BSON document', { cause }); + } + } + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + }, + utf8ByteLength(input) { + return new TextEncoder().encode(input).byteLength; + }, + encodeUTF8Into(uint8array, source, byteOffset) { + const bytes = new TextEncoder().encode(source); + uint8array.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } + [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) { + return this.inspect(depth, options, inspect); + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + typeof buffer === 'string' && + !ArrayBuffer.isView(buffer) && + !isAnyArrayBuffer(buffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from Uint8Array or number[]'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + this.buffer = Array.isArray(buffer) + ? ByteUtils.fromNumberArray(buffer) + : ByteUtils.toLocalBufferType(buffer); + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + throw new BSONError('input cannot be string'); + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value() { + return this.buffer.length === this.position + ? this.buffer + : this.buffer.subarray(0, this.position); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + toUUID() { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); + } + static createFromHexString(hex, subType) { + return new Binary(ByteUtils.fromHex(hex), subType); + } + static createFromBase64(base64, subType) { + return new Binary(ByteUtils.fromBase64(base64), subType); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = UUID.bytesFromString(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + const base64Arg = inspect(base64, options); + const subTypeArg = inspect(this.sub_type, options); + return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_SENSITIVE = 8; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; +const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; +class UUID extends Binary { + constructor(input) { + let bytes; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = UUID.bytesFromString(input); + } + else { + throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + } + toHexString(includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(this.buffer.subarray(0, 4)), + ByteUtils.toHex(this.buffer.subarray(4, 6)), + ByteUtils.toHex(this.buffer.subarray(6, 8)), + ByteUtils.toHex(this.buffer.subarray(8, 10)), + ByteUtils.toHex(this.buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (typeof input === 'string') { + return UUID.isValidUUIDString(input); + } + if (isUint8Array(input)) { + return input.byteLength === UUID_BYTE_LENGTH; + } + return (input._bsontype === 'Binary' && + input.sub_type === this.SUBTYPE_UUID && + input.buffer.byteLength === 16); + } + static createFromHexString(hexString) { + const buffer = UUID.bytesFromString(hexString); + return new UUID(buffer); + } + static createFromBase64(base64) { + return new UUID(ByteUtils.fromBase64(base64)); + } + static bytesFromString(representation) { + if (!UUID.isValidUUIDString(representation)) { + throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation'); + } + return ByteUtils.fromHex(representation.replace(/-/g, '')); + } + static isValidUUIDString(representation) { + return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new UUID(${inspect(this.toHexString(), options)})`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + let parametersString = inspect(this.code, options); + const multiLineFn = parametersString.includes('\n'); + if (this.scope != null) { + parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`; + } + const endingNewline = multiLineFn && this.scope === null; + return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const args = [ + inspect(this.namespace, options), + inspect(this.oid, options), + ...(this.db ? [inspect(this.db, options)] : []), + ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []) + ]; + args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; + return `new DBRef(${args.join(', ')})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch { +} +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + static fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + } + static fromBytesBE(bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + const thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + const hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + toBytesBE() { + const hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const longVal = inspect(this.toString(), options); + const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ''; + return `new Long(${longVal}${unsignedVal})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (let i = 0; i <= 3; i++) { + _rem = _rem.shiftLeft(32); + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + return Decimal128._fromString(representation, { allowRounding: false }); + } + static fromStringWithRounding(representation) { + return Decimal128._fromString(representation, { allowRounding: true }); + } + static _fromString(representation, options) { + let isNegative = false; + let sawSign = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let lastDigit = 0; + let exponent = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + sawSign = true; + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < MAX_DIGITS) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + if (!nDigitsStored) { + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') { + significantDigits = significantDigits - 1; + } + } + } + if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit >= MAX_DIGITS) { + if (significantDigits === 0) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + if (options.allowRounding) { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + let dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + else { + break; + } + } + } + } + } + else { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0) { + if (significantDigits === 0) { + exponent = EXPONENT_MIN; + break; + } + invalidErr(representation, 'exponent underflow'); + } + if (nDigitsStored < nDigits) { + if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' && + significantDigits !== 0) { + invalidErr(representation, 'inexact rounding'); + } + nDigits = nDigits - 1; + } + else { + if (digits[lastDigit] !== 0) { + invalidErr(representation, 'inexact rounding'); + } + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + if (sawRadix) { + firstNonZero = firstNonZero + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + if (roundDigit !== 0) { + invalidErr(representation, 'inexact rounding'); + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit < 17) { + let dIdx = 0; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + let dIdx = 0; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocateUnsafe(16); + index = 0; + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + return new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + const exponent = biased_exponent - EXPONENT_BIAS; + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) + string.push(`E+${exponent}`); + else if (exponent < 0) + string.push(`E${exponent}`); + return string.join(''); + } + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + while (radix_position++ < 0) { + string.push('0'); + } + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + return string.join(''); + } + toJSON() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const d128string = inspect(this.toString(), options); + return `new Decimal128(${d128string})`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Double(${inspect(this.value, options)})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Int32(${inspect(this.value, options)})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + inspect() { + return 'new MinKey()'; + } +} + +const FLOAT = new Float64Array(1); +const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); +FLOAT[0] = -1; +const isBigEndian = FLOAT_BYTES[7] === 0; +const NumberUtils = { + getInt32LE(source, offset) { + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); + }, + getUint32LE(source, offset) { + return (source[offset] + + source[offset + 1] * 256 + + source[offset + 2] * 65536 + + source[offset + 3] * 16777216); + }, + getUint32BE(source, offset) { + return (source[offset + 3] + + source[offset + 2] * 256 + + source[offset + 1] * 65536 + + source[offset] * 16777216); + }, + getBigInt64LE(source, offset) { + const lo = NumberUtils.getUint32LE(source, offset); + const hi = NumberUtils.getUint32LE(source, offset + 4); + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }, + getFloat64LE: isBigEndian + ? (source, offset) => { + FLOAT_BYTES[7] = source[offset]; + FLOAT_BYTES[6] = source[offset + 1]; + FLOAT_BYTES[5] = source[offset + 2]; + FLOAT_BYTES[4] = source[offset + 3]; + FLOAT_BYTES[3] = source[offset + 4]; + FLOAT_BYTES[2] = source[offset + 5]; + FLOAT_BYTES[1] = source[offset + 6]; + FLOAT_BYTES[0] = source[offset + 7]; + return FLOAT[0]; + } + : (source, offset) => { + FLOAT_BYTES[0] = source[offset]; + FLOAT_BYTES[1] = source[offset + 1]; + FLOAT_BYTES[2] = source[offset + 2]; + FLOAT_BYTES[3] = source[offset + 3]; + FLOAT_BYTES[4] = source[offset + 4]; + FLOAT_BYTES[5] = source[offset + 5]; + FLOAT_BYTES[6] = source[offset + 6]; + FLOAT_BYTES[7] = source[offset + 7]; + return FLOAT[0]; + }, + setInt32BE(destination, offset, value) { + destination[offset + 3] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset] = value; + return 4; + }, + setInt32LE(destination, offset, value) { + destination[offset] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 3] = value; + return 4; + }, + setBigInt64LE(destination, offset, value) { + const mask32bits = BigInt(4294967295); + let lo = Number(value & mask32bits); + destination[offset] = lo; + lo >>= 8; + destination[offset + 1] = lo; + lo >>= 8; + destination[offset + 2] = lo; + lo >>= 8; + destination[offset + 3] = lo; + let hi = Number((value >> BigInt(32)) & mask32bits); + destination[offset + 4] = hi; + hi >>= 8; + destination[offset + 5] = hi; + hi >>= 8; + destination[offset + 6] = hi; + hi >>= 8; + destination[offset + 7] = hi; + return 8; + }, + setFloat64LE: isBigEndian + ? (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[7]; + destination[offset + 1] = FLOAT_BYTES[6]; + destination[offset + 2] = FLOAT_BYTES[5]; + destination[offset + 3] = FLOAT_BYTES[4]; + destination[offset + 4] = FLOAT_BYTES[3]; + destination[offset + 5] = FLOAT_BYTES[2]; + destination[offset + 6] = FLOAT_BYTES[1]; + destination[offset + 7] = FLOAT_BYTES[0]; + return 8; + } + : (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[0]; + destination[offset + 1] = FLOAT_BYTES[1]; + destination[offset + 2] = FLOAT_BYTES[2]; + destination[offset + 3] = FLOAT_BYTES[3]; + destination[offset + 4] = FLOAT_BYTES[4]; + destination[offset + 5] = FLOAT_BYTES[5]; + destination[offset + 6] = FLOAT_BYTES[6]; + destination[offset + 7] = FLOAT_BYTES[7]; + return 8; + } +}; + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this.buffer = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this.buffer = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this.buffer = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocateUnsafe(12); + NumberUtils.setInt32BE(buffer, 0, time); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + static is(variable) { + return (variable != null && + typeof variable === 'object' && + '_bsontype' in variable && + variable._bsontype === 'ObjectId'); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (ObjectId.is(otherId)) { + return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer)); + } + if (typeof otherId === 'string') { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + return false; + } + getTimestamp() { + const timestamp = new Date(); + const time = NumberUtils.getUint32BE(this.buffer, 0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + serializeInto(uint8array, index) { + uint8array[index] = this.buffer[0]; + uint8array[index + 1] = this.buffer[1]; + uint8array[index + 2] = this.buffer[2]; + uint8array[index + 3] = this.buffer[3]; + uint8array[index + 4] = this.buffer[4]; + uint8array[index + 5] = this.buffer[5]; + uint8array[index + 6] = this.buffer[6]; + uint8array[index + 7] = this.buffer[7]; + uint8array[index + 8] = this.buffer[8]; + uint8array[index + 9] = this.buffer[9]; + uint8array[index + 10] = this.buffer[10]; + uint8array[index + 11] = this.buffer[11]; + return 12; + } + static createFromTime(time) { + const buffer = ByteUtils.allocate(12); + for (let i = 11; i >= 4; i--) + buffer[i] = 0; + NumberUtils.setInt32BE(buffer, 0, time); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (hexString?.length !== 24) { + throw new BSONError('hex string must be 24 characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static createFromBase64(base64) { + if (base64?.length !== 16) { + throw new BSONError('base64 string must be 16 characters'); + } + return new ObjectId(ByteUtils.fromBase64(base64)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new ObjectId(${inspect(this.toHexString(), options)})`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + let totalLength = 4 + 1; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); + } + for (let i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + static parseOptions(options) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + inspect(depth, options, inspect) { + const stylize = getStylizeFunction(options) ?? (v => v); + inspect ??= defaultInspect; + const pattern = stylize(inspect(this.pattern), 'regexp'); + const flags = stylize(inspect(this.options), 'regexp'); + return `new BSONRegExp(${pattern}, ${flags})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new BSONSymbol(${inspect(this.value, options)})`; + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + const t = Number(low.t); + const i = Number(low.i); + if (t < 0 || Number.isNaN(t)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (i < 0 || Number.isNaN(i)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(i, t, true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const t = inspect(this.high >>> 0, options); + const i = inspect(this.low >>> 0, options); + return `new Timestamp({ t: ${t}, i: ${i} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + const size = NumberUtils.getInt32LE(buffer, index); + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + if (size + index > buffer.byteLength) { + throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`); + } + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + let utf8KeysSet; + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } + else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + utf8KeysSet = new Set(); + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet?.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + const oid = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oid[i] = buffer[index + i]; + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(NumberUtils.getInt32LE(buffer, index)); + index += 4; + } + else if (elementType === BSON_DATA_INT) { + value = NumberUtils.getInt32LE(buffer, index); + index += 4; + } + else if (elementType === BSON_DATA_NUMBER) { + value = NumberUtils.getFloat64LE(buffer, index); + index += 8; + if (promoteValues === false) + value = new Double(value); + } + else if (elementType === BSON_DATA_DATE) { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + let arrayOptions = options; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, raw: true }; + } + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + if (useBigInt64) { + value = NumberUtils.getBigInt64LE(buffer, index); + index += 8; + } + else { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + const long = new Long(lowBits, highBits); + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocateUnsafe(16); + for (let i = 0; i < 16; i++) + bytes[i] = buffer[index + i]; + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + else { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.allocateUnsafe(binarySize); + for (i = 0; i < binarySize; i++) { + value[i] = buffer[index + i]; + } + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + value = new Timestamp({ + i: NumberUtils.getUint32LE(buffer, index), + t: NumberUtils.getUint32LE(buffer, index + 4) + }); + index += 8; + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, false); + index = index + stringSize; + const oidBuffer = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oidBuffer[i] = buffer[index + i]; + const oid = new ObjectId(oidBuffer); + index = index + 12; + value = new DBRef(namespace, oid); + } + else { + throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + NumberUtils.setInt32LE(buffer, index, size + 1); + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + if (type === BSON_DATA_INT) { + index += NumberUtils.setInt32LE(buffer, index, value); + } + else { + index += NumberUtils.setFloat64LE(buffer, index, value); + } + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setBigInt64LE(buffer, index, value); + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += value.serializeInto(buffer, index); + return index; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = value[i]; + } + else { + buffer.set(value, index); + } + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + for (let i = 0; i < 16; i++) + buffer[index + i] = value.bytes[i]; + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeInt32(buffer, key, value, index) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setInt32LE(buffer, index, value); + return index; +} +function serializeDouble(buffer, key, value, index) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setFloat64LE(buffer, index, value.value); + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, codeSize); + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize); + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = value.sub_type; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + index += NumberUtils.setInt32LE(buffer, index, size); + } + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = data[i]; + } + else { + buffer.set(data, index); + } + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path); + const size = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, index, size); + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size); + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + return date; + } + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + if (v instanceof DBRef) + return v; + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid = false; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + if (value instanceof Map || isMap(value)) { + const obj = Object.create(null); + for (const [k, v] of value) { + if (typeof k !== 'string') { + throw new BSONError('Can only serialize maps with string keys'); + } + obj[k] = v; + } + return serializeValue(obj, options); + } + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONError('Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/`); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +const BSON_TYPE_MAPPINGS = { + Binary: (o) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectId: (o) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(doc)) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + _doc[name] = value; + } + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); + } + return deserializeValue(value, ejsonOptions); + }); +} +function stringify(value, replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +function getSize(source, offset) { + if (source[offset + 3] > 127) { + throw new BSONOffsetError('BSON size cannot be negative', offset); + } + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); +} +function findNull(bytes, offset) { + let nullTerminatorOffset = offset; + for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++) + ; + if (nullTerminatorOffset === bytes.length - 1) { + throw new BSONOffsetError('Null terminator not found', offset); + } + return nullTerminatorOffset; +} +function parseToElements(bytes, startOffset = 0) { + if (bytes.length < 5) { + throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); + } + const documentSize = getSize(bytes, startOffset); + if (documentSize > bytes.length - startOffset) { + throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); + } + if (bytes[startOffset + documentSize - 1] !== 0x00) { + throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize); + } + const elements = []; + let offset = startOffset + 4; + while (offset <= documentSize + startOffset) { + const type = bytes[offset]; + offset += 1; + if (type === 0) { + if (offset - startOffset !== documentSize) { + throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); + } + break; + } + const nameOffset = offset; + const nameLength = findNull(bytes, offset) - nameOffset; + offset += nameLength + 1; + let length; + if (type === 1 || type === 18 || type === 9 || type === 17) { + length = 8; + } + else if (type === 16) { + length = 4; + } + else if (type === 7) { + length = 12; + } + else if (type === 19) { + length = 16; + } + else if (type === 8) { + length = 1; + } + else if (type === 10 || type === 6 || type === 127 || type === 255) { + length = 0; + } + else if (type === 11) { + length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; + } + else if (type === 3 || type === 4 || type === 15) { + length = getSize(bytes, offset); + } + else if (type === 2 || + type === 5 || + type === 12 || + type === 13 || + type === 14) { + length = getSize(bytes, offset) + 4; + if (type === 5) { + length += 1; + } + if (type === 12) { + length += 12; + } + } + else { + throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset); + } + if (length > documentSize) { + throw new BSONOffsetError('value reports length larger than document', offset); + } + elements.push([type, nameOffset, nameLength, offset, length]); + offset += length; + } + return elements; +} + +const onDemand = Object.create(null); +onDemand.parseToElements = parseToElements; +onDemand.BSONOffsetError = BSONOffsetError; +Object.freeze(onDemand); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + options = options || {}; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = NumberUtils.getInt32LE(bufferData, index); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + BSONError: BSONError, + BSONRegExp: BSONRegExp, + BSONRuntimeError: BSONRuntimeError, + BSONSymbol: BSONSymbol, + BSONType: BSONType, + BSONValue: BSONValue, + BSONVersionError: BSONVersionError, + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + EJSON: EJSON, + Int32: Int32, + Long: Long, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + Timestamp: Timestamp, + UUID: UUID, + calculateObjectSize: calculateObjectSize, + deserialize: deserialize, + deserializeStream: deserializeStream, + onDemand: onDemand, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + setInternalBufferSize: setInternalBufferSize +}); + +export { bson as BSON, BSONError, BSONRegExp, BSONRuntimeError, BSONSymbol, BSONType, BSONValue, BSONVersionError, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, MaxKey, MinKey, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, onDemand, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; +//# sourceMappingURL=bson.mjs.map diff --git a/nodejs/node_modules/bson/lib/bson.mjs.map b/nodejs/node_modules/bson/lib/bson.mjs.map new file mode 100644 index 00000000..838f45a9 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.mjs","sources":["../src/parser/utils.ts","../src/constants.ts","../src/error.ts","../src/validate_utf8.ts","../src/utils/latin.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/utils/number_utils.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/parser/on_demand/parse_to_elements.ts","../src/parser/on_demand/index.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":"AAAM,SAAU,gBAAgB,CAAC,KAAc,EAAA;AAC7C,IAAA,OAAO,CAAC,sBAAsB,EAAE,4BAA4B,CAAC,CAAC,QAAQ,CACpE,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CACtC,CAAC;AACJ,CAAC;AAEK,SAAU,YAAY,CAAC,KAAc,EAAA;AACzC,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,qBAAqB,CAAC;AACzE,CAAC;AAUK,SAAU,QAAQ,CAAC,CAAU,EAAA;AACjC,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC;AACjE,CAAC;AAEK,SAAU,KAAK,CAAC,CAAU,EAAA;AAC9B,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,cAAc,CAAC;AAC9D,CAAC;AAEK,SAAU,MAAM,CAAC,CAAU,EAAA;AAC/B,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC;AAC/D,CAAC;AAGe,SAAA,cAAc,CAAC,CAAU,EAAE,QAAkB,EAAA;IAC3D,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAS,EAAE,CAAU,KAAI;AACjD,QAAA,IAAI,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,CAAC;AAEvB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;QAE1C,MAAM,IAAI,GAAG,WAAW,CAAC,UAAU,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;AAEvD,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;KACtB;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/bson/lib/bson.rn.cjs b/nodejs/node_modules/bson/lib/bson.rn.cjs new file mode 100644 index 00000000..0042a3f5 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.rn.cjs @@ -0,0 +1,4353 @@ +'use strict'; + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} +function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} +function defaultInspect(x, _options) { + return JSON.stringify(x, (k, v) => { + if (typeof v === 'bigint') { + return { $numberLong: `${v}` }; + } + else if (isMap(v)) { + return Object.fromEntries(v); + } + return v; + }); +} +function getStylizeFunction(options) { + const stylizeExists = options != null && + typeof options === 'object' && + 'stylize' in options && + typeof options.stylize === 'function'; + if (stylizeExists) { + return options.stylize; + } +} + +const BSON_MAJOR_VERSION = 6; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_FUNCTION = 1; +const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +const BSON_BINARY_SUBTYPE_UUID = 3; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +const BSON_BINARY_SUBTYPE_MD5 = 5; +const BSON_BINARY_SUBTYPE_ENCRYPTED = 6; +const BSON_BINARY_SUBTYPE_COLUMN = 7; +const BSON_BINARY_SUBTYPE_SENSITIVE = 8; +const BSON_BINARY_SUBTYPE_USER_DEFINED = 128; +const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message, options) { + super(message, options); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} +class BSONOffsetError extends BSONError { + get name() { + return 'BSONOffsetError'; + } + constructor(message, offset) { + super(`${message}. offset: ${offset}`); + this.offset = offset; + } +} + +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; +function validateUtf8(bytes, start, end) { + let continuation = 0; + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} + +function tryReadBasicLatin(uint8array, start, end) { + if (uint8array.length === 0) { + return ''; + } + const stringByteLength = end - start; + if (stringByteLength === 0) { + return ''; + } + if (stringByteLength > 20) { + return null; + } + if (stringByteLength === 1 && uint8array[start] < 128) { + return String.fromCharCode(uint8array[start]); + } + if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + if (stringByteLength === 3 && + uint8array[start] < 128 && + uint8array[start + 1] < 128 && + uint8array[start + 2] < 128) { + return (String.fromCharCode(uint8array[start]) + + String.fromCharCode(uint8array[start + 1]) + + String.fromCharCode(uint8array[start + 2])); + } + const latinBytes = []; + for (let i = start; i < end; i++) { + const byte = uint8array[i]; + if (byte > 127) { + return null; + } + latinBytes.push(byte); + } + return String.fromCharCode(...latinBytes); +} +function tryWriteBasicLatin(destination, source, offset) { + if (source.length === 0) + return 0; + if (source.length > 25) + return null; + if (destination.length - offset < source.length) + return null; + for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) { + const char = source.charCodeAt(charOffset); + if (char > 127) + return null; + destination[destinationOffset] = char; + } + return source.length; +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + allocateUnsafe(size) { + return Buffer.allocUnsafe(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + toUTF8(buffer, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end); + if (fatal) { + for (let i = 0; i < string.length; i++) { + if (string.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return string; + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset); + if (latinBytesWritten != null) { + return latinBytesWritten; + } + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +const { TextEncoder, TextDecoder } = require('../vendor/text-encoding'); +const { encode: btoa, decode: atob } = require('../vendor/base64'); +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + allocateUnsafe(size) { + return webByteUtils.allocate(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + toUTF8(uint8array, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + if (fatal) { + try { + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + } + catch (cause) { + throw new BSONError('Invalid UTF-8 string in BSON document', { cause }); + } + } + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + }, + utf8ByteLength(input) { + return new TextEncoder().encode(input).byteLength; + }, + encodeUTF8Into(uint8array, source, byteOffset) { + const bytes = new TextEncoder().encode(source); + uint8array.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } + [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) { + return this.inspect(depth, options, inspect); + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + typeof buffer === 'string' && + !ArrayBuffer.isView(buffer) && + !isAnyArrayBuffer(buffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from Uint8Array or number[]'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + this.buffer = Array.isArray(buffer) + ? ByteUtils.fromNumberArray(buffer) + : ByteUtils.toLocalBufferType(buffer); + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } + else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } + else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + throw new BSONError('input cannot be string'); + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value() { + return this.buffer.length === this.position + ? this.buffer + : this.buffer.subarray(0, this.position); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + toUUID() { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); + } + static createFromHexString(hex, subType) { + return new Binary(ByteUtils.fromHex(hex), subType); + } + static createFromBase64(base64, subType) { + return new Binary(ByteUtils.fromBase64(base64), subType); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = UUID.bytesFromString(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + const base64Arg = inspect(base64, options); + const subTypeArg = inspect(this.sub_type, options); + return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_SENSITIVE = 8; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; +const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; +class UUID extends Binary { + constructor(input) { + let bytes; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = UUID.bytesFromString(input); + } + else { + throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + } + toHexString(includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(this.buffer.subarray(0, 4)), + ByteUtils.toHex(this.buffer.subarray(4, 6)), + ByteUtils.toHex(this.buffer.subarray(6, 8)), + ByteUtils.toHex(this.buffer.subarray(8, 10)), + ByteUtils.toHex(this.buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (typeof input === 'string') { + return UUID.isValidUUIDString(input); + } + if (isUint8Array(input)) { + return input.byteLength === UUID_BYTE_LENGTH; + } + return (input._bsontype === 'Binary' && + input.sub_type === this.SUBTYPE_UUID && + input.buffer.byteLength === 16); + } + static createFromHexString(hexString) { + const buffer = UUID.bytesFromString(hexString); + return new UUID(buffer); + } + static createFromBase64(base64) { + return new UUID(ByteUtils.fromBase64(base64)); + } + static bytesFromString(representation) { + if (!UUID.isValidUUIDString(representation)) { + throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation'); + } + return ByteUtils.fromHex(representation.replace(/-/g, '')); + } + static isValidUUIDString(representation) { + return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new UUID(${inspect(this.toHexString(), options)})`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + let parametersString = inspect(this.code, options); + const multiLineFn = parametersString.includes('\n'); + if (this.scope != null) { + parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`; + } + const endingNewline = multiLineFn && this.scope === null; + return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let o = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o; + } + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const args = [ + inspect(this.namespace, options), + inspect(this.oid, options), + ...(this.db ? [inspect(this.db, options)] : []), + ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []) + ]; + args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; + return `new DBRef(${args.join(', ')})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch { +} +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + static fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + } + static fromBytesBE(bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + const thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } + else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); + } + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + const hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + toBytesBE() { + const hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const longVal = inspect(this.toString(), options); + const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ''; + return `new Long(${longVal}${unsignedVal})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + for (let i = 0; i <= 3; i++) { + _rem = _rem.shiftLeft(32); + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + return { quotient: value, rem: _rem }; +} +function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + return { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + if (uhleft < uhright) { + return true; + } + else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) + return true; + } + return false; +} +function invalidErr(string, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + return Decimal128._fromString(representation, { allowRounding: false }); + } + static fromStringWithRounding(representation) { + return Decimal128._fromString(representation, { allowRounding: true }); + } + static _fromString(representation, options) { + let isNegative = false; + let sawSign = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let lastDigit = 0; + let exponent = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + sawSign = true; + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; + } + if (nDigitsStored < MAX_DIGITS) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + if (!nDigitsStored) { + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') { + significantDigits = significantDigits - 1; + } + } + } + if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit >= MAX_DIGITS) { + if (significantDigits === 0) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + if (options.allowRounding) { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + let dIdx = lastDigit; + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + else { + break; + } + } + } + } + } + else { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0) { + if (significantDigits === 0) { + exponent = EXPONENT_MIN; + break; + } + invalidErr(representation, 'exponent underflow'); + } + if (nDigitsStored < nDigits) { + if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' && + significantDigits !== 0) { + invalidErr(representation, 'inexact rounding'); + } + nDigits = nDigits - 1; + } + else { + if (digits[lastDigit] !== 0) { + invalidErr(representation, 'inexact rounding'); + } + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + invalidErr(representation, 'overflow'); + } + } + if (lastDigit + 1 < significantDigits) { + if (sawRadix) { + firstNonZero = firstNonZero + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + if (roundDigit !== 0) { + invalidErr(representation, 'inexact rounding'); + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } + else if (lastDigit < 17) { + let dIdx = 0; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + else { + let dIdx = 0; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + dec.low = significand.low; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocateUnsafe(16); + index = 0; + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + return new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } + else if (combination === COMBINATION_NAN) { + return 'NaN'; + } + else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + const exponent = biased_exponent - EXPONENT_BIAS; + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0) { + is_zero = true; + } + else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) + string.push(`E+${exponent}`); + else if (exponent < 0) + string.push(`E${exponent}`); + return string.join(''); + } + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); + } + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + while (radix_position++ < 0) { + string.push('0'); + } + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + return string.join(''); + } + toJSON() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const d128string = inspect(this.toString(), options); + return `new Decimal128(${d128string})`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Double(${inspect(this.value, options)})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Int32(${inspect(this.value, options)})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + inspect() { + return 'new MinKey()'; + } +} + +const FLOAT = new Float64Array(1); +const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); +FLOAT[0] = -1; +const isBigEndian = FLOAT_BYTES[7] === 0; +const NumberUtils = { + getInt32LE(source, offset) { + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); + }, + getUint32LE(source, offset) { + return (source[offset] + + source[offset + 1] * 256 + + source[offset + 2] * 65536 + + source[offset + 3] * 16777216); + }, + getUint32BE(source, offset) { + return (source[offset + 3] + + source[offset + 2] * 256 + + source[offset + 1] * 65536 + + source[offset] * 16777216); + }, + getBigInt64LE(source, offset) { + const lo = NumberUtils.getUint32LE(source, offset); + const hi = NumberUtils.getUint32LE(source, offset + 4); + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }, + getFloat64LE: isBigEndian + ? (source, offset) => { + FLOAT_BYTES[7] = source[offset]; + FLOAT_BYTES[6] = source[offset + 1]; + FLOAT_BYTES[5] = source[offset + 2]; + FLOAT_BYTES[4] = source[offset + 3]; + FLOAT_BYTES[3] = source[offset + 4]; + FLOAT_BYTES[2] = source[offset + 5]; + FLOAT_BYTES[1] = source[offset + 6]; + FLOAT_BYTES[0] = source[offset + 7]; + return FLOAT[0]; + } + : (source, offset) => { + FLOAT_BYTES[0] = source[offset]; + FLOAT_BYTES[1] = source[offset + 1]; + FLOAT_BYTES[2] = source[offset + 2]; + FLOAT_BYTES[3] = source[offset + 3]; + FLOAT_BYTES[4] = source[offset + 4]; + FLOAT_BYTES[5] = source[offset + 5]; + FLOAT_BYTES[6] = source[offset + 6]; + FLOAT_BYTES[7] = source[offset + 7]; + return FLOAT[0]; + }, + setInt32BE(destination, offset, value) { + destination[offset + 3] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset] = value; + return 4; + }, + setInt32LE(destination, offset, value) { + destination[offset] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 3] = value; + return 4; + }, + setBigInt64LE(destination, offset, value) { + const mask32bits = BigInt(4294967295); + let lo = Number(value & mask32bits); + destination[offset] = lo; + lo >>= 8; + destination[offset + 1] = lo; + lo >>= 8; + destination[offset + 2] = lo; + lo >>= 8; + destination[offset + 3] = lo; + let hi = Number((value >> BigInt(32)) & mask32bits); + destination[offset + 4] = hi; + hi >>= 8; + destination[offset + 5] = hi; + hi >>= 8; + destination[offset + 6] = hi; + hi >>= 8; + destination[offset + 7] = hi; + return 8; + }, + setFloat64LE: isBigEndian + ? (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[7]; + destination[offset + 1] = FLOAT_BYTES[6]; + destination[offset + 2] = FLOAT_BYTES[5]; + destination[offset + 3] = FLOAT_BYTES[4]; + destination[offset + 4] = FLOAT_BYTES[3]; + destination[offset + 5] = FLOAT_BYTES[2]; + destination[offset + 6] = FLOAT_BYTES[1]; + destination[offset + 7] = FLOAT_BYTES[0]; + return 8; + } + : (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[0]; + destination[offset + 1] = FLOAT_BYTES[1]; + destination[offset + 2] = FLOAT_BYTES[2]; + destination[offset + 3] = FLOAT_BYTES[3]; + destination[offset + 4] = FLOAT_BYTES[4]; + destination[offset + 5] = FLOAT_BYTES[5]; + destination[offset + 6] = FLOAT_BYTES[6]; + destination[offset + 7] = FLOAT_BYTES[7]; + return 8; + } +}; + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this.buffer = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this.buffer = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this.buffer = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocateUnsafe(12); + NumberUtils.setInt32BE(buffer, 0, time); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + static is(variable) { + return (variable != null && + typeof variable === 'object' && + '_bsontype' in variable && + variable._bsontype === 'ObjectId'); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (ObjectId.is(otherId)) { + return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer)); + } + if (typeof otherId === 'string') { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + return false; + } + getTimestamp() { + const timestamp = new Date(); + const time = NumberUtils.getUint32BE(this.buffer, 0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + serializeInto(uint8array, index) { + uint8array[index] = this.buffer[0]; + uint8array[index + 1] = this.buffer[1]; + uint8array[index + 2] = this.buffer[2]; + uint8array[index + 3] = this.buffer[3]; + uint8array[index + 4] = this.buffer[4]; + uint8array[index + 5] = this.buffer[5]; + uint8array[index + 6] = this.buffer[6]; + uint8array[index + 7] = this.buffer[7]; + uint8array[index + 8] = this.buffer[8]; + uint8array[index + 9] = this.buffer[9]; + uint8array[index + 10] = this.buffer[10]; + uint8array[index + 11] = this.buffer[11]; + return 12; + } + static createFromTime(time) { + const buffer = ByteUtils.allocate(12); + for (let i = 11; i >= 4; i--) + buffer[i] = 0; + NumberUtils.setInt32BE(buffer, 0, time); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (hexString?.length !== 24) { + throw new BSONError('hex string must be 24 characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static createFromBase64(base64) { + if (base64?.length !== 16) { + throw new BSONError('base64 string must be 16 characters'); + } + return new ObjectId(ByteUtils.fromBase64(base64)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new ObjectId(${inspect(this.toHexString(), options)})`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + let totalLength = 4 + 1; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); + } + for (let i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u')) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + static parseOptions(options) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + inspect(depth, options, inspect) { + const stylize = getStylizeFunction(options) ?? (v => v); + inspect ??= defaultInspect; + const pattern = stylize(inspect(this.pattern), 'regexp'); + const flags = stylize(inspect(this.options), 'regexp'); + return `new BSONRegExp(${pattern}, ${flags})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new BSONSymbol(${inspect(this.value, options)})`; + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + const t = Number(low.t); + const i = Number(low.i); + if (t < 0 || Number.isNaN(t)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (i < 0 || Number.isNaN(i)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(i, t, true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const t = inspect(this.high >>> 0, options); + const i = inspect(this.low >>> 0, options); + return `new Timestamp({ t: ${t}, i: ${i} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + const size = NumberUtils.getInt32LE(buffer, index); + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + if (size + index > buffer.byteLength) { + throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`); + } + if (buffer[index + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + let utf8KeysSet; + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } + else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + utf8KeysSet = new Set(); + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet?.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === BSON_DATA_STRING) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } + else if (elementType === BSON_DATA_OID) { + const oid = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oid[i] = buffer[index + i]; + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(NumberUtils.getInt32LE(buffer, index)); + index += 4; + } + else if (elementType === BSON_DATA_INT) { + value = NumberUtils.getInt32LE(buffer, index); + index += 4; + } + else if (elementType === BSON_DATA_NUMBER) { + value = NumberUtils.getFloat64LE(buffer, index); + index += 8; + if (promoteValues === false) + value = new Double(value); + } + else if (elementType === BSON_DATA_DATE) { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + value = new Date(new Long(lowBits, highBits).toNumber()); + } + else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === BSON_DATA_OBJECT) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + if (raw) { + value = buffer.slice(index, index + objectSize); + } + else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + index = index + objectSize; + } + else if (elementType === BSON_DATA_ARRAY) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + let arrayOptions = options; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, raw: true }; + } + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + if (buffer[index - 1] !== 0) + throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new BSONError('corrupted array bson'); + } + else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + if (useBigInt64) { + value = NumberUtils.getBigInt64LE(buffer, index); + index += 8; + } + else { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + const long = new Long(lowBits, highBits); + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; + } + } + } + else if (elementType === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocateUnsafe(16); + for (let i = 0; i < 16; i++) + bytes[i] = buffer[index + i]; + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + else { + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.allocateUnsafe(binarySize); + for (i = 0; i < binarySize; i++) { + value[i] = buffer[index + i]; + } + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === BSON_DATA_SYMBOL) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } + else if (elementType === BSON_DATA_TIMESTAMP) { + value = new Timestamp({ + i: NumberUtils.getUint32LE(buffer, index), + t: NumberUtils.getUint32LE(buffer, index + 4) + }); + index += 8; + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === BSON_DATA_CODE) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new BSONError('bad string length in bson'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, false); + index = index + stringSize; + const oidBuffer = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) + oidBuffer[i] = buffer[index + i]; + const oid = new ObjectId(oidBuffer); + index = index + 12; + value = new DBRef(namespace, oid); + } + else { + throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + NumberUtils.setInt32LE(buffer, index, size + 1); + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + if (type === BSON_DATA_INT) { + index += NumberUtils.setInt32LE(buffer, index, value); + } + else { + index += NumberUtils.setFloat64LE(buffer, index, value); + } + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setBigInt64LE(buffer, index, value); + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += value.serializeInto(buffer, index); + return index; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = value[i]; + } + else { + buffer.set(value, index); + } + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + for (let i = 0; i < 16; i++) + buffer[index + i] = value.bytes[i]; + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + index += NumberUtils.setInt32LE(buffer, index, lowBits); + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} +function serializeInt32(buffer, key, value, index) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setInt32LE(buffer, index, value); + return index; +} +function serializeDouble(buffer, key, value, index) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + index += NumberUtils.setFloat64LE(buffer, index, value.value); + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, codeSize); + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize); + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + index += NumberUtils.setInt32LE(buffer, index, size); + buffer[index++] = value.sub_type; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + index += NumberUtils.setInt32LE(buffer, index, size); + } + if (size <= 16) { + for (let i = 0; i < size; i++) + buffer[index + i] = data[i]; + } + else { + buffer.set(data, index); + } + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + NumberUtils.setInt32LE(buffer, index, size); + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path); + const size = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer, index, size); + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(buffer, key, value, index); + } + else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } + else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } + else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } + else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } + else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size); + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + return date; + } + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + if (v instanceof DBRef) + return v; + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid = false; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + if (value instanceof Map || isMap(value)) { + const obj = Object.create(null); + for (const [k, v] of value) { + if (typeof k !== 'string') { + throw new BSONError('Can only serialize maps with string keys'); + } + obj[k] = v; + } + return serializeValue(obj, options); + } + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONError('Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/`); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +const BSON_TYPE_MAPPINGS = { + Binary: (o) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectId: (o) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(doc)) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + _doc[name] = value; + } + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); + } + return deserializeValue(value, ejsonOptions); + }); +} +function stringify(value, replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +function getSize(source, offset) { + if (source[offset + 3] > 127) { + throw new BSONOffsetError('BSON size cannot be negative', offset); + } + return (source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24)); +} +function findNull(bytes, offset) { + let nullTerminatorOffset = offset; + for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++) + ; + if (nullTerminatorOffset === bytes.length - 1) { + throw new BSONOffsetError('Null terminator not found', offset); + } + return nullTerminatorOffset; +} +function parseToElements(bytes, startOffset = 0) { + if (bytes.length < 5) { + throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); + } + const documentSize = getSize(bytes, startOffset); + if (documentSize > bytes.length - startOffset) { + throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); + } + if (bytes[startOffset + documentSize - 1] !== 0x00) { + throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize); + } + const elements = []; + let offset = startOffset + 4; + while (offset <= documentSize + startOffset) { + const type = bytes[offset]; + offset += 1; + if (type === 0) { + if (offset - startOffset !== documentSize) { + throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); + } + break; + } + const nameOffset = offset; + const nameLength = findNull(bytes, offset) - nameOffset; + offset += nameLength + 1; + let length; + if (type === 1 || type === 18 || type === 9 || type === 17) { + length = 8; + } + else if (type === 16) { + length = 4; + } + else if (type === 7) { + length = 12; + } + else if (type === 19) { + length = 16; + } + else if (type === 8) { + length = 1; + } + else if (type === 10 || type === 6 || type === 127 || type === 255) { + length = 0; + } + else if (type === 11) { + length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; + } + else if (type === 3 || type === 4 || type === 15) { + length = getSize(bytes, offset); + } + else if (type === 2 || + type === 5 || + type === 12 || + type === 13 || + type === 14) { + length = getSize(bytes, offset) + 4; + if (type === 5) { + length += 1; + } + if (type === 12) { + length += 12; + } + } + else { + throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset); + } + if (length > documentSize) { + throw new BSONOffsetError('value reports length larger than document', offset); + } + elements.push([type, nameOffset, nameLength, offset, length]); + offset += length; + } + return elements; +} + +const onDemand = Object.create(null); +onDemand.parseToElements = parseToElements; +onDemand.BSONOffsetError = BSONOffsetError; +Object.freeze(onDemand); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + options = options || {}; + const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = NumberUtils.getInt32LE(bufferData, index); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + BSONError: BSONError, + BSONRegExp: BSONRegExp, + BSONRuntimeError: BSONRuntimeError, + BSONSymbol: BSONSymbol, + BSONType: BSONType, + BSONValue: BSONValue, + BSONVersionError: BSONVersionError, + Binary: Binary, + Code: Code, + DBRef: DBRef, + Decimal128: Decimal128, + Double: Double, + EJSON: EJSON, + Int32: Int32, + Long: Long, + MaxKey: MaxKey, + MinKey: MinKey, + ObjectId: ObjectId, + Timestamp: Timestamp, + UUID: UUID, + calculateObjectSize: calculateObjectSize, + deserialize: deserialize, + deserializeStream: deserializeStream, + onDemand: onDemand, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + setInternalBufferSize: setInternalBufferSize +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONRuntimeError = BSONRuntimeError; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.onDemand = onDemand; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; +//# sourceMappingURL=bson.rn.cjs.map diff --git a/nodejs/node_modules/bson/lib/bson.rn.cjs.map b/nodejs/node_modules/bson/lib/bson.rn.cjs.map new file mode 100644 index 00000000..525a8aa2 --- /dev/null +++ b/nodejs/node_modules/bson/lib/bson.rn.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.rn.cjs","sources":["../src/parser/utils.ts","../src/constants.ts","../src/error.ts","../src/validate_utf8.ts","../src/utils/latin.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/utils/number_utils.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/parser/on_demand/parse_to_elements.ts","../src/parser/on_demand/index.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;AAAM,SAAU,gBAAgB,CAAC,KAAc,EAAA;AAC7C,IAAA,OAAO,CAAC,sBAAsB,EAAE,4BAA4B,CAAC,CAAC,QAAQ,CACpE,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CACtC,CAAC;AACJ,CAAC;AAEK,SAAU,YAAY,CAAC,KAAc,EAAA;AACzC,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,qBAAqB,CAAC;AACzE,CAAC;AAEK,SAAU,eAAe,CAAC,KAAc,EAAA;AAC5C,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,wBAAwB,CAAC;AAC5E,CAAC;AAEK,SAAU,gBAAgB,CAAC,KAAc,EAAA;AAC7C,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,yBAAyB,CAAC;AAC7E,CAAC;AAEK,SAAU,QAAQ,CAAC,CAAU,EAAA;AACjC,IAAA,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/bson/package.json b/nodejs/node_modules/bson/package.json new file mode 100644 index 00000000..576698cd --- /dev/null +++ b/nodejs/node_modules/bson/package.json @@ -0,0 +1,120 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "files": [ + "lib", + "src", + "bson.d.ts", + "etc/prepare.js", + "vendor" + ], + "types": "bson.d.ts", + "version": "6.5.0", + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "license": "Apache-2.0", + "contributors": [], + "repository": "mongodb/js-bson", + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "devDependencies": { + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.40.5", + "@octokit/core": "^5.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-typescript": "^11.1.6", + "@types/chai": "^4.3.11", + "@types/mocha": "^10.0.6", + "@types/node": "^20.11.19", + "@types/sinon": "^17.0.3", + "@types/sinon-chai": "^3.2.12", + "@typescript-eslint/eslint-plugin": "^7.0.2", + "@typescript-eslint/parser": "^7.0.2", + "benchmark": "^2.1.4", + "chai": "^4.3.10", + "chalk": "^5.3.0", + "dbx-js-tools": "github:mongodb-js/dbx-js-tools", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-no-bigint-usage": "file:etc/eslint/no-bigint-usage", + "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-tsdoc": "^0.2.17", + "magic-string": "^0.30.7", + "mocha": "10.3.0", + "node-fetch": "^3.3.2", + "nyc": "^15.1.0", + "prettier": "^3.2.5", + "rollup": "^4.12.0", + "sinon": "^17.0.1", + "sinon-chai": "^3.7.0", + "source-map-support": "^0.5.21", + "standard-version": "^9.5.0", + "tar": "^6.2.0", + "ts-node": "^10.9.2", + "tsd": "^0.30.5", + "typescript": "^5.0.4", + "typescript-cached-transpile": "0.0.6", + "uuid": "^9.0.1" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + }, + "config": { + "native": false + }, + "main": "./lib/bson.cjs", + "module": "./lib/bson.mjs", + "exports": { + "import": { + "types": "./bson.d.ts", + "default": "./lib/bson.mjs" + }, + "require": { + "types": "./bson.d.ts", + "default": "./lib/bson.cjs" + }, + "react-native": "./lib/bson.rn.cjs", + "browser": "./lib/bson.mjs" + }, + "compass:exports": { + "import": "./lib/bson.cjs", + "require": "./lib/bson.cjs" + }, + "engines": { + "node": ">=16.20.1" + }, + "scripts": { + "pretest": "npm run build", + "test": "npm run check:node && npm run check:web && npm run check:web-no-bigint", + "check:node": "WEB=false mocha test/node", + "check:tsd": "npm run build:dts && tsd", + "check:web": "WEB=true mocha test/node", + "check:web-no-bigint": "WEB=true NO_BIGINT=true mocha test/node", + "check:granular-bench": "npm run build:bench && node ./test/bench/etc/run_granular_benchmarks.js", + "check:spec-bench": "npm run build:bench && node ./test/bench/lib/spec/bsonBench.js", + "build:bench": "cd test/bench && npx tsc", + "build:ts": "node ./node_modules/typescript/bin/tsc", + "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && node etc/clean_definition_files.cjs", + "build:bundle": "rollup -c rollup.config.mjs", + "build": "npm run build:dts && npm run build:bundle", + "check:lint": "eslint -v && eslint --ext '.js,.ts' --max-warnings=0 src test && npm run build:dts && npm run check:tsd", + "format": "eslint --ext '.js,.ts' src test --fix", + "check:coverage": "nyc --check-coverage npm run check:node", + "prepare": "node etc/prepare.js", + "release": "standard-version -i HISTORY.md" + } +} diff --git a/nodejs/node_modules/bson/src/binary.ts b/nodejs/node_modules/bson/src/binary.ts new file mode 100644 index 00000000..84182fb2 --- /dev/null +++ b/nodejs/node_modules/bson/src/binary.ts @@ -0,0 +1,472 @@ +import { type InspectFn, defaultInspect, isAnyArrayBuffer, isUint8Array } from './parser/utils'; +import type { EJSONOptions } from './extended_json'; +import { BSONError } from './error'; +import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants'; +import { ByteUtils } from './utils/byte_utils'; +import { BSONValue } from './bson_value'; + +/** @public */ +export type BinarySequence = Uint8Array | number[]; + +/** @public */ +export interface BinaryExtendedLegacy { + $type: string; + $binary: string; +} + +/** @public */ +export interface BinaryExtended { + $binary: { + subType: string; + base64: string; + }; +} + +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +export class Binary extends BSONValue { + get _bsontype(): 'Binary' { + return 'Binary'; + } + + /** + * Binary default subtype + * @internal + */ + private static readonly BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** Initial buffer default size */ + static readonly BUFFER_SIZE = 256; + /** Default BSON type */ + static readonly SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + static readonly SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + static readonly SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + static readonly SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + static readonly SUBTYPE_UUID = 4; + /** MD5 BSON type */ + static readonly SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + static readonly SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + static readonly SUBTYPE_COLUMN = 7; + /** Sensitive BSON type */ + static readonly SUBTYPE_SENSITIVE = 8; + /** User BSON type */ + static readonly SUBTYPE_USER_DEFINED = 128; + + buffer!: Uint8Array; + sub_type!: number; + position!: number; + + /** + * Create a new Binary instance. + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + constructor(buffer?: BinarySequence, subType?: number) { + super(); + if ( + !(buffer == null) && + typeof buffer === 'string' && + !ArrayBuffer.isView(buffer) && + !isAnyArrayBuffer(buffer) && + !Array.isArray(buffer) + ) { + throw new BSONError('Binary can only be constructed from Uint8Array or number[]'); + } + + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + + if (buffer == null) { + // create an empty binary buffer + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } else { + this.buffer = Array.isArray(buffer) + ? ByteUtils.fromNumberArray(buffer) + : ByteUtils.toLocalBufferType(buffer); + this.position = this.buffer.byteLength; + } + } + + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + put(byteValue: string | number | Uint8Array | number[]): void { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + + // Decode the byte value once + let decodedByte: number; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); + } else if (typeof byteValue === 'number') { + decodedByte = byteValue; + } else { + decodedByte = byteValue[0]; + } + + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + + /** + * Writes a buffer to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + write(sequence: BinarySequence, offset: number): void { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + + // Assign the new buffer + this.buffer = newSpace; + } + + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } else if (typeof sequence === 'string') { + throw new BSONError('input cannot be string'); + } + } + + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + read(position: number, length: number): BinarySequence { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + } + + /** returns a view of the binary value as a Uint8Array */ + value(): Uint8Array { + // Optimize to serialize for the situation where the data == size of buffer + return this.buffer.length === this.position + ? this.buffer + : this.buffer.subarray(0, this.position); + } + + /** the length of the binary sequence */ + length(): number { + return this.position; + } + + toJSON(): string { + return ByteUtils.toBase64(this.buffer); + } + + toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string { + if (encoding === 'hex') return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + } + + toUUID(): UUID { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID(this.buffer.slice(0, this.position)); + } + + throw new BSONError( + `Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.` + ); + } + + /** Creates an Binary instance from a hex digit string */ + static createFromHexString(hex: string, subType?: number): Binary { + return new Binary(ByteUtils.fromHex(hex), subType); + } + + /** Creates an Binary instance from a base64 string */ + static createFromBase64(base64: string, subType?: number): Binary { + return new Binary(ByteUtils.fromBase64(base64), subType); + } + + /** @internal */ + static fromExtendedJSON( + doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended, + options?: EJSONOptions + ): Binary { + options = options || {}; + let data: Uint8Array | undefined; + let type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary); + } else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } else if ('$uuid' in doc) { + type = 4; + data = UUID.bytesFromString(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + const base64Arg = inspect(base64, options); + const subTypeArg = inspect(this.sub_type, options); + return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; + } +} + +/** @public */ +export type UUIDExtended = { + $uuid: string; +}; + +const UUID_BYTE_LENGTH = 16; +const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; +const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; + +/** + * A class representation of the BSON UUID type. + * @public + */ +export class UUID extends Binary { + /** + * Create a UUID type + * + * When the argument to the constructor is omitted a random v4 UUID will be generated. + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + constructor(input?: string | Uint8Array | UUID) { + let bytes: Uint8Array; + if (input == null) { + bytes = UUID.generate(); + } else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } else if (typeof input === 'string') { + bytes = UUID.bytesFromString(input); + } else { + throw new BSONError( + 'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).' + ); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + } + + /** + * The UUID bytes + * @readonly + */ + get id(): Uint8Array { + return this.buffer; + } + + set id(value: Uint8Array) { + this.buffer = value; + } + + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + */ + toHexString(includeDashes = true): string { + if (includeDashes) { + return [ + ByteUtils.toHex(this.buffer.subarray(0, 4)), + ByteUtils.toHex(this.buffer.subarray(4, 6)), + ByteUtils.toHex(this.buffer.subarray(6, 8)), + ByteUtils.toHex(this.buffer.subarray(8, 10)), + ByteUtils.toHex(this.buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(this.buffer); + } + + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + toString(encoding?: 'hex' | 'base64'): string { + if (encoding === 'hex') return ByteUtils.toHex(this.id); + if (encoding === 'base64') return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + toJSON(): string { + return this.toHexString(); + } + + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + equals(otherId: string | Uint8Array | UUID): boolean { + if (!otherId) { + return false; + } + + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } catch { + return false; + } + } + + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Uint8Array { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + return bytes; + } + + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Uint8Array | UUID | Binary): boolean { + if (!input) { + return false; + } + + if (typeof input === 'string') { + return UUID.isValidUUIDString(input); + } + + if (isUint8Array(input)) { + return input.byteLength === UUID_BYTE_LENGTH; + } + + return ( + input._bsontype === 'Binary' && + input.sub_type === this.SUBTYPE_UUID && + input.buffer.byteLength === 16 + ); + } + + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + static override createFromHexString(hexString: string): UUID { + const buffer = UUID.bytesFromString(hexString); + return new UUID(buffer); + } + + /** Creates an UUID from a base64 string representation of an UUID. */ + static override createFromBase64(base64: string): UUID { + return new UUID(ByteUtils.fromBase64(base64)); + } + + /** @internal */ + static bytesFromString(representation: string) { + if (!UUID.isValidUUIDString(representation)) { + throw new BSONError( + 'UUID string representation must be 32 hex digits or canonical hyphenated representation' + ); + } + return ByteUtils.fromHex(representation.replace(/-/g, '')); + } + + /** + * @internal + * + * Validates a string to be a hex digit sequence with or without dashes. + * The canonical hyphenated representation of a uuid is hex in 8-4-4-4-12 groups. + */ + static isValidUUIDString(representation: string) { + return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); + } + + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * + */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + return `new UUID(${inspect(this.toHexString(), options)})`; + } +} diff --git a/nodejs/node_modules/bson/src/bson.ts b/nodejs/node_modules/bson/src/bson.ts new file mode 100644 index 00000000..5475e08e --- /dev/null +++ b/nodejs/node_modules/bson/src/bson.ts @@ -0,0 +1,248 @@ +import { Binary, UUID } from './binary'; +import { Code } from './code'; +import { DBRef } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { internalCalculateObjectSize } from './parser/calculate_size'; +// Parts of the parser +import { internalDeserialize, type DeserializeOptions } from './parser/deserializer'; +import { serializeInto, type SerializeOptions } from './parser/serializer'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; +import { ByteUtils } from './utils/byte_utils'; +import { NumberUtils } from './utils/number_utils'; +export type { UUIDExtended, BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary'; +export type { CodeExtended } from './code'; +export type { DBRefLike } from './db_ref'; +export type { Decimal128Extended } from './decimal128'; +export type { DoubleExtended } from './double'; +export type { EJSONOptions } from './extended_json'; +export type { Int32Extended } from './int_32'; +export type { LongExtended } from './long'; +export type { MaxKeyExtended } from './max_key'; +export type { MinKeyExtended } from './min_key'; +export type { ObjectIdExtended, ObjectIdLike } from './objectid'; +export type { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp'; +export type { BSONSymbolExtended } from './symbol'; +export type { LongWithoutOverrides, TimestampExtended, TimestampOverrides } from './timestamp'; +export type { LongWithoutOverridesClass } from './timestamp'; +export type { SerializeOptions, DeserializeOptions }; + +export { + Code, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128 +}; +export { BSONValue } from './bson_value'; +export { BSONError, BSONVersionError, BSONRuntimeError } from './error'; +export { BSONType } from './constants'; +export { EJSON } from './extended_json'; +export { onDemand } from './parser/on_demand/index'; + +/** @public */ +export interface Document { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; +} + +/** @internal */ +// Default Max Size +const MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +let buffer = ByteUtils.allocate(MAXSIZE); + +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer in bytes + * @public + */ +export function setInternalBufferSize(size: number): void { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} + +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +export function serialize(object: Document, options: SerializeOptions = {}): Uint8Array { + // Unpack the options + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + + // Attempt to serialize + const serializationIndex = serializeInto( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + null + ); + + // Create the final buffer + const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); + + // Copy into the finished buffer + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + + // Return the buffer + return finishedBuffer; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +export function serializeWithBufferAndIndex( + object: Document, + finalBuffer: Uint8Array, + options: SerializeOptions = {} +): number { + // Unpack the options + const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + const startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + const serializationIndex = serializeInto( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + null + ); + + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +export function deserialize(buffer: Uint8Array, options: DeserializeOptions = {}): Document { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} + +/** @public */ +export type CalculateObjectSizeOptions = Pick< + SerializeOptions, + 'serializeFunctions' | 'ignoreUndefined' +>; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +export function calculateObjectSize( + object: Document, + options: CalculateObjectSizeOptions = {} +): number { + options = options || {}; + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +export function deserializeStream( + data: Uint8Array | ArrayBuffer, + startIndex: number, + numberOfDocuments: number, + documents: Document[], + docStartIndex: number, + options: DeserializeOptions +): number { + const internalOptions = Object.assign( + { allowObjectSmallerThanBufferSize: true, index: 0 }, + options + ); + const bufferData = ByteUtils.toLocalBufferType(data); + + let index = startIndex; + // Loop over all documents + for (let i = 0; i < numberOfDocuments; i++) { + // Find size of the document + const size = NumberUtils.getInt32LE(bufferData, index); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} diff --git a/nodejs/node_modules/bson/src/bson_value.ts b/nodejs/node_modules/bson/src/bson_value.ts new file mode 100644 index 00000000..069764d8 --- /dev/null +++ b/nodejs/node_modules/bson/src/bson_value.ts @@ -0,0 +1,31 @@ +import { BSON_MAJOR_VERSION } from './constants'; +import { type InspectFn } from './parser/utils'; + +/** @public */ +export abstract class BSONValue { + /** @public */ + public abstract get _bsontype(): string; + + /** @internal */ + get [Symbol.for('@@mdb.bson.version')](): typeof BSON_MAJOR_VERSION { + return BSON_MAJOR_VERSION; + } + + [Symbol.for('nodejs.util.inspect.custom')]( + depth?: number, + options?: unknown, + inspect?: InspectFn + ): string { + return this.inspect(depth, options, inspect); + } + + /** + * @public + * Prints a human-readable string of BSON value information + * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify + */ + public abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string; + + /** @internal */ + abstract toExtendedJSON(): unknown; +} diff --git a/nodejs/node_modules/bson/src/code.ts b/nodejs/node_modules/bson/src/code.ts new file mode 100644 index 00000000..98b1ede9 --- /dev/null +++ b/nodejs/node_modules/bson/src/code.ts @@ -0,0 +1,69 @@ +import type { Document } from './bson'; +import { BSONValue } from './bson_value'; +import { type InspectFn, defaultInspect } from './parser/utils'; + +/** @public */ +export interface CodeExtended { + $code: string; + $scope?: Document; +} + +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +export class Code extends BSONValue { + get _bsontype(): 'Code' { + return 'Code'; + } + + code: string; + + // a code instance having a null scope is what determines whether + // it is BSONType 0x0D (just code) / 0x0F (code with scope) + scope: Document | null; + + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document | null) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + + toJSON(): { code: string; scope?: Document } { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + + return { code: this.code }; + } + + /** @internal */ + toExtendedJSON(): CodeExtended { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + + return { $code: this.code }; + } + + /** @internal */ + static fromExtendedJSON(doc: CodeExtended): Code { + return new Code(doc.$code, doc.$scope); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + let parametersString = inspect(this.code, options); + const multiLineFn = parametersString.includes('\n'); + if (this.scope != null) { + parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`; + } + const endingNewline = multiLineFn && this.scope === null; + return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`; + } +} diff --git a/nodejs/node_modules/bson/src/constants.ts b/nodejs/node_modules/bson/src/constants.ts new file mode 100644 index 00000000..a71f7993 --- /dev/null +++ b/nodejs/node_modules/bson/src/constants.ts @@ -0,0 +1,144 @@ +/** @internal */ +export const BSON_MAJOR_VERSION = 6 as const; + +/** @internal */ +export const BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +export const BSON_INT32_MIN = -0x80000000; +/** @internal */ +export const BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +export const BSON_INT64_MIN = -Math.pow(2, 63); + +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +export const JS_INT_MAX = Math.pow(2, 53); + +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +export const JS_INT_MIN = -Math.pow(2, 53); + +/** Number BSON Type @internal */ +export const BSON_DATA_NUMBER = 1; + +/** String BSON Type @internal */ +export const BSON_DATA_STRING = 2; + +/** Object BSON Type @internal */ +export const BSON_DATA_OBJECT = 3; + +/** Array BSON Type @internal */ +export const BSON_DATA_ARRAY = 4; + +/** Binary BSON Type @internal */ +export const BSON_DATA_BINARY = 5; + +/** Binary BSON Type @internal */ +export const BSON_DATA_UNDEFINED = 6; + +/** ObjectId BSON Type @internal */ +export const BSON_DATA_OID = 7; + +/** Boolean BSON Type @internal */ +export const BSON_DATA_BOOLEAN = 8; + +/** Date BSON Type @internal */ +export const BSON_DATA_DATE = 9; + +/** null BSON Type @internal */ +export const BSON_DATA_NULL = 10; + +/** RegExp BSON Type @internal */ +export const BSON_DATA_REGEXP = 11; + +/** Code BSON Type @internal */ +export const BSON_DATA_DBPOINTER = 12; + +/** Code BSON Type @internal */ +export const BSON_DATA_CODE = 13; + +/** Symbol BSON Type @internal */ +export const BSON_DATA_SYMBOL = 14; + +/** Code with Scope BSON Type @internal */ +export const BSON_DATA_CODE_W_SCOPE = 15; + +/** 32 bit Integer BSON Type @internal */ +export const BSON_DATA_INT = 16; + +/** Timestamp BSON Type @internal */ +export const BSON_DATA_TIMESTAMP = 17; + +/** Long BSON Type @internal */ +export const BSON_DATA_LONG = 18; + +/** Decimal128 BSON Type @internal */ +export const BSON_DATA_DECIMAL128 = 19; + +/** MinKey BSON Type @internal */ +export const BSON_DATA_MIN_KEY = 0xff; + +/** MaxKey BSON Type @internal */ +export const BSON_DATA_MAX_KEY = 0x7f; + +/** Binary Default Type @internal */ +export const BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** Binary Function Type @internal */ +export const BSON_BINARY_SUBTYPE_FUNCTION = 1; + +/** Binary Byte Array Type @internal */ +export const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +export const BSON_BINARY_SUBTYPE_UUID = 3; + +/** Binary UUID Type @internal */ +export const BSON_BINARY_SUBTYPE_UUID_NEW = 4; + +/** Binary MD5 Type @internal */ +export const BSON_BINARY_SUBTYPE_MD5 = 5; + +/** Encrypted BSON type @internal */ +export const BSON_BINARY_SUBTYPE_ENCRYPTED = 6; + +/** Column BSON type @internal */ +export const BSON_BINARY_SUBTYPE_COLUMN = 7; + +/** Sensitive BSON type @internal */ +export const BSON_BINARY_SUBTYPE_SENSITIVE = 8; + +/** Binary User Defined Type @internal */ +export const BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** @public */ +export const BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +} as const); + +/** @public */ +export type BSONType = (typeof BSONType)[keyof typeof BSONType]; diff --git a/nodejs/node_modules/bson/src/db_ref.ts b/nodejs/node_modules/bson/src/db_ref.ts new file mode 100644 index 00000000..fbb751f8 --- /dev/null +++ b/nodejs/node_modules/bson/src/db_ref.ts @@ -0,0 +1,128 @@ +import type { Document } from './bson'; +import { BSONValue } from './bson_value'; +import type { EJSONOptions } from './extended_json'; +import type { ObjectId } from './objectid'; +import { type InspectFn, defaultInspect } from './parser/utils'; + +/** @public */ +export interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** @internal */ +export function isDBRefLike(value: unknown): value is DBRefLike { + return ( + value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + // If '$db' is defined it MUST be a string, otherwise it should be absent + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')) + ); +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export class DBRef extends BSONValue { + get _bsontype(): 'DBRef' { + return 'DBRef'; + } + + collection!: string; + oid!: ObjectId; + db?: string; + fields!: Document; + + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + constructor(collection: string, oid: ObjectId, db?: string, fields?: Document) { + super(); + // check if namespace has been provided + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift()!; + } + + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + + /** @internal */ + get namespace(): string { + return this.collection; + } + + set namespace(value: string) { + this.collection = value; + } + + toJSON(): DBRefLike & Document { + const o = Object.assign( + { + $ref: this.collection, + $id: this.oid + }, + this.fields + ); + + if (this.db != null) o.$db = this.db; + return o; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): DBRefLike { + options = options || {}; + let o: DBRefLike = { + $ref: this.collection, + $id: this.oid + }; + + if (options.legacy) { + return o; + } + + if (this.db) o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + } + + /** @internal */ + static fromExtendedJSON(doc: DBRefLike): DBRef { + const copy = Object.assign({}, doc) as Partial; + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + + const args = [ + inspect(this.namespace, options), + inspect(this.oid, options), + ...(this.db ? [inspect(this.db, options)] : []), + ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []) + ]; + + args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; + + return `new DBRef(${args.join(', ')})`; + } +} diff --git a/nodejs/node_modules/bson/src/decimal128.ts b/nodejs/node_modules/bson/src/decimal128.ts new file mode 100644 index 00000000..806938e3 --- /dev/null +++ b/nodejs/node_modules/bson/src/decimal128.ts @@ -0,0 +1,855 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import { Long } from './long'; +import { type InspectFn, defaultInspect, isUint8Array } from './parser/utils'; +import { ByteUtils } from './utils/byte_utils'; + +const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +const EXPONENT_MAX = 6111; +const EXPONENT_MIN = -6176; +const EXPONENT_BIAS = 6176; +const MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +const NAN_BUFFER = ByteUtils.fromNumberArray( + [ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse() +); +// Infinity value bits 32 bit values (due to lack of longs) +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray( + [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse() +); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray( + [ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse() +); + +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +// Extract least significant 5 bits +const COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +const EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +const COMBINATION_INFINITY = 30; +// Value of combination field for NaN +const COMBINATION_NAN = 31; + +// Detect if the value is a digit +function isDigit(value: string): boolean { + return !isNaN(parseInt(value, 10)); +} + +// Divide two uint128 values +function divideu128(value: { parts: [number, number, number, number] }) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (let i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +} + +// Multiply two Long values and return the 128 bit value +function multiply64x2(left: Long, right: Long): { high: Long; low: Long } { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} + +function lessThan(left: Long, right: Long): boolean { + // Make values unsigned + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) return true; + } + + return false; +} + +function invalidErr(string: string, message: string) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} + +/** @public */ +export interface Decimal128Extended { + $numberDecimal: string; +} + +/** + * A class representation of the BSON Decimal128 type. + * @public + * @category BSONType + */ +export class Decimal128 extends BSONValue { + get _bsontype(): 'Decimal128' { + return 'Decimal128'; + } + + readonly bytes!: Uint8Array; + + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Uint8Array | string) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + static fromString(representation: string): Decimal128 { + return Decimal128._fromString(representation, { allowRounding: false }); + } + + /** + * Create a Decimal128 instance from a string representation, allowing for rounding to 34 + * significant digits + * + * @example Example of a number that will be rounded + * ```ts + * > let d = Decimal128.fromString('37.499999999999999196428571428571375') + * Uncaught: + * BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding + * at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11) + * at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25) + * at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27) + * + * > d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375') + * new Decimal128("37.49999999999999919642857142857138") + * ``` + * @param representation - a numeric string representation. + */ + static fromStringWithRounding(representation: string): Decimal128 { + return Decimal128._fromString(representation, { allowRounding: true }); + } + + private static _fromString(representation: string, options: { allowRounding: boolean }) { + // Parse state tracking + let isNegative = false; + let sawSign = false; + let sawRadix = false; + let foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + let significantDigits = 0; + // Total number of significand digits read + let nDigitsRead = 0; + // Total number of digits (no leading zeros) + let nDigits = 0; + // The number of the digits after radix + let radixPosition = 0; + // The index of the first non-zero in *str* + let firstNonZero = 0; + + // Digits Array + const digits = [0]; + // The number of digits in digits + let nDigitsStored = 0; + // Insertion pointer for digits + let digitsInsert = 0; + // The index of the last digit + let lastDigit = 0; + + // Exponent + let exponent = 0; + // The high 17 digits of the significand + let significandHigh = new Long(0, 0); + // The low 17 digits of the significand + let significandLow = new Long(0, 0); + // The biased exponent + let biasedExponent = 0; + + // Read index + let index = 0; + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + + // Results + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + + const unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) invalidErr(representation, 'missing exponent power'); + + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) invalidErr(representation, 'missing exponent base'); + + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + + // Get the negative or positive sign + if (representation[index] === '+' || representation[index] === '-') { + sawSign = true; + isNegative = representation[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + + // Read all the digits + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) invalidErr(representation, 'contains multiple periods'); + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < MAX_DIGITS) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) nDigits = nDigits + 1; + if (sawRadix) radixPosition = radixPosition + 1; + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + + // Read exponent if exists + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + const match = representation.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) return new Decimal128(NAN_BUFFER); + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (representation[index]) return new Decimal128(NAN_BUFFER); + + // Done reading input + // Find first non-zero digit in digits + if (!nDigitsStored) { + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while ( + representation[ + firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix) + ] === '0' + ) { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + if (lastDigit >= MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + if (significantDigits === 0) { + exponent = EXPONENT_MAX; + break; + } + + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + + if (options.allowRounding) { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (sawSign) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + let dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } else { + break; + } + } + } + } + } else { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0) { + if (significantDigits === 0) { + exponent = EXPONENT_MIN; + break; + } + + invalidErr(representation, 'exponent underflow'); + } + + if (nDigitsStored < nDigits) { + if ( + representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' && + significantDigits !== 0 + ) { + invalidErr(representation, 'inexact rounding'); + } + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + if (digits[lastDigit] !== 0) { + invalidErr(representation, 'inexact rounding'); + } + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + invalidErr(representation, 'overflow'); + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit + 1 < significantDigits) { + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix) { + firstNonZero = firstNonZero + 1; + } + // if saw sign, we need to increment again to account for - or + sign at start. + if (sawSign) { + firstNonZero = firstNonZero + 1; + } + + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + + if (roundDigit !== 0) { + invalidErr(representation, 'inexact rounding'); + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit < 17) { + let dIdx = 0; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + let dIdx = 0; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1)) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + const buffer = ByteUtils.allocateUnsafe(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low & 0xff; + buffer[index++] = (dec.low.low >> 8) & 0xff; + buffer[index++] = (dec.low.low >> 16) & 0xff; + buffer[index++] = (dec.low.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high & 0xff; + buffer[index++] = (dec.low.high >> 8) & 0xff; + buffer[index++] = (dec.low.high >> 16) & 0xff; + buffer[index++] = (dec.low.high >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low & 0xff; + buffer[index++] = (dec.high.low >> 8) & 0xff; + buffer[index++] = (dec.high.low >> 16) & 0xff; + buffer[index++] = (dec.high.low >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high & 0xff; + buffer[index++] = (dec.high.high >> 8) & 0xff; + buffer[index++] = (dec.high.high >> 16) & 0xff; + buffer[index++] = (dec.high.high >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + } + /** Create a string representation of the raw Decimal128 value */ + toString(): string { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // decoded biased exponent (14 bits) + let biased_exponent; + // the number of significand digits + let significand_digits = 0; + // the base-10 digits in the significand + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + let index = 0; + + // true if the number is zero + let is_zero = false; + + // the most significant significand bits (50-46) + let significand_msb; + // temporary storage for significand decoding + let significand128: { parts: [number, number, number, number] } = { parts: [0, 0, 0, 0] }; + // indexing variables + let j, k; + + // Output string + const string: string[] = []; + + // Unpack index + index = 0; + + // Buffer reference + const buffer = this.bytes; + + // Unpack the low 64bits into a long + // bits 96 - 127 + const low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + const midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + // bits 32 - 63 + const midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + const high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + // bits 1 - 5 + const combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + // unbiased exponent + const exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + let least_digits = 0; + // Perform the divide + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + // the exponent if scientific notation is used + const scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push(`${0}`); + if (exponent > 0) string.push(`E+${exponent}`); + else if (exponent < 0) string.push(`E${exponent}`); + return string.join(''); + } + + string.push(`${significand[index++]}`); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } else { + string.push(`${scientific_exponent}`); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } else { + let radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(`${significand[index++]}`); + } + } + } + + return string.join(''); + } + + toJSON(): Decimal128Extended { + return { $numberDecimal: this.toString() }; + } + + /** @internal */ + toExtendedJSON(): Decimal128Extended { + return { $numberDecimal: this.toString() }; + } + + /** @internal */ + static fromExtendedJSON(doc: Decimal128Extended): Decimal128 { + return Decimal128.fromString(doc.$numberDecimal); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + const d128string = inspect(this.toString(), options); + return `new Decimal128(${d128string})`; + } +} diff --git a/nodejs/node_modules/bson/src/double.ts b/nodejs/node_modules/bson/src/double.ts new file mode 100644 index 00000000..6dcec2e9 --- /dev/null +++ b/nodejs/node_modules/bson/src/double.ts @@ -0,0 +1,79 @@ +import { BSONValue } from './bson_value'; +import type { EJSONOptions } from './extended_json'; +import { type InspectFn, defaultInspect } from './parser/utils'; + +/** @public */ +export interface DoubleExtended { + $numberDouble: string; +} + +/** + * A class representation of the BSON Double type. + * @public + * @category BSONType + */ +export class Double extends BSONValue { + get _bsontype(): 'Double' { + return 'Double'; + } + + value!: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number) { + super(); + if ((value as unknown) instanceof Number) { + value = value.valueOf(); + } + + this.value = +value; + } + + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + valueOf(): number { + return this.value; + } + + toJSON(): number { + return this.value; + } + + toString(radix?: number): string { + return this.value.toString(radix); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): number | DoubleExtended { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + + if (Object.is(Math.sign(this.value), -0)) { + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + return { $numberDouble: '-0.0' }; + } + + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + + /** @internal */ + static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + return `new Double(${inspect(this.value, options)})`; + } +} diff --git a/nodejs/node_modules/bson/src/error.ts b/nodejs/node_modules/bson/src/error.ts new file mode 100644 index 00000000..7203f46b --- /dev/null +++ b/nodejs/node_modules/bson/src/error.ts @@ -0,0 +1,105 @@ +import { BSON_MAJOR_VERSION } from './constants'; + +/** + * @public + * @category Error + * + * `BSONError` objects are thrown when BSON encounters an error. + * + * This is the parent class for all the other errors thrown by this library. + */ +export class BSONError extends Error { + /** + * @internal + * The underlying algorithm for isBSONError may change to improve how strict it is + * about determining if an input is a BSONError. But it must remain backwards compatible + * with previous minors & patches of the current major version. + */ + protected get bsonError(): true { + return true; + } + + override get name(): string { + return 'BSONError'; + } + + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + } + + /** + * @public + * + * All errors thrown from the BSON library inherit from `BSONError`. + * This method can assist with determining if an error originates from the BSON library + * even if it does not pass an `instanceof` check against this class' constructor. + * + * @param value - any javascript value that needs type checking + */ + public static isBSONError(value: unknown): value is BSONError { + return ( + value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + // Do not access the following properties, just check existence + 'name' in value && + 'message' in value && + 'stack' in value + ); + } +} + +/** + * @public + * @category Error + */ +export class BSONVersionError extends BSONError { + get name(): 'BSONVersionError' { + return 'BSONVersionError'; + } + + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } +} + +/** + * @public + * @category Error + * + * An error generated when BSON functions encounter an unexpected input + * or reaches an unexpected/invalid internal state + * + */ +export class BSONRuntimeError extends BSONError { + get name(): 'BSONRuntimeError' { + return 'BSONRuntimeError'; + } + + constructor(message: string) { + super(message); + } +} + +/** + * @public + * @category Error + * + * @experimental + * + * An error generated when BSON bytes are invalid. + * Reports the offset the parser was able to reach before encountering the error. + */ +export class BSONOffsetError extends BSONError { + public get name(): 'BSONOffsetError' { + return 'BSONOffsetError'; + } + + public offset: number; + + constructor(message: string, offset: number) { + super(`${message}. offset: ${offset}`); + this.offset = offset; + } +} diff --git a/nodejs/node_modules/bson/src/extended_json.ts b/nodejs/node_modules/bson/src/extended_json.ts new file mode 100644 index 00000000..eb08b3c1 --- /dev/null +++ b/nodejs/node_modules/bson/src/extended_json.ts @@ -0,0 +1,515 @@ +import { Binary } from './binary'; +import type { Document } from './bson'; +import { Code } from './code'; +import { + BSON_INT32_MAX, + BSON_INT32_MIN, + BSON_INT64_MAX, + BSON_INT64_MIN, + BSON_MAJOR_VERSION +} from './constants'; +import { DBRef, isDBRefLike } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { BSONError, BSONRuntimeError, BSONVersionError } from './error'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { isDate, isRegExp, isMap } from './parser/utils'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; + +/** @public */ +export type EJSONOptions = { + /** + * Output using the Extended JSON v1 spec + * @defaultValue `false` + */ + legacy?: boolean; + /** + * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types + * @defaultValue `false` */ + relaxed?: boolean; + /** + * Enable native bigint support + * @defaultValue `false` + */ + useBigInt64?: boolean; +}; + +/** @internal */ +type BSONType = + | Binary + | Code + | DBRef + | Decimal128 + | Double + | Int32 + | Long + | MaxKey + | MinKey + | ObjectId + | BSONRegExp + | BSONSymbol + | Timestamp; + +function isBSONType(value: unknown): value is BSONType { + return ( + value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string' + ); +} + +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +const keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp +} as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value: any, options: EJSONOptions = {}) { + if (typeof value === 'number') { + // TODO(NODE-4377): EJSON js number handling diverges from BSON + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + + if (options.relaxed || options.legacy) { + return value; + } + + if (Number.isInteger(value) && !Object.is(value, -0)) { + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + // eslint-disable-next-line no-restricted-globals -- This is allowed here as useBigInt64=true + return BigInt(value); + } + return Long.fromNumber(value); + } + } + + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new Double(value); + } + + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') return value; + + // upgrade deprecated undefined to null + if (value.$undefined) return null; + + const keys = Object.keys(value).filter( + k => k.startsWith('$') && value[k] != null + ) as (keyof typeof keysToCodecs)[]; + for (let i = 0; i < keys.length; i++) { + const c = keysToCodecs[keys[i]]; + if (c) return c.fromExtendedJSON(value, options); + } + + if (value.$date != null) { + const d = value.$date; + const date = new Date(); + + if (options.legacy) { + if (typeof d === 'number') date.setTime(d); + else if (typeof d === 'string') date.setTime(Date.parse(d)); + else if (typeof d === 'bigint') date.setTime(Number(d)); + else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } else { + if (typeof d === 'string') date.setTime(Date.parse(d)); + else if (Long.isLong(d)) date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) date.setTime(d); + else if (typeof d === 'bigint') date.setTime(Number(d)); + else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + return date; + } + + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + + return Code.fromExtendedJSON(value); + } + + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof DBRef) return v; + + const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); + let valid = true; + dollarKeys.forEach(k => { + if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false; + }); + + // only make DBRef if $ keys are all valid + if (valid) return DBRef.fromExtendedJSON(v); + } + + return value; +} + +type EJSONSerializeOptions = EJSONOptions & { + seenObjects: { obj: unknown; propertyName: string }[]; +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array: any[], options: EJSONSerializeOptions): any[] { + return array.map((v: unknown, index: number) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } finally { + options.seenObjects.pop(); + } + }); +} + +function getISOString(date: Date) { + const isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value: any, options: EJSONSerializeOptions): any { + if (value instanceof Map || isMap(value)) { + const obj: Record = Object.create(null); + for (const [k, v] of value) { + if (typeof k !== 'string') { + throw new BSONError('Can only serialize maps with string keys'); + } + obj[k] = v; + } + + return serializeValue(obj, options); + } + + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + const index = options.seenObjects.findIndex(entry => entry.obj === value); + if (index !== -1) { + const props = options.seenObjects.map(entry => entry.propertyName); + const leadingPart = props + .slice(0, index) + .map(prop => `${prop} -> `) + .join(''); + const alreadySeen = props[index]; + const circularPart = + ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(prop => `${prop} -> `) + .join(''); + const current = props[props.length - 1]; + const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = '-'.repeat( + circularPart.length + (alreadySeen.length + current.length) / 2 - 1 + ); + + throw new BSONError( + 'Converting circular structure to EJSON:\n' + + ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + + ` ${leadingSpace}\\${dashes}/` + ); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + + if (Array.isArray(value)) return serializeArray(value, options); + + if (value === undefined) return null; + + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + // TODO(NODE-4377): EJSON js number handling diverges from BSON + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + + if (typeof value === 'bigint') { + /* eslint-disable no-restricted-globals -- This is allowed as we are accepting a bigint as input */ + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + /* eslint-enable */ + } + + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + + if (value != null && typeof value === 'object') return serializeDocument(value, options); + return value; +} + +const BSON_TYPE_MAPPINGS = { + Binary: (o: Binary) => new Binary(o.value(), o.sub_type), + Code: (o: Code) => new Code(o.code, o.scope), + DBRef: (o: DBRef) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), // "namespace" for 1.x library backwards compat + Decimal128: (o: Decimal128) => new Decimal128(o.bytes), + Double: (o: Double) => new Double(o.value), + Int32: (o: Int32) => new Int32(o.value), + Long: ( + o: Long & { + low_: number; + high_: number; + unsigned_: boolean | undefined; + } + ) => + Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, + o.low != null ? o.high : o.high_, + o.low != null ? o.unsigned : o.unsigned_ + ), + MaxKey: () => new MaxKey(), + MinKey: () => new MinKey(), + ObjectId: (o: ObjectId) => new ObjectId(o), + BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o: BSONSymbol) => new BSONSymbol(o.value), + Timestamp: (o: Timestamp) => Timestamp.fromBits(o.low, o.high) +} as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc: any, options: EJSONSerializeOptions) { + if (doc == null || typeof doc !== 'object') throw new BSONError('not an object instance'); + + const bsontype: BSONType['_bsontype'] = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + const _doc: Document = {}; + for (const name of Object.keys(doc)) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc[name], options); + if (name === '__proto__') { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } else { + _doc[name] = value; + } + } finally { + options.seenObjects.pop(); + } + } + return _doc; + } else if ( + doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let outDoc: any = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new DBRef( + serializeValue(outDoc.collection, options), + serializeValue(outDoc.oid, options), + serializeValue(outDoc.db, options), + serializeValue(outDoc.fields, options) + ); + } + + return outDoc.toExtendedJSON(options); + } else { + throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} + +/** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function parse(text: string, options?: EJSONOptions): any { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + return JSON.parse(text, (key, value) => { + if (key.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}` + ); + } + return deserializeValue(value, ejsonOptions); + }); +} + +/** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ +function stringify( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, + space?: string | number, + options?: EJSONOptions +): string { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer as Parameters[1], space); +} + +/** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function EJSONserialize(value: any, options?: EJSONOptions): Document { + options = options || {}; + return JSON.parse(stringify(value, options)); +} + +/** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} + +/** @public */ +const EJSON: { + parse: typeof parse; + stringify: typeof stringify; + serialize: typeof EJSONserialize; + deserialize: typeof EJSONdeserialize; +} = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); +export { EJSON }; diff --git a/nodejs/node_modules/bson/src/index.ts b/nodejs/node_modules/bson/src/index.ts new file mode 100644 index 00000000..5ef41575 --- /dev/null +++ b/nodejs/node_modules/bson/src/index.ts @@ -0,0 +1,19 @@ +import * as BSON from './bson'; + +// Export all named properties from BSON to support +// import { ObjectId, serialize } from 'bson'; +// const { ObjectId, serialize } = require('bson'); +export * from './bson'; + +// Export BSON as a namespace to support: +// import { BSON } from 'bson'; +// const { BSON } = require('bson'); +export { BSON }; + +// BSON does **NOT** have a default export + +// The following will crash in es module environments +// import BSON from 'bson'; + +// The following will work as expected, BSON as a namespace of all the APIs (BSON.ObjectId, BSON.serialize) +// const BSON = require('bson'); diff --git a/nodejs/node_modules/bson/src/int_32.ts b/nodejs/node_modules/bson/src/int_32.ts new file mode 100644 index 00000000..31b13c15 --- /dev/null +++ b/nodejs/node_modules/bson/src/int_32.ts @@ -0,0 +1,67 @@ +import { BSONValue } from './bson_value'; +import type { EJSONOptions } from './extended_json'; +import { type InspectFn, defaultInspect } from './parser/utils'; + +/** @public */ +export interface Int32Extended { + $numberInt: string; +} + +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +export class Int32 extends BSONValue { + get _bsontype(): 'Int32' { + return 'Int32'; + } + + value!: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string) { + super(); + if ((value as unknown) instanceof Number) { + value = value.valueOf(); + } + + this.value = +value | 0; + } + + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + valueOf(): number { + return this.value; + } + + toString(radix?: number): string { + return this.value.toString(radix); + } + + toJSON(): number { + return this.value; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): number | Int32Extended { + if (options && (options.relaxed || options.legacy)) return this.value; + return { $numberInt: this.value.toString() }; + } + + /** @internal */ + static fromExtendedJSON(doc: Int32Extended, options?: EJSONOptions): number | Int32 { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + return `new Int32(${inspect(this.value, options)})`; + } +} diff --git a/nodejs/node_modules/bson/src/long.ts b/nodejs/node_modules/bson/src/long.ts new file mode 100644 index 00000000..f05f71e6 --- /dev/null +++ b/nodejs/node_modules/bson/src/long.ts @@ -0,0 +1,1066 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import type { EJSONOptions } from './extended_json'; +import { type InspectFn, defaultInspect } from './parser/utils'; +import type { Timestamp } from './timestamp'; + +interface LongWASMHelpers { + /** Gets the high bits of the last operation performed */ + get_high(this: void): number; + div_u( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + div_s( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + rem_u( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + rem_s( + this: void, + lowBits: number, + highBits: number, + lowBitsDivisor: number, + highBitsDivisor: number + ): number; + mul( + this: void, + lowBits: number, + highBits: number, + lowBitsMultiplier: number, + highBitsMultiplier: number + ): number; +} + +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +let wasm: LongWASMHelpers | undefined = undefined; + +/* We do not want to have to include DOM types just for this check */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +declare const WebAssembly: any; + +try { + wasm = new WebAssembly.Instance( + new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11]) + ), + {} + ).exports as unknown as LongWASMHelpers; +} catch { + // no wasm support +} + +const TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + +/** A cache of the Long representations of small integer values. */ +const INT_CACHE: { [key: number]: Long } = {}; + +/** A cache of the Long representations of small unsigned integer values. */ +const UINT_CACHE: { [key: number]: Long } = {}; + +const MAX_INT64_STRING_LENGTH = 20; + +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; + +/** @public */ +export interface LongExtended { + $numberLong: string; +} + +/** + * A class representing a 64-bit integer + * @public + * @category BSONType + * @remarks + * The internal representation of a long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16 bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +export class Long extends BSONValue { + get _bsontype(): 'Long' { + return 'Long'; + } + + /** An indicator used to reliably determine if an object is a Long or not. */ + get __isLong__(): boolean { + return true; + } + + /** + * The high 32 bits as a signed value. + */ + high!: number; + + /** + * The low 32 bits as a signed value. + */ + low!: number; + + /** + * Whether unsigned or not. + */ + unsigned!: boolean; + + /** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See the from* functions below for more convenient ways of constructing Longs. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + constructor(low: number | bigint | string = 0, high?: number | boolean, unsigned?: boolean) { + super(); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); + } else { + this.low = low | 0; + this.high = (high as number) | 0; + this.unsigned = !!unsigned; + } + } + + static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + + /** Maximum unsigned value. */ + static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + static ZERO = Long.fromInt(0); + /** Unsigned zero. */ + static UZERO = Long.fromInt(0, true); + /** Signed one. */ + static ONE = Long.fromInt(1); + /** Unsigned one. */ + static UONE = Long.fromInt(1, true); + /** Signed negative one. */ + static NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long { + return new Long(lowBits, highBits, unsigned); + } + + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromInt(value: number, unsigned?: boolean): Long { + let obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) INT_CACHE[value] = obj; + return obj; + } + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromNumber(value: number, unsigned?: boolean): Long { + if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) return Long.UZERO; + if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE; + } + if (value < 0) return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + } + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBigInt(value: bigint, unsigned?: boolean): Long { + return Long.fromString(value.toString(), unsigned); + } + + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long { + if (str.length === 0) throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); + } else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) throw new BSONError('radix'); + + let p; + if ((p = str.indexOf('-')) > 0) throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + let result = Long.ZERO; + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesLE(bytes: number[], unsigned?: boolean): Long { + return new Long( + bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), + bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), + unsigned + ); + } + + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + static fromBytesBE(bytes: number[], unsigned?: boolean): Long { + return new Long( + (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], + (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], + unsigned + ); + } + + /** + * Tests if the specified object is a Long. + */ + static isLong(value: unknown): value is Long { + return ( + value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true + ); + } + + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + static fromValue( + val: number | string | { low: number; high: number; unsigned?: boolean }, + unsigned?: boolean + ): Long { + if (typeof val === 'number') return Long.fromNumber(val, unsigned); + if (typeof val === 'string') return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits( + val.low, + val.high, + typeof unsigned === 'boolean' ? unsigned : val.unsigned + ); + } + + /** Returns the sum of this and the specified Long. */ + add(addend: string | number | Long | Timestamp): Long { + if (!Long.isLong(addend)) addend = Long.fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + + const b48 = addend.high >>> 16; + const b32 = addend.high & 0xffff; + const b16 = addend.low >>> 16; + const b00 = addend.low & 0xffff; + + let c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + and(other: string | number | Long | Timestamp): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + + /** + * Compares this Long's value with the specified's. + * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: string | number | Long | Timestamp): 0 | 1 | -1 { + if (!Long.isLong(other)) other = Long.fromValue(other); + if (this.eq(other)) return 0; + const thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) return -1; + if (!thisNeg && otherNeg) return 1; + // At this point the sign bits are the same + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + + /** This is an alias of {@link Long.compare} */ + comp(other: string | number | Long | Timestamp): 0 | 1 | -1 { + return this.compare(other); + } + + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + divide(divisor: string | number | Long | Timestamp): Long { + if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); + if (divisor.isZero()) throw new BSONError('division by zero'); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if ( + !this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1 + ) { + // be consistent with non-wasm code path + return this; + } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) divisor = divisor.toUnsigned(); + if (divisor.gt(this)) return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + // eslint-disable-next-line @typescript-eslint/no-this-alias + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) approxRes = Long.ONE; + + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + + /**This is an alias of {@link Long.divide} */ + div(divisor: string | number | Long | Timestamp): Long { + return this.divide(divisor); + } + + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + equals(other: string | number | Long | Timestamp): boolean { + if (!Long.isLong(other)) other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + } + + /** This is an alias of {@link Long.equals} */ + eq(other: string | number | Long | Timestamp): boolean { + return this.equals(other); + } + + /** Gets the high 32 bits as a signed integer. */ + getHighBits(): number { + return this.high; + } + + /** Gets the high 32 bits as an unsigned integer. */ + getHighBitsUnsigned(): number { + return this.high >>> 0; + } + + /** Gets the low 32 bits as a signed integer. */ + getLowBits(): number { + return this.low; + } + + /** Gets the low 32 bits as an unsigned integer. */ + getLowBitsUnsigned(): number { + return this.low >>> 0; + } + + /** Gets the number of bits needed to represent the absolute value of this Long. */ + getNumBitsAbs(): number { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit: number; + for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + + /** Tests if this Long's value is greater than the specified's. */ + greaterThan(other: string | number | Long | Timestamp): boolean { + return this.comp(other) > 0; + } + + /** This is an alias of {@link Long.greaterThan} */ + gt(other: string | number | Long | Timestamp): boolean { + return this.greaterThan(other); + } + + /** Tests if this Long's value is greater than or equal the specified's. */ + greaterThanOrEqual(other: string | number | Long | Timestamp): boolean { + return this.comp(other) >= 0; + } + + /** This is an alias of {@link Long.greaterThanOrEqual} */ + gte(other: string | number | Long | Timestamp): boolean { + return this.greaterThanOrEqual(other); + } + /** This is an alias of {@link Long.greaterThanOrEqual} */ + ge(other: string | number | Long | Timestamp): boolean { + return this.greaterThanOrEqual(other); + } + + /** Tests if this Long's value is even. */ + isEven(): boolean { + return (this.low & 1) === 0; + } + + /** Tests if this Long's value is negative. */ + isNegative(): boolean { + return !this.unsigned && this.high < 0; + } + + /** Tests if this Long's value is odd. */ + isOdd(): boolean { + return (this.low & 1) === 1; + } + + /** Tests if this Long's value is positive. */ + isPositive(): boolean { + return this.unsigned || this.high >= 0; + } + + /** Tests if this Long's value equals zero. */ + isZero(): boolean { + return this.high === 0 && this.low === 0; + } + + /** Tests if this Long's value is less than the specified's. */ + lessThan(other: string | number | Long | Timestamp): boolean { + return this.comp(other) < 0; + } + + /** This is an alias of {@link Long#lessThan}. */ + lt(other: string | number | Long | Timestamp): boolean { + return this.lessThan(other); + } + + /** Tests if this Long's value is less than or equal the specified's. */ + lessThanOrEqual(other: string | number | Long | Timestamp): boolean { + return this.comp(other) <= 0; + } + + /** This is an alias of {@link Long.lessThanOrEqual} */ + lte(other: string | number | Long | Timestamp): boolean { + return this.lessThanOrEqual(other); + } + + /** Returns this Long modulo the specified. */ + modulo(divisor: string | number | Long | Timestamp): Long { + if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor); + + // use wasm support if present + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + return this.sub(this.div(divisor).mul(divisor)); + } + + /** This is an alias of {@link Long.modulo} */ + mod(divisor: string | number | Long | Timestamp): Long { + return this.modulo(divisor); + } + /** This is an alias of {@link Long.modulo} */ + rem(divisor: string | number | Long | Timestamp): Long { + return this.modulo(divisor); + } + + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + multiply(multiplier: string | number | Long | Timestamp): Long { + if (this.isZero()) return Long.ZERO; + if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier); + + // use wasm support if present + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + + if (multiplier.isZero()) return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); + else return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + const a48 = this.high >>> 16; + const a32 = this.high & 0xffff; + const a16 = this.low >>> 16; + const a00 = this.low & 0xffff; + + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 0xffff; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 0xffff; + + let c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + } + + /** This is an alias of {@link Long.multiply} */ + mul(multiplier: string | number | Long | Timestamp): Long { + return this.multiply(multiplier); + } + + /** Returns the Negation of this Long's value. */ + negate(): Long { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + + /** This is an alias of {@link Long.negate} */ + neg(): Long { + return this.negate(); + } + + /** Returns the bitwise NOT of this Long. */ + not(): Long { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + + /** Tests if this Long's value differs from the specified's. */ + notEquals(other: string | number | Long | Timestamp): boolean { + return !this.equals(other); + } + + /** This is an alias of {@link Long.notEquals} */ + neq(other: string | number | Long | Timestamp): boolean { + return this.notEquals(other); + } + /** This is an alias of {@link Long.notEquals} */ + ne(other: string | number | Long | Timestamp): boolean { + return this.notEquals(other); + } + + /** + * Returns the bitwise OR of this Long and the specified. + */ + or(other: number | string | Long): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftLeft(numBits: number | Long): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return Long.fromBits( + this.low << numBits, + (this.high << numBits) | (this.low >>> (32 - numBits)), + this.unsigned + ); + else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + } + + /** This is an alias of {@link Long.shiftLeft} */ + shl(numBits: number | Long): Long { + return this.shiftLeft(numBits); + } + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRight(numBits: number | Long): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + else if (numBits < 32) + return Long.fromBits( + (this.low >>> numBits) | (this.high << (32 - numBits)), + this.high >> numBits, + this.unsigned + ); + else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + } + + /** This is an alias of {@link Long.shiftRight} */ + shr(numBits: number | Long): Long { + return this.shiftRight(numBits); + } + + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + shiftRightUnsigned(numBits: Long | number): Long { + if (Long.isLong(numBits)) numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits, + this.unsigned + ); + } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned); + else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); + } + } + + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shr_u(numBits: number | Long): Long { + return this.shiftRightUnsigned(numBits); + } + /** This is an alias of {@link Long.shiftRightUnsigned} */ + shru(numBits: number | Long): Long { + return this.shiftRightUnsigned(numBits); + } + + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + subtract(subtrahend: string | number | Long | Timestamp): Long { + if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + + /** This is an alias of {@link Long.subtract} */ + sub(subtrahend: string | number | Long | Timestamp): Long { + return this.subtract(subtrahend); + } + + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + toInt(): number { + return this.unsigned ? this.low >>> 0 : this.low; + } + + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + toNumber(): number { + if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + + /** Converts the Long to a BigInt (arbitrary precision). */ + toBigInt(): bigint { + // eslint-disable-next-line no-restricted-globals -- This is allowed here as it is explicitly requesting a bigint + return BigInt(this.toString()); + } + + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + toBytes(le?: boolean): number[] { + return le ? this.toBytesLE() : this.toBytesBE(); + } + + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + toBytesLE(): number[] { + const hi = this.high, + lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + } + + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + toBytesBE(): number[] { + const hi = this.high, + lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + } + + /** + * Converts this Long to signed. + */ + toSigned(): Long { + if (!this.unsigned) return this; + return Long.fromBits(this.low, this.high, false); + } + + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + toString(radix?: number): string { + radix = radix || 10; + if (radix < 2 || 36 < radix) throw new BSONError('radix'); + if (this.isZero()) return '0'; + if (this.isNegative()) { + // Unsigned Longs are never negative + if (this.eq(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + const radixLong = Long.fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else return '-' + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + let rem: Long = this; + let result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) digits = '0' + digits; + result = '' + digits + result; + } + } + } + + /** Converts this Long to unsigned. */ + toUnsigned(): Long { + if (this.unsigned) return this; + return Long.fromBits(this.low, this.high, true); + } + + /** Returns the bitwise XOR of this Long and the given one. */ + xor(other: Long | number | string): Long { + if (!Long.isLong(other)) other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + + /** This is an alias of {@link Long.isZero} */ + eqz(): boolean { + return this.isZero(); + } + + /** This is an alias of {@link Long.lessThanOrEqual} */ + le(other: string | number | Long | Timestamp): boolean { + return this.lessThanOrEqual(other); + } + + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + toExtendedJSON(options?: EJSONOptions): number | LongExtended { + if (options && options.relaxed) return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON( + doc: { $numberLong: string }, + options?: EJSONOptions + ): number | Long | bigint { + const { useBigInt64 = false, relaxed = true } = { ...options }; + + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + + if (useBigInt64) { + /* eslint-disable no-restricted-globals -- Can use BigInt here as useBigInt64=true */ + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + /* eslint-enable */ + } + + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + const longVal = inspect(this.toString(), options); + const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ''; + return `new Long(${longVal}${unsignedVal})`; + } +} diff --git a/nodejs/node_modules/bson/src/max_key.ts b/nodejs/node_modules/bson/src/max_key.ts new file mode 100644 index 00000000..903f1d16 --- /dev/null +++ b/nodejs/node_modules/bson/src/max_key.ts @@ -0,0 +1,31 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export class MaxKey extends BSONValue { + get _bsontype(): 'MaxKey' { + return 'MaxKey'; + } + + /** @internal */ + toExtendedJSON(): MaxKeyExtended { + return { $maxKey: 1 }; + } + + /** @internal */ + static fromExtendedJSON(): MaxKey { + return new MaxKey(); + } + + inspect(): string { + return 'new MaxKey()'; + } +} diff --git a/nodejs/node_modules/bson/src/min_key.ts b/nodejs/node_modules/bson/src/min_key.ts new file mode 100644 index 00000000..244e645a --- /dev/null +++ b/nodejs/node_modules/bson/src/min_key.ts @@ -0,0 +1,31 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +export class MinKey extends BSONValue { + get _bsontype(): 'MinKey' { + return 'MinKey'; + } + + /** @internal */ + toExtendedJSON(): MinKeyExtended { + return { $minKey: 1 }; + } + + /** @internal */ + static fromExtendedJSON(): MinKey { + return new MinKey(); + } + + inspect(): string { + return 'new MinKey()'; + } +} diff --git a/nodejs/node_modules/bson/src/objectid.ts b/nodejs/node_modules/bson/src/objectid.ts new file mode 100644 index 00000000..98daecc8 --- /dev/null +++ b/nodejs/node_modules/bson/src/objectid.ts @@ -0,0 +1,361 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import { type InspectFn, defaultInspect } from './parser/utils'; +import { ByteUtils } from './utils/byte_utils'; +import { NumberUtils } from './utils/number_utils'; + +// Regular expression that checks for hex value +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Unique sequence for the current process (initialized on first use) +let PROCESS_UNIQUE: Uint8Array | null = null; + +/** @public */ +export interface ObjectIdLike { + id: string | Uint8Array; + __id?: string; + toHexString(): string; +} + +/** @public */ +export interface ObjectIdExtended { + $oid: string; +} + +/** + * A class representation of the BSON ObjectId type. + * @public + * @category BSONType + */ +export class ObjectId extends BSONValue { + get _bsontype(): 'ObjectId' { + return 'ObjectId'; + } + + /** @internal */ + private static index = Math.floor(Math.random() * 0xffffff); + + static cacheHexString: boolean; + + /** ObjectId Bytes @internal */ + private buffer!: Uint8Array; + /** ObjectId hexString cache @internal */ + private __id?: string; + + /** + * Create ObjectId from a number. + * + * @param inputId - A number. + * @deprecated Instead, use `static createFromTime()` to set a numeric value for the new ObjectId. + */ + constructor(inputId: number); + /** + * Create ObjectId from a 24 character hex string. + * + * @param inputId - A 24 character hex string. + */ + constructor(inputId: string); + /** + * Create ObjectId from the BSON ObjectId type. + * + * @param inputId - The BSON ObjectId type. + */ + constructor(inputId: ObjectId); + /** + * Create ObjectId from the object type that has the toHexString method. + * + * @param inputId - The ObjectIdLike type. + */ + constructor(inputId: ObjectIdLike); + /** + * Create ObjectId from a 12 byte binary Buffer. + * + * @param inputId - A 12 byte binary Buffer. + */ + constructor(inputId: Uint8Array); + /** To generate a new ObjectId, use ObjectId() with no argument. */ + constructor(); + /** + * Implementation overload. + * + * @param inputId - All input types that are used in the constructor implementation. + */ + constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array); + /** + * Create a new ObjectId. + * + * @param inputId - An input value to create a new ObjectId from. + */ + constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array) { + super(); + // workingId is set based on type of input and whether valid id exists for the input + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } else { + workingId = inputId.id; + } + } else { + workingId = inputId; + } + + // The following cases use workingId to construct an ObjectId + if (workingId == null || typeof workingId === 'number') { + // The most common use case (blank id, new objectId instance) + // Generate a new id + this.buffer = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + // If intstanceof matches we can escape calling ensure buffer in Node.js environments + this.buffer = ByteUtils.toLocalBufferType(workingId); + } else if (typeof workingId === 'string') { + if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this.buffer = ByteUtils.fromHex(workingId); + } else { + throw new BSONError( + 'input must be a 24 character hex string, 12 byte Uint8Array, or an integer' + ); + } + } else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + + /** + * The ObjectId bytes + * @readonly + */ + get id(): Uint8Array { + return this.buffer; + } + + set id(value: Uint8Array) { + this.buffer = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + + /** Returns the ObjectId id as a 24 lowercase character hex string representation */ + toHexString(): string { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + + const hexString = ByteUtils.toHex(this.id); + + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + + return hexString; + } + + /** + * Update the ObjectId index + * @internal + */ + private static getInc(): number { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + static generate(time?: number): Uint8Array { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocateUnsafe(12); + + // 4-byte timestamp + NumberUtils.setInt32BE(buffer, 0, time); + + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + + // 3-byte counter + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + + return buffer; + } + + /** + * Converts the id into a 24 character hex string for printing, unless encoding is provided. + * @param encoding - hex or base64 + */ + toString(encoding?: 'hex' | 'base64'): string { + // Is the id a buffer then use the buffer toString method to return the format + if (encoding === 'base64') return ByteUtils.toBase64(this.id); + if (encoding === 'hex') return this.toHexString(); + return this.toHexString(); + } + + /** Converts to its JSON the 24 character hex string representation. */ + toJSON(): string { + return this.toHexString(); + } + + /** @internal */ + private static is(variable: unknown): variable is ObjectId { + return ( + variable != null && + typeof variable === 'object' && + '_bsontype' in variable && + variable._bsontype === 'ObjectId' + ); + } + + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean { + if (otherId === undefined || otherId === null) { + return false; + } + + if (ObjectId.is(otherId)) { + return ( + this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer) + ); + } + + if (typeof otherId === 'string') { + return otherId.toLowerCase() === this.toHexString(); + } + + if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString(); + return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; + } + + return false; + } + + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + getTimestamp(): Date { + const timestamp = new Date(); + const time = NumberUtils.getUint32BE(this.buffer, 0); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + + /** @internal */ + static createPk(): ObjectId { + return new ObjectId(); + } + + /** @internal */ + serializeInto(uint8array: Uint8Array, index: number): 12 { + uint8array[index] = this.buffer[0]; + uint8array[index + 1] = this.buffer[1]; + uint8array[index + 2] = this.buffer[2]; + uint8array[index + 3] = this.buffer[3]; + uint8array[index + 4] = this.buffer[4]; + uint8array[index + 5] = this.buffer[5]; + uint8array[index + 6] = this.buffer[6]; + uint8array[index + 7] = this.buffer[7]; + uint8array[index + 8] = this.buffer[8]; + uint8array[index + 9] = this.buffer[9]; + uint8array[index + 10] = this.buffer[10]; + uint8array[index + 11] = this.buffer[11]; + return 12; + } + + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId. + * + * @param time - an integer number representing a number of seconds. + */ + static createFromTime(time: number): ObjectId { + const buffer = ByteUtils.allocate(12); + for (let i = 11; i >= 4; i--) buffer[i] = 0; + // Encode time into first 4 bytes + NumberUtils.setInt32BE(buffer, 0, time); + // Return the new objectId + return new ObjectId(buffer); + } + + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + static createFromHexString(hexString: string): ObjectId { + if (hexString?.length !== 24) { + throw new BSONError('hex string must be 24 characters'); + } + + return new ObjectId(ByteUtils.fromHex(hexString)); + } + + /** Creates an ObjectId instance from a base64 string */ + static createFromBase64(base64: string): ObjectId { + if (base64?.length !== 16) { + throw new BSONError('base64 string must be 16 characters'); + } + + return new ObjectId(ByteUtils.fromBase64(base64)); + } + + /** + * Checks if a value can be used to create a valid bson ObjectId + * @param id - any JS value + */ + static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean { + if (id == null) return false; + + try { + new ObjectId(id); + return true; + } catch { + return false; + } + } + + /** @internal */ + toExtendedJSON(): ObjectIdExtended { + if (this.toHexString) return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + + /** @internal */ + static fromExtendedJSON(doc: ObjectIdExtended): ObjectId { + return new ObjectId(doc.$oid); + } + + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + */ + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + return `new ObjectId(${inspect(this.toHexString(), options)})`; + } +} diff --git a/nodejs/node_modules/bson/src/parser/calculate_size.ts b/nodejs/node_modules/bson/src/parser/calculate_size.ts new file mode 100644 index 00000000..fd1e4a02 --- /dev/null +++ b/nodejs/node_modules/bson/src/parser/calculate_size.ts @@ -0,0 +1,211 @@ +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import { BSONVersionError } from '../error'; +import * as constants from '../constants'; +import { ByteUtils } from '../utils/byte_utils'; +import { isAnyArrayBuffer, isDate, isRegExp } from './utils'; + +export function internalCalculateObjectSize( + object: Document, + serializeFunctions?: boolean, + ignoreUndefined?: boolean +): number { + let totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + + // Calculate size + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +} + +/** @internal */ +function calculateElement( + name: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: any, + serializeFunctions = false, + isArray = false, + ignoreUndefined = false +) { + // If we have toBSON defined, override the current object + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if ( + Math.floor(value) === value && + value >= constants.JS_INT_MIN && + value <= constants.JS_INT_MAX + ) { + if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { + // 32 bit + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if ( + value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if ( + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value) + ) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength + ); + } else if ( + value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp' + ) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } else if (value._bsontype === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + ); + } + } else if (value._bsontype === 'Binary') { + const binary: Binary = value; + // Check what kind of subtype we have + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1) + ); + } + } else if (value._bsontype === 'Symbol') { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1 + ); + } else if (value._bsontype === 'DBRef') { + // Set up correct object for serialization + const ordered_values = Object.assign( + { + $ref: value.collection, + $id: value.oid + }, + value.fields + ); + + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if (value instanceof RegExp || isRegExp(value)) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value._bsontype === 'BSONRegExp') { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1 + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + if (serializeFunctions) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1 + ); + } + } + + return 0; +} diff --git a/nodejs/node_modules/bson/src/parser/deserializer.ts b/nodejs/node_modules/bson/src/parser/deserializer.ts new file mode 100644 index 00000000..ac278190 --- /dev/null +++ b/nodejs/node_modules/bson/src/parser/deserializer.ts @@ -0,0 +1,661 @@ +import { Binary, UUID } from '../binary'; +import type { Document } from '../bson'; +import { Code } from '../code'; +import * as constants from '../constants'; +import { DBRef, type DBRefLike, isDBRefLike } from '../db_ref'; +import { Decimal128 } from '../decimal128'; +import { Double } from '../double'; +import { BSONError } from '../error'; +import { Int32 } from '../int_32'; +import { Long } from '../long'; +import { MaxKey } from '../max_key'; +import { MinKey } from '../min_key'; +import { ObjectId } from '../objectid'; +import { BSONRegExp } from '../regexp'; +import { BSONSymbol } from '../symbol'; +import { Timestamp } from '../timestamp'; +import { ByteUtils } from '../utils/byte_utils'; +import { NumberUtils } from '../utils/number_utils'; +import { validateUtf8 } from '../validate_utf8'; + +/** @public */ +export interface DeserializeOptions { + /** + * when deserializing a Long return as a BigInt. + * @defaultValue `false` + */ + useBigInt64?: boolean; + /** + * when deserializing a Long will fit it into a Number if it's smaller than 53 bits. + * @defaultValue `true` + */ + promoteLongs?: boolean; + /** + * when deserializing a Binary will return it as a node.js Buffer instance. + * @defaultValue `false` + */ + promoteBuffers?: boolean; + /** + * when deserializing will promote BSON values to their Node.js closest equivalent types. + * @defaultValue `true` + */ + promoteValues?: boolean; + /** + * allow to specify if there what fields we wish to return as unserialized raw buffer. + * @defaultValue `null` + */ + fieldsAsRaw?: Document; + /** + * return BSON regular expressions as BSONRegExp instances. + * @defaultValue `false` + */ + bsonRegExp?: boolean; + /** + * allows the buffer to be larger than the parsed BSON object. + * @defaultValue `false` + */ + allowObjectSmallerThanBufferSize?: boolean; + /** + * Offset into buffer to begin reading document from + * @defaultValue `0` + */ + index?: number; + + raw?: boolean; + /** Allows for opt-out utf-8 validation for all keys or + * specified keys. Must be all true or all false. + * + * @example + * ```js + * // disables validation on all keys + * validation: { utf8: false } + * + * // enables validation only on specified keys a, b, and c + * validation: { utf8: { a: true, b: true, c: true } } + * + * // disables validation only on specified keys a, b + * validation: { utf8: { a: false, b: false } } + * ``` + */ + validation?: { utf8: boolean | Record | Record }; +} + +// Internal long versions +const JS_INT_MAX_LONG = Long.fromNumber(constants.JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(constants.JS_INT_MIN); + +export function internalDeserialize( + buffer: Uint8Array, + options: DeserializeOptions, + isArray?: boolean +): Document { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + // Read the document size + const size = NumberUtils.getInt32LE(buffer, index); + + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); + } + + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); + } + + if (size + index > buffer.byteLength) { + throw new BSONError( + `(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})` + ); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new BSONError( + "One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00" + ); + } + + // Start deserialization + return deserializeObject(buffer, index, options, isArray); +} + +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + +function deserializeObject( + buffer: Uint8Array, + index: number, + options: DeserializeOptions, + isArray = false +) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + const raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + + // Ensures default validation option if none given + const validation = options.validation == null ? { utf8: true } : options.validation; + + // Shows if global utf-8 validation is enabled or disabled + let globalUTFValidation = true; + // Reflects utf-8 validation setting regardless of global or specific key validation + let validationSetting: boolean; + // Set of keys either to enable or disable validation on + let utf8KeysSet; + + // Check for boolean uniformity and empty validation option + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + // Ensures boolean uniformity in utf-8 validation (all true or all false) + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + + // Add keys to set that will either be validated or not based on validationSetting + if (!globalUTFValidation) { + utf8KeysSet = new Set(); + + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + + // Set the start index + const startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new BSONError('corrupt bson message < 5 bytes long'); + + // Read the document size + const size = NumberUtils.getInt32LE(buffer, index); + index += 4; + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new BSONError('corrupt bson message'); + + // Create holding object + const object: Document = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + let arrayIndex = 0; + const done = false; + + let isPossibleDBRef = isArray ? false : null; + + // While we have more left data left keep parsing + while (!done) { + // Read the type + const elementType = buffer[index++]; + + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + let i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) throw new BSONError('Bad BSON Document: illegal CString'); + + // Represents the key + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false); + + // shouldValidateKey is true if the key should be validated, false otherwise + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet?.has(name)) { + shouldValidateKey = validationSetting; + } else { + shouldValidateKey = !validationSetting; + } + + if (isPossibleDBRef !== false && (name as string)[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name as string); + } + let value; + + index = i + 1; + + if (elementType === constants.BSON_DATA_STRING) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_OID) { + const oid = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) oid[i] = buffer[index + i]; + value = new ObjectId(oid); + index = index + 12; + } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { + value = new Int32(NumberUtils.getInt32LE(buffer, index)); + index += 4; + } else if (elementType === constants.BSON_DATA_INT) { + value = NumberUtils.getInt32LE(buffer, index); + index += 4; + } else if (elementType === constants.BSON_DATA_NUMBER) { + value = NumberUtils.getFloat64LE(buffer, index); + index += 8; + if (promoteValues === false) value = new Double(value); + } else if (elementType === constants.BSON_DATA_DATE) { + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + + value = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === constants.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } else if (elementType === constants.BSON_DATA_OBJECT) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new BSONError('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + value = buffer.slice(index, index + objectSize); + } else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, objectOptions, false); + } + + index = index + objectSize; + } else if (elementType === constants.BSON_DATA_ARRAY) { + const _index = index; + const objectSize = NumberUtils.getInt32LE(buffer, index); + let arrayOptions: DeserializeOptions = options; + + // Stop index + const stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, raw: true }; + } + + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new BSONError('invalid array terminator byte'); + if (index !== stopIndex) throw new BSONError('corrupted array bson'); + } else if (elementType === constants.BSON_DATA_UNDEFINED) { + value = undefined; + } else if (elementType === constants.BSON_DATA_NULL) { + value = null; + } else if (elementType === constants.BSON_DATA_LONG) { + if (useBigInt64) { + value = NumberUtils.getBigInt64LE(buffer, index); + index += 8; + } else { + // Unpack the low and high bits + const lowBits = NumberUtils.getInt32LE(buffer, index); + const highBits = NumberUtils.getInt32LE(buffer, index + 4); + index += 8; + + const long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + value = long; + } + } + } else if (elementType === constants.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + const bytes = ByteUtils.allocateUnsafe(16); + // Copy the next 16 bytes into the bytes buffer + for (let i = 0; i < 16; i++) bytes[i] = buffer[index + i]; + // Update index + index = index + 16; + // Assign the new Decimal128 value + value = new Decimal128(bytes); + } else if (elementType === constants.BSON_DATA_BINARY) { + let binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + const totalBinarySize = binarySize; + const subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new BSONError('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + + if (promoteBuffers && promoteValues) { + value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } else { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + + if (promoteBuffers && promoteValues) { + value = ByteUtils.allocateUnsafe(binarySize); + // Copy the data + for (i = 0; i < binarySize; i++) { + value[i] = buffer[index + i]; + } + } else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { + value = value.toUUID(); + } + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const source = ByteUtils.toUTF8(buffer, index, i, false); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + + // For each option add the corresponding one for javascript + const optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + value = new RegExp(source, optionsArray.join('')); + } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const source = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); + // Return the C string + const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false); + index = i + 1; + + // Set the object + value = new BSONRegExp(source, regExpOptions); + } else if (elementType === constants.BSON_DATA_SYMBOL) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new BSONSymbol(symbol); + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_TIMESTAMP) { + value = new Timestamp({ + i: NumberUtils.getUint32LE(buffer, index), + t: NumberUtils.getUint32LE(buffer, index + 4) + }); + index += 8; + } else if (elementType === constants.BSON_DATA_MIN_KEY) { + value = new MinKey(); + } else if (elementType === constants.BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } else if (elementType === constants.BSON_DATA_CODE) { + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + const functionString = ByteUtils.toUTF8( + buffer, + index, + index + stringSize - 1, + shouldValidateKey + ); + + value = new Code(functionString); + + // Update parse index position + index = index + stringSize; + } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) { + const totalSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) { + throw new BSONError('bad string length in bson'); + } + + // Javascript function + const functionString = ByteUtils.toUTF8( + buffer, + index, + index + stringSize - 1, + shouldValidateKey + ); + // Update parse index position + index = index + stringSize; + // Parse the element + const _index = index; + // Decode the size of the object document + const objectSize = NumberUtils.getInt32LE(buffer, index); + // Decode the scope object + const scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is too short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + + // Check if totalSize field is too long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + + value = new Code(functionString, scopeObject); + } else if (elementType === constants.BSON_DATA_DBPOINTER) { + // Get the code string size + const stringSize = NumberUtils.getInt32LE(buffer, index); + index += 4; + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new BSONError('bad string length in bson'); + // Namespace + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, false); + // Update parse index position + index = index + stringSize; + + // Read the oid + const oidBuffer = ByteUtils.allocateUnsafe(12); + for (let i = 0; i < 12; i++) oidBuffer[i] = buffer[index + i]; + const oid = new ObjectId(oidBuffer); + + // Update the index + index = index + 12; + + // Upgrade to DBRef type + value = new DBRef(namespace, oid); + } else { + throw new BSONError( + `Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"` + ); + } + if (name === '__proto__') { + Object.defineProperty(object, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } else { + object[name] = value; + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) return object; + + if (isDBRefLike(object)) { + const copy = Object.assign({}, object) as Partial; + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + + return object; +} diff --git a/nodejs/node_modules/bson/src/parser/on_demand/index.ts b/nodejs/node_modules/bson/src/parser/on_demand/index.ts new file mode 100644 index 00000000..bd08cdb8 --- /dev/null +++ b/nodejs/node_modules/bson/src/parser/on_demand/index.ts @@ -0,0 +1,28 @@ +import { type BSONError, BSONOffsetError } from '../../error'; +import { type BSONElement, parseToElements } from './parse_to_elements'; +/** + * @experimental + * @public + * + * A new set of BSON APIs that are currently experimental and not intended for production use. + */ +export type OnDemand = { + BSONOffsetError: { + new (message: string, offset: number): BSONOffsetError; + isBSONError(value: unknown): value is BSONError; + }; + parseToElements: (this: void, bytes: Uint8Array, startOffset?: number) => Iterable; +}; + +/** + * @experimental + * @public + */ +const onDemand: OnDemand = Object.create(null); + +onDemand.parseToElements = parseToElements; +onDemand.BSONOffsetError = BSONOffsetError; + +Object.freeze(onDemand); + +export { onDemand }; diff --git a/nodejs/node_modules/bson/src/parser/on_demand/parse_to_elements.ts b/nodejs/node_modules/bson/src/parser/on_demand/parse_to_elements.ts new file mode 100644 index 00000000..bc3c107d --- /dev/null +++ b/nodejs/node_modules/bson/src/parser/on_demand/parse_to_elements.ts @@ -0,0 +1,174 @@ +/* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */ +import { BSONOffsetError } from '../../error'; + +/** + * @internal + * + * @remarks + * - This enum is const so the code we produce will inline the numbers + * - `minKey` is set to 255 so unsigned comparisons succeed + * - Modify with caution, double check the bundle contains literals + */ +const enum t { + double = 1, + string = 2, + object = 3, + array = 4, + binData = 5, + undefined = 6, + objectId = 7, + bool = 8, + date = 9, + null = 10, + regex = 11, + dbPointer = 12, + javascript = 13, + symbol = 14, + javascriptWithScope = 15, + int = 16, + timestamp = 17, + long = 18, + decimal = 19, + minKey = 255, + maxKey = 127 +} + +/** + * @public + * @experimental + */ +export type BSONElement = [ + type: number, + nameOffset: number, + nameLength: number, + offset: number, + length: number +]; + +/** Parses a int32 little-endian at offset, throws if it is negative */ +function getSize(source: Uint8Array, offset: number): number { + if (source[offset + 3] > 127) { + throw new BSONOffsetError('BSON size cannot be negative', offset); + } + return ( + source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24) + ); +} + +/** + * Searches for null terminator of a BSON element's value (Never the document null terminator) + * **Does not** bounds check since this should **ONLY** be used within parseToElements which has asserted that `bytes` ends with a `0x00`. + * So this will at most iterate to the document's terminator and error if that is the offset reached. + */ +function findNull(bytes: Uint8Array, offset: number): number { + let nullTerminatorOffset = offset; + + for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++); + + if (nullTerminatorOffset === bytes.length - 1) { + // We reached the null terminator of the document, not a value's + throw new BSONOffsetError('Null terminator not found', offset); + } + + return nullTerminatorOffset; +} + +/** + * @public + * @experimental + */ +export function parseToElements(bytes: Uint8Array, startOffset = 0): Iterable { + if (bytes.length < 5) { + throw new BSONOffsetError( + `Input must be at least 5 bytes, got ${bytes.length} bytes`, + startOffset + ); + } + + const documentSize = getSize(bytes, startOffset); + + if (documentSize > bytes.length - startOffset) { + throw new BSONOffsetError( + `Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, + startOffset + ); + } + + if (bytes[startOffset + documentSize - 1] !== 0x00) { + throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize); + } + + const elements: BSONElement[] = []; + let offset = startOffset + 4; + + while (offset <= documentSize + startOffset) { + const type = bytes[offset]; + offset += 1; + + if (type === 0) { + if (offset - startOffset !== documentSize) { + throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); + } + break; + } + + const nameOffset = offset; + const nameLength = findNull(bytes, offset) - nameOffset; + offset += nameLength + 1; + + let length: number; + + if (type === t.double || type === t.long || type === t.date || type === t.timestamp) { + length = 8; + } else if (type === t.int) { + length = 4; + } else if (type === t.objectId) { + length = 12; + } else if (type === t.decimal) { + length = 16; + } else if (type === t.bool) { + length = 1; + } else if (type === t.null || type === t.undefined || type === t.maxKey || type === t.minKey) { + length = 0; + } + // Needs a size calculation + else if (type === t.regex) { + length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; + } else if (type === t.object || type === t.array || type === t.javascriptWithScope) { + length = getSize(bytes, offset); + } else if ( + type === t.string || + type === t.binData || + type === t.dbPointer || + type === t.javascript || + type === t.symbol + ) { + length = getSize(bytes, offset) + 4; + if (type === t.binData) { + // binary subtype + length += 1; + } + if (type === t.dbPointer) { + // dbPointer's objectId + length += 12; + } + } else { + throw new BSONOffsetError( + `Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, + offset + ); + } + + if (length > documentSize) { + throw new BSONOffsetError('value reports length larger than document', offset); + } + + elements.push([type, nameOffset, nameLength, offset, length]); + offset += length; + } + + return elements; +} diff --git a/nodejs/node_modules/bson/src/parser/serializer.ts b/nodejs/node_modules/bson/src/parser/serializer.ts new file mode 100644 index 00000000..86490798 --- /dev/null +++ b/nodejs/node_modules/bson/src/parser/serializer.ts @@ -0,0 +1,942 @@ +import { Binary } from '../binary'; +import type { BSONSymbol, DBRef, Document, MaxKey } from '../bson'; +import type { Code } from '../code'; +import * as constants from '../constants'; +import type { DBRefLike } from '../db_ref'; +import type { Decimal128 } from '../decimal128'; +import type { Double } from '../double'; +import { BSONError, BSONVersionError } from '../error'; +import type { Int32 } from '../int_32'; +import { Long } from '../long'; +import type { MinKey } from '../min_key'; +import type { ObjectId } from '../objectid'; +import type { BSONRegExp } from '../regexp'; +import { ByteUtils } from '../utils/byte_utils'; +import { NumberUtils } from '../utils/number_utils'; +import { isAnyArrayBuffer, isDate, isMap, isRegExp, isUint8Array } from './utils'; + +/** @public */ +export interface SerializeOptions { + /** + * the serializer will check if keys are valid. + * @defaultValue `false` + */ + checkKeys?: boolean; + /** + * serialize the javascript functions + * @defaultValue `false` + */ + serializeFunctions?: boolean; + /** + * serialize will not emit undefined fields + * note that the driver sets this to `false` + * @defaultValue `true` + */ + ignoreUndefined?: boolean; + /** @internal Resize internal buffer */ + minInternalBufferSize?: number; + /** + * the index in the buffer where we wish to start serializing into + * @defaultValue `0` + */ + index?: number; +} + +const regexp = /\x00/; // eslint-disable-line no-control-regex +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); + +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ + +function serializeString(buffer: Uint8Array, key: string, value: string, index: number) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + // Write the size of the string to buffer + NumberUtils.setInt32LE(buffer, index, size + 1); + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +function serializeNumber(buffer: Uint8Array, key: string, value: number, index: number) { + const isNegativeZero = Object.is(value, -0); + + const type = + !isNegativeZero && + Number.isSafeInteger(value) && + value <= constants.BSON_INT32_MAX && + value >= constants.BSON_INT32_MIN + ? constants.BSON_DATA_INT + : constants.BSON_DATA_NUMBER; + + buffer[index++] = type; + + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + + if (type === constants.BSON_DATA_INT) { + index += NumberUtils.setInt32LE(buffer, index, value); + } else { + index += NumberUtils.setFloat64LE(buffer, index, value); + } + + return index; +} + +function serializeBigInt(buffer: Uint8Array, key: string, value: bigint, index: number) { + buffer[index++] = constants.BSON_DATA_LONG; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index += numberOfWrittenBytes; + buffer[index++] = 0; + + index += NumberUtils.setBigInt64LE(buffer, index, value); + + return index; +} + +function serializeNull(buffer: Uint8Array, key: string, _: unknown, index: number) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeBoolean(buffer: Uint8Array, key: string, value: boolean, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +function serializeDate(buffer: Uint8Array, key: string, value: Date, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + // Encode low bits + index += NumberUtils.setInt32LE(buffer, index, lowBits); + // Encode high bits + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} + +function serializeRegExp(buffer: Uint8Array, key: string, value: RegExp, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.global) buffer[index++] = 0x73; // s + if (value.multiline) buffer[index++] = 0x6d; // m + + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeBSONRegExp(buffer: Uint8Array, key: string, value: BSONRegExp, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + // Write zero + buffer[index++] = 0x00; + // Write the options + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeMinMax(buffer: Uint8Array, key: string, value: MinKey | MaxKey, index: number) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = constants.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = constants.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = constants.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeObjectId(buffer: Uint8Array, key: string, value: ObjectId, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + index += value.serializeInto(buffer, index); + + // Adjust index + return index; +} + +function serializeBuffer(buffer: Uint8Array, key: string, value: Uint8Array, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + const size = value.length; + // Write the size of the string to buffer + index += NumberUtils.setInt32LE(buffer, index, size); + // Write the default subtype + buffer[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + if (size <= 16) { + for (let i = 0; i < size; i++) buffer[index + i] = value[i]; + } else { + buffer.set(value, index); + } + // Adjust the index + index = index + size; + return index; +} + +function serializeObject( + buffer: Uint8Array, + key: string, + value: Document, + index: number, + checkKeys: boolean, + depth: number, + serializeFunctions: boolean, + ignoreUndefined: boolean, + path: Set +) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + + path.add(value); + + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + + path.delete(value); + + return endIndex; +} + +function serializeDecimal128(buffer: Uint8Array, key: string, value: Decimal128, index: number) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + for (let i = 0; i < 16; i++) buffer[index + i] = value.bytes[i]; + return index + 16; +} + +function serializeLong(buffer: Uint8Array, key: string, value: Long, index: number) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + // Encode low bits + index += NumberUtils.setInt32LE(buffer, index, lowBits); + // Encode high bits + index += NumberUtils.setInt32LE(buffer, index, highBits); + return index; +} + +function serializeInt32(buffer: Uint8Array, key: string, value: Int32 | number, index: number) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + index += NumberUtils.setInt32LE(buffer, index, value); + return index; +} + +function serializeDouble(buffer: Uint8Array, key: string, value: Double, index: number) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write float + index += NumberUtils.setFloat64LE(buffer, index, value.value); + + return index; +} + +function serializeFunction(buffer: Uint8Array, key: string, value: Function, index: number) { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.toString(); + + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + // Write the size of the string to buffer + NumberUtils.setInt32LE(buffer, index, size); + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +function serializeCode( + buffer: Uint8Array, + key: string, + value: Code, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + path: Set +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + let startIndex = index; + + // Serialize the function + // Get the function string + const functionString = value.code; + // Index adjustment + index = index + 4; + // Write string into buffer + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + // Write the size of the string to buffer + NumberUtils.setInt32LE(buffer, index, codeSize); + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // Serialize the scope value + const endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + index = endIndex - 1; + + // Writ the total + const totalSize = endIndex - startIndex; + + // Write the total size of the object + startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize); + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.code.toString(); + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + // Write the size of the string to buffer + NumberUtils.setInt32LE(buffer, index, size); + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +function serializeBinary(buffer: Uint8Array, key: string, value: Binary, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + const data = value.buffer; + // Calculate size + let size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + index += NumberUtils.setInt32LE(buffer, index, size); + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + index += NumberUtils.setInt32LE(buffer, index, size); + } + + if (size <= 16) { + for (let i = 0; i < size; i++) buffer[index + i] = data[i]; + } else { + buffer.set(data, index); + } + // Adjust the index + index = index + value.position; + return index; +} + +function serializeSymbol(buffer: Uint8Array, key: string, value: BSONSymbol, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + // Write the size of the string to buffer + NumberUtils.setInt32LE(buffer, index, size); + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +function serializeDBRef( + buffer: Uint8Array, + key: string, + value: DBRef, + index: number, + depth: number, + serializeFunctions: boolean, + path: Set +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + let startIndex = index; + let output: DBRefLike = { + $ref: value.collection || value.namespace, // "namespace" was what library 1.x called "collection" + $id: value.oid + }; + + if (value.db != null) { + output.$db = value.db; + } + + output = Object.assign(output, value.fields); + const endIndex = serializeInto( + buffer, + output, + false, + index, + depth + 1, + serializeFunctions, + true, + path + ); + + // Calculate object size + const size = endIndex - startIndex; + // Write the size + startIndex += NumberUtils.setInt32LE(buffer, index, size); + // Set index + return endIndex; +} + +export function serializeInto( + buffer: Uint8Array, + object: Document, + checkKeys: boolean, + startingIndex: number, + depth: number, + serializeFunctions: boolean, + ignoreUndefined: boolean, + path: Set | null +): number { + if (path == null) { + // We are at the root input + if (object == null) { + // ONLY the root should turn into an empty document + // BSON Empty document has a size of 5 (LE) + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + // All documents end with null terminator + buffer[4] = 0x00; + return 5; + } + + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } else if ( + isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object) + ) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + + path = new Set(); + } + + // Push the object to the path + path.add(object); + + // Start place to serialize into + let index = startingIndex + 4; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + + // Is there an override value + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (typeof value === 'object' && value._bsontype == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + + while (!done) { + // Unpack the next entry + const entry = iterator.next(); + done = !!entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + const key = entry.value[0]; + let value = entry.value[1]; + + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + // Check the type of the value + const type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value._bsontype == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value._bsontype === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } else { + if (typeof object?.toBSON === 'function') { + // Provided a custom serialization method + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + + // Iterate over all the keys + for (const key of Object.keys(object)) { + let value = object[key]; + // Is there an override value + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + + // Check the type of the value + const type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } else if (key.includes('.')) { + throw new BSONError('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value._bsontype == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (type === 'object' && value._bsontype === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value._bsontype === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value._bsontype === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } else if (value._bsontype === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value._bsontype === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } else if (typeof value._bsontype !== 'undefined') { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + + // Remove the path + path.delete(object); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + const size = index - startingIndex; + // Write the size of the object + startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size); + return index; +} diff --git a/nodejs/node_modules/bson/src/parser/utils.ts b/nodejs/node_modules/bson/src/parser/utils.ts new file mode 100644 index 00000000..0b27249e --- /dev/null +++ b/nodejs/node_modules/bson/src/parser/utils.ts @@ -0,0 +1,56 @@ +export function isAnyArrayBuffer(value: unknown): value is ArrayBuffer { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes( + Object.prototype.toString.call(value) + ); +} + +export function isUint8Array(value: unknown): value is Uint8Array { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} + +export function isBigInt64Array(value: unknown): value is BigInt64Array { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} + +export function isBigUInt64Array(value: unknown): value is BigUint64Array { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} + +export function isRegExp(d: unknown): d is RegExp { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +export function isMap(d: unknown): d is Map { + return Object.prototype.toString.call(d) === '[object Map]'; +} + +export function isDate(d: unknown): d is Date { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +export type InspectFn = (x: unknown, options?: unknown) => string; +export function defaultInspect(x: unknown, _options?: unknown): string { + return JSON.stringify(x, (k: string, v: unknown) => { + if (typeof v === 'bigint') { + return { $numberLong: `${v}` }; + } else if (isMap(v)) { + return Object.fromEntries(v); + } + return v; + }); +} + +/** @internal */ +type StylizeFunction = (x: string, style: string) => string; +/** @internal */ +export function getStylizeFunction(options?: unknown): StylizeFunction | undefined { + const stylizeExists = + options != null && + typeof options === 'object' && + 'stylize' in options && + typeof options.stylize === 'function'; + + if (stylizeExists) { + return options.stylize as StylizeFunction; + } +} diff --git a/nodejs/node_modules/bson/src/regexp.ts b/nodejs/node_modules/bson/src/regexp.ts new file mode 100644 index 00000000..e401a290 --- /dev/null +++ b/nodejs/node_modules/bson/src/regexp.ts @@ -0,0 +1,114 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import type { EJSONOptions } from './extended_json'; +import { type InspectFn, defaultInspect, getStylizeFunction } from './parser/utils'; + +function alphabetize(str: string): string { + return str.split('').sort().join(''); +} + +/** @public */ +export interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} + +/** @public */ +export interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} + +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +export class BSONRegExp extends BSONValue { + get _bsontype(): 'BSONRegExp' { + return 'BSONRegExp'; + } + + pattern!: string; + options!: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string) { + super(); + this.pattern = pattern; + this.options = alphabetize(options ?? ''); + + if (this.pattern.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}` + ); + } + if (this.options.indexOf('\x00') !== -1) { + throw new BSONError( + `BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}` + ); + } + + // Validate options + for (let i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); + } + } + } + + static parseOptions(options?: string): string { + return options ? options.split('').sort().join('') : ''; + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BSONRegExpExtendedLegacy | BSONRegExpExtended { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + + /** @internal */ + static fromExtendedJSON(doc: BSONRegExpExtendedLegacy | BSONRegExpExtended): BSONRegExp { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc as unknown as BSONRegExp; + } + } else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp( + doc.$regularExpression.pattern, + BSONRegExp.parseOptions(doc.$regularExpression.options) + ); + } + throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + const stylize = getStylizeFunction(options) ?? (v => v); + inspect ??= defaultInspect; + const pattern = stylize(inspect(this.pattern), 'regexp'); + const flags = stylize(inspect(this.options), 'regexp'); + return `new BSONRegExp(${pattern}, ${flags})`; + } +} diff --git a/nodejs/node_modules/bson/src/symbol.ts b/nodejs/node_modules/bson/src/symbol.ts new file mode 100644 index 00000000..6835ab95 --- /dev/null +++ b/nodejs/node_modules/bson/src/symbol.ts @@ -0,0 +1,55 @@ +import { BSONValue } from './bson_value'; +import { type InspectFn, defaultInspect } from './parser/utils'; + +/** @public */ +export interface BSONSymbolExtended { + $symbol: string; +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export class BSONSymbol extends BSONValue { + get _bsontype(): 'BSONSymbol' { + return 'BSONSymbol'; + } + + value!: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string) { + super(); + this.value = value; + } + + /** Access the wrapped string value. */ + valueOf(): string { + return this.value; + } + + toString(): string { + return this.value; + } + + toJSON(): string { + return this.value; + } + + /** @internal */ + toExtendedJSON(): BSONSymbolExtended { + return { $symbol: this.value }; + } + + /** @internal */ + static fromExtendedJSON(doc: BSONSymbolExtended): BSONSymbol { + return new BSONSymbol(doc.$symbol); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + return `new BSONSymbol(${inspect(this.value, options)})`; + } +} diff --git a/nodejs/node_modules/bson/src/timestamp.ts b/nodejs/node_modules/bson/src/timestamp.ts new file mode 100644 index 00000000..9d1e205c --- /dev/null +++ b/nodejs/node_modules/bson/src/timestamp.ts @@ -0,0 +1,151 @@ +import { BSONError } from './error'; +import type { Int32 } from './int_32'; +import { Long } from './long'; +import { type InspectFn, defaultInspect } from './parser/utils'; + +/** @public */ +export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; +/** @public */ +export type LongWithoutOverrides = new ( + low: unknown, + high?: number | boolean, + unsigned?: boolean +) => { + [P in Exclude]: Long[P]; +}; +/** @public */ +export const LongWithoutOverridesClass: LongWithoutOverrides = + Long as unknown as LongWithoutOverrides; + +/** @public */ +export interface TimestampExtended { + $timestamp: { + t: number; + i: number; + }; +} + +/** + * @public + * @category BSONType + */ +export class Timestamp extends LongWithoutOverridesClass { + get _bsontype(): 'Timestamp' { + return 'Timestamp'; + } + + static readonly MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + + /** + * @param int - A 64-bit bigint representing the Timestamp. + */ + constructor(int: bigint); + /** + * @param long - A 64-bit Long representing the Timestamp. + */ + constructor(long: Long); + /** + * @param value - A pair of two values indicating timestamp and increment. + */ + constructor(value: { t: number; i: number }); + constructor(low?: bigint | Long | { t: number | Int32; i: number | Int32 }) { + if (low == null) { + super(0, 0, true); + } else if (typeof low === 'bigint') { + super(low, true); + } else if (Long.isLong(low)) { + super(low.low, low.high, true); + } else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + const t = Number(low.t); + const i = Number(low.i); + if (t < 0 || Number.isNaN(t)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (i < 0 || Number.isNaN(i)) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (t > 0xffff_ffff) { + throw new BSONError( + 'Timestamp constructed from { t, i } must provide t equal or less than uint32 max' + ); + } + if (i > 0xffff_ffff) { + throw new BSONError( + 'Timestamp constructed from { t, i } must provide i equal or less than uint32 max' + ); + } + + super(i, t, true); + } else { + throw new BSONError( + 'A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }' + ); + } + } + + toJSON(): { $timestamp: string } { + return { + $timestamp: this.toString() + }; + } + + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + static fromInt(value: number): Timestamp { + return new Timestamp(Long.fromInt(value, true)); + } + + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + static fromNumber(value: number): Timestamp { + return new Timestamp(Long.fromNumber(value, true)); + } + + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + static fromBits(lowBits: number, highBits: number): Timestamp { + return new Timestamp({ i: lowBits, t: highBits }); + } + + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + static fromString(str: string, optRadix: number): Timestamp { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + + /** @internal */ + toExtendedJSON(): TimestampExtended { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + + /** @internal */ + static fromExtendedJSON(doc: TimestampExtended): Timestamp { + // The Long check is necessary because extended JSON has different behavior given the size of the input number + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() // Need to fetch the least significant 32 bits + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() // Need to fetch the least significant 32 bits + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + + inspect(depth?: number, options?: unknown, inspect?: InspectFn): string { + inspect ??= defaultInspect; + const t = inspect(this.high >>> 0, options); + const i = inspect(this.low >>> 0, options); + return `new Timestamp({ t: ${t}, i: ${i} })`; + } +} diff --git a/nodejs/node_modules/bson/src/utils/byte_utils.ts b/nodejs/node_modules/bson/src/utils/byte_utils.ts new file mode 100644 index 00000000..9c748acb --- /dev/null +++ b/nodejs/node_modules/bson/src/utils/byte_utils.ts @@ -0,0 +1,55 @@ +import { nodeJsByteUtils } from './node_byte_utils'; +import { webByteUtils } from './web_byte_utils'; + +/** @internal */ +export type ByteUtils = { + /** Transforms the input to an instance of Buffer if running on node, otherwise Uint8Array */ + toLocalBufferType(buffer: Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array; + /** Create empty space of size */ + allocate: (size: number) => Uint8Array; + /** Create empty space of size, use pooled memory when available */ + allocateUnsafe: (size: number) => Uint8Array; + /** Check if two Uint8Arrays are deep equal */ + equals: (a: Uint8Array, b: Uint8Array) => boolean; + /** Check if two Uint8Arrays are deep equal */ + fromNumberArray: (array: number[]) => Uint8Array; + /** Create a Uint8Array from a base64 string */ + fromBase64: (base64: string) => Uint8Array; + /** Create a base64 string from bytes */ + toBase64: (buffer: Uint8Array) => string; + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591: (codePoints: string) => Uint8Array; + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591: (buffer: Uint8Array) => string; + /** Create a Uint8Array from a hex string */ + fromHex: (hex: string) => Uint8Array; + /** Create a lowercase hex string from bytes */ + toHex: (buffer: Uint8Array) => string; + /** Create a string from utf8 code units, fatal=true will throw an error if UTF-8 bytes are invalid, fatal=false will insert replacement characters */ + toUTF8: (buffer: Uint8Array, start: number, end: number, fatal: boolean) => string; + /** Get the utf8 code unit count from a string if it were to be transformed to utf8 */ + utf8ByteLength: (input: string) => number; + /** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */ + encodeUTF8Into(destination: Uint8Array, source: string, byteOffset: number): number; + /** Generate a Uint8Array filled with random bytes with byteLength */ + randomBytes(byteLength: number): Uint8Array; +}; + +declare const Buffer: { new (): unknown; prototype?: { _isBuffer?: boolean } } | undefined; + +/** + * Check that a global Buffer exists that is a function and + * does not have a '_isBuffer' property defined on the prototype + * (this is to prevent using the npm buffer) + */ +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; + +/** + * This is the only ByteUtils that should be used across the rest of the BSON library. + * + * The type annotation is important here, it asserts that each of the platform specific + * utils implementations are compatible with the common one. + * + * @internal + */ +export const ByteUtils: ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; diff --git a/nodejs/node_modules/bson/src/utils/latin.ts b/nodejs/node_modules/bson/src/utils/latin.ts new file mode 100644 index 00000000..5dd5c91f --- /dev/null +++ b/nodejs/node_modules/bson/src/utils/latin.ts @@ -0,0 +1,104 @@ +/** + * This function is an optimization for small basic latin strings. + * @internal + * @remarks + * ### Important characteristics: + * - If the uint8array or distance between start and end is 0 this function returns an empty string + * - If the byteLength of the string is 1, 2, or 3 we invoke String.fromCharCode and manually offset into the buffer + * - If the byteLength of the string is less than or equal to 20 an array of bytes is built and `String.fromCharCode.apply` is called with the result + * - If any byte exceeds 128 this function returns null + * + * @param uint8array - A sequence of bytes that may contain basic latin characters + * @param start - The start index from which to search the uint8array + * @param end - The index to stop searching the uint8array + * @returns string if all bytes are within the basic latin range, otherwise null + */ +export function tryReadBasicLatin( + uint8array: Uint8Array, + start: number, + end: number +): string | null { + if (uint8array.length === 0) { + return ''; + } + + const stringByteLength = end - start; + if (stringByteLength === 0) { + return ''; + } + + if (stringByteLength > 20) { + return null; + } + + if (stringByteLength === 1 && uint8array[start] < 128) { + return String.fromCharCode(uint8array[start]); + } + + if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + + if ( + stringByteLength === 3 && + uint8array[start] < 128 && + uint8array[start + 1] < 128 && + uint8array[start + 2] < 128 + ) { + return ( + String.fromCharCode(uint8array[start]) + + String.fromCharCode(uint8array[start + 1]) + + String.fromCharCode(uint8array[start + 2]) + ); + } + + const latinBytes = []; + for (let i = start; i < end; i++) { + const byte = uint8array[i]; + if (byte > 127) { + return null; + } + latinBytes.push(byte); + } + + return String.fromCharCode(...latinBytes); +} + +/** + * This function is an optimization for writing small basic latin strings. + * @internal + * @remarks + * ### Important characteristics: + * - If the string length is 0 return 0, do not perform any work + * - If a string is longer than 25 code units return null + * - If any code unit exceeds 128 this function returns null + * + * @param destination - The uint8array to serialize the string to + * @param source - The string to turn into UTF-8 bytes if it fits in the basic latin range + * @param offset - The position in the destination to begin writing bytes to + * @returns the number of bytes written to destination if all code units are below 128, otherwise null + */ +export function tryWriteBasicLatin( + destination: Uint8Array, + source: string, + offset: number +): number | null { + if (source.length === 0) return 0; + + if (source.length > 25) return null; + + if (destination.length - offset < source.length) return null; + + for ( + let charOffset = 0, destinationOffset = offset; + charOffset < source.length; + charOffset++, destinationOffset++ + ) { + const char = source.charCodeAt(charOffset); + if (char > 127) return null; + + destination[destinationOffset] = char; + } + + return source.length; +} diff --git a/nodejs/node_modules/bson/src/utils/node_byte_utils.ts b/nodejs/node_modules/bson/src/utils/node_byte_utils.ts new file mode 100644 index 00000000..d6a641a4 --- /dev/null +++ b/nodejs/node_modules/bson/src/utils/node_byte_utils.ts @@ -0,0 +1,166 @@ +import { BSONError } from '../error'; +import { validateUtf8 } from '../validate_utf8'; +import { tryReadBasicLatin, tryWriteBasicLatin } from './latin'; + +type NodeJsEncoding = 'base64' | 'hex' | 'utf8' | 'binary'; +type NodeJsBuffer = ArrayBufferView & + Uint8Array & { + write(string: string, offset: number, length: undefined, encoding: 'utf8'): number; + copy(target: Uint8Array, targetStart: number, sourceStart: number, sourceEnd: number): number; + toString: (this: Uint8Array, encoding: NodeJsEncoding, start?: number, end?: number) => string; + equals: (this: Uint8Array, other: Uint8Array) => boolean; + }; +type NodeJsBufferConstructor = Omit & { + alloc: (size: number) => NodeJsBuffer; + allocUnsafe: (size: number) => NodeJsBuffer; + from(array: number[]): NodeJsBuffer; + from(array: Uint8Array): NodeJsBuffer; + from(array: ArrayBuffer): NodeJsBuffer; + from(array: ArrayBuffer, byteOffset: number, byteLength: number): NodeJsBuffer; + from(base64: string, encoding: NodeJsEncoding): NodeJsBuffer; + byteLength(input: string, encoding: 'utf8'): number; + isBuffer(value: unknown): value is NodeJsBuffer; +}; + +// This can be nullish, but we gate the nodejs functions on being exported whether or not this exists +// Node.js global +declare const Buffer: NodeJsBufferConstructor; +declare const require: (mod: 'crypto') => { randomBytes: (byteLength: number) => Uint8Array }; + +/** @internal */ +export function nodejsMathRandomBytes(byteLength: number) { + return nodeJsByteUtils.fromNumberArray( + Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)) + ); +} + +/** + * @internal + * WARNING: REQUIRE WILL BE REWRITTEN + * + * This code is carefully used by require_rewriter.mjs any modifications must be reflected in the plugin. + * + * @remarks + * "crypto" is the only dependency BSON needs. This presents a problem for creating a bundle of the BSON library + * in an es module format that can be used both on the browser and in Node.js. In Node.js when BSON is imported as + * an es module, there will be no global require function defined, making the code below fallback to the much less desireable math.random bytes. + * In order to make our es module bundle work as expected on Node.js we need to change this `require()` to a dynamic import, and the dynamic + * import must be top-level awaited since es modules are async. So we rely on a custom rollup plugin to seek out the following lines of code + * and replace `require` with `await import` and the IIFE line (`nodejsRandomBytes = (() => { ... })()`) with `nodejsRandomBytes = await (async () => { ... })()` + * when generating an es module bundle. + */ +const nodejsRandomBytes: (byteLength: number) => Uint8Array = (() => { + try { + return require('crypto').randomBytes; + } catch { + return nodejsMathRandomBytes; + } +})(); + +/** @internal */ +export const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer: Uint8Array | NodeJsBuffer | ArrayBuffer): NodeJsBuffer { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from( + potentialBuffer.buffer, + potentialBuffer.byteOffset, + potentialBuffer.byteLength + ); + } + + const stringTag = + potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if ( + stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]' + ) { + return Buffer.from(potentialBuffer); + } + + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + + allocate(size: number): NodeJsBuffer { + return Buffer.alloc(size); + }, + + allocateUnsafe(size: number): NodeJsBuffer { + return Buffer.allocUnsafe(size); + }, + + equals(a: Uint8Array, b: Uint8Array): boolean { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + + fromNumberArray(array: number[]): NodeJsBuffer { + return Buffer.from(array); + }, + + fromBase64(base64: string): NodeJsBuffer { + return Buffer.from(base64, 'base64'); + }, + + toBase64(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591(codePoints: string): NodeJsBuffer { + return Buffer.from(codePoints, 'binary'); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + + fromHex(hex: string): NodeJsBuffer { + return Buffer.from(hex, 'hex'); + }, + + toHex(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + + toUTF8(buffer: Uint8Array, start: number, end: number, fatal: boolean): string { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + + const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end); + if (fatal) { + // TODO(NODE-4930): Insufficiently strict BSON UTF8 validation + for (let i = 0; i < string.length; i++) { + if (string.charCodeAt(i) === 0xfffd) { + if (!validateUtf8(buffer, start, end)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return string; + }, + + utf8ByteLength(input: string): number { + return Buffer.byteLength(input, 'utf8'); + }, + + encodeUTF8Into(buffer: Uint8Array, source: string, byteOffset: number): number { + const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset); + if (latinBytesWritten != null) { + return latinBytesWritten; + } + + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + + randomBytes: nodejsRandomBytes +}; diff --git a/nodejs/node_modules/bson/src/utils/number_utils.ts b/nodejs/node_modules/bson/src/utils/number_utils.ts new file mode 100644 index 00000000..66dd4ff5 --- /dev/null +++ b/nodejs/node_modules/bson/src/utils/number_utils.ts @@ -0,0 +1,165 @@ +const FLOAT = new Float64Array(1); +const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); + +FLOAT[0] = -1; +// Little endian [0, 0, 0, 0, 0, 0, 240, 191] +// Big endian [191, 240, 0, 0, 0, 0, 0, 0] +const isBigEndian = FLOAT_BYTES[7] === 0; + +/** + * Number parsing and serializing utilities. + * + * @internal + */ +export const NumberUtils = { + /** Reads a little-endian 32-bit integer from source */ + getInt32LE(source: Uint8Array, offset: number): number { + return ( + source[offset] | + (source[offset + 1] << 8) | + (source[offset + 2] << 16) | + (source[offset + 3] << 24) + ); + }, + + /** Reads a little-endian 32-bit unsigned integer from source */ + getUint32LE(source: Uint8Array, offset: number): number { + return ( + source[offset] + + source[offset + 1] * 256 + + source[offset + 2] * 65536 + + source[offset + 3] * 16777216 + ); + }, + + /** Reads a big-endian 32-bit integer from source */ + getUint32BE(source: Uint8Array, offset: number): number { + return ( + source[offset + 3] + + source[offset + 2] * 256 + + source[offset + 1] * 65536 + + source[offset] * 16777216 + ); + }, + + /** Reads a little-endian 64-bit integer from source */ + getBigInt64LE(source: Uint8Array, offset: number): bigint { + const lo = NumberUtils.getUint32LE(source, offset); + const hi = NumberUtils.getUint32LE(source, offset + 4); + + /* + eslint-disable-next-line no-restricted-globals + -- This is allowed since this helper should not be called unless bigint features are enabled + */ + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }, + + /** Reads a little-endian 64-bit float from source */ + getFloat64LE: isBigEndian + ? (source: Uint8Array, offset: number) => { + FLOAT_BYTES[7] = source[offset]; + FLOAT_BYTES[6] = source[offset + 1]; + FLOAT_BYTES[5] = source[offset + 2]; + FLOAT_BYTES[4] = source[offset + 3]; + FLOAT_BYTES[3] = source[offset + 4]; + FLOAT_BYTES[2] = source[offset + 5]; + FLOAT_BYTES[1] = source[offset + 6]; + FLOAT_BYTES[0] = source[offset + 7]; + return FLOAT[0]; + } + : (source: Uint8Array, offset: number) => { + FLOAT_BYTES[0] = source[offset]; + FLOAT_BYTES[1] = source[offset + 1]; + FLOAT_BYTES[2] = source[offset + 2]; + FLOAT_BYTES[3] = source[offset + 3]; + FLOAT_BYTES[4] = source[offset + 4]; + FLOAT_BYTES[5] = source[offset + 5]; + FLOAT_BYTES[6] = source[offset + 6]; + FLOAT_BYTES[7] = source[offset + 7]; + return FLOAT[0]; + }, + + /** Writes a big-endian 32-bit integer to destination, can be signed or unsigned */ + setInt32BE(destination: Uint8Array, offset: number, value: number): 4 { + destination[offset + 3] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset] = value; + return 4; + }, + + /** Writes a little-endian 32-bit integer to destination, can be signed or unsigned */ + setInt32LE(destination: Uint8Array, offset: number, value: number): 4 { + destination[offset] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 3] = value; + return 4; + }, + + /** Write a little-endian 64-bit integer to source */ + setBigInt64LE(destination: Uint8Array, offset: number, value: bigint): 8 { + /* eslint-disable-next-line no-restricted-globals -- This is allowed here as useBigInt64=true */ + const mask32bits = BigInt(0xffff_ffff); + + /** lower 32 bits */ + let lo = Number(value & mask32bits); + destination[offset] = lo; + lo >>= 8; + destination[offset + 1] = lo; + lo >>= 8; + destination[offset + 2] = lo; + lo >>= 8; + destination[offset + 3] = lo; + + /* + eslint-disable-next-line no-restricted-globals + -- This is allowed here as useBigInt64=true + + upper 32 bits + */ + let hi = Number((value >> BigInt(32)) & mask32bits); + destination[offset + 4] = hi; + hi >>= 8; + destination[offset + 5] = hi; + hi >>= 8; + destination[offset + 6] = hi; + hi >>= 8; + destination[offset + 7] = hi; + + return 8; + }, + + /** Writes a little-endian 64-bit float to destination */ + setFloat64LE: isBigEndian + ? (destination: Uint8Array, offset: number, value: number) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[7]; + destination[offset + 1] = FLOAT_BYTES[6]; + destination[offset + 2] = FLOAT_BYTES[5]; + destination[offset + 3] = FLOAT_BYTES[4]; + destination[offset + 4] = FLOAT_BYTES[3]; + destination[offset + 5] = FLOAT_BYTES[2]; + destination[offset + 6] = FLOAT_BYTES[1]; + destination[offset + 7] = FLOAT_BYTES[0]; + return 8; + } + : (destination: Uint8Array, offset: number, value: number) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[0]; + destination[offset + 1] = FLOAT_BYTES[1]; + destination[offset + 2] = FLOAT_BYTES[2]; + destination[offset + 3] = FLOAT_BYTES[3]; + destination[offset + 4] = FLOAT_BYTES[4]; + destination[offset + 5] = FLOAT_BYTES[5]; + destination[offset + 6] = FLOAT_BYTES[6]; + destination[offset + 7] = FLOAT_BYTES[7]; + return 8; + } +}; diff --git a/nodejs/node_modules/bson/src/utils/web_byte_utils.ts b/nodejs/node_modules/bson/src/utils/web_byte_utils.ts new file mode 100644 index 00000000..77a1f0f7 --- /dev/null +++ b/nodejs/node_modules/bson/src/utils/web_byte_utils.ts @@ -0,0 +1,203 @@ +import { BSONError } from '../error'; +import { tryReadBasicLatin } from './latin'; + +type TextDecoder = { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Uint8Array): string; +}; +type TextDecoderConstructor = { + new (label: 'utf8', options: { fatal: boolean; ignoreBOM?: boolean }): TextDecoder; +}; + +type TextEncoder = { + readonly encoding: string; + encode(input?: string): Uint8Array; +}; +type TextEncoderConstructor = { + new (): TextEncoder; +}; + +// Web global +declare const TextDecoder: TextDecoderConstructor; +declare const TextEncoder: TextEncoderConstructor; +declare const atob: (base64: string) => string; +declare const btoa: (binary: string) => string; + +type ArrayBufferViewWithTag = ArrayBufferView & { + [Symbol.toStringTag]?: string; +}; + +function isReactNative() { + const { navigator } = globalThis as { navigator?: { product?: string } }; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} + +/** @internal */ +export function webMathRandomBytes(byteLength: number) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray( + Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)) + ); +} + +/** @internal */ +const webRandomBytes: (byteLength: number) => Uint8Array = (() => { + const { crypto } = globalThis as { + crypto?: { getRandomValues?: (space: Uint8Array) => Uint8Array }; + }; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength: number) => { + // @ts-expect-error: crypto.getRandomValues cannot actually be null here + // You cannot separate getRandomValues from crypto (need to have this === crypto) + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } else { + if (isReactNative()) { + const { console } = globalThis as { console?: { warn?: (message: string) => void } }; + console?.warn?.( + 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + ); + } + return webMathRandomBytes; + } +})(); + +const HEX_DIGIT = /(\d|[a-f])/i; + +/** @internal */ +export const webByteUtils = { + toLocalBufferType( + potentialUint8array: Uint8Array | ArrayBufferViewWithTag | ArrayBuffer + ): Uint8Array { + const stringTag = + potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + + if (stringTag === 'Uint8Array') { + return potentialUint8array as Uint8Array; + } + + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array( + potentialUint8array.buffer.slice( + potentialUint8array.byteOffset, + potentialUint8array.byteOffset + potentialUint8array.byteLength + ) + ); + } + + if ( + stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]' + ) { + return new Uint8Array(potentialUint8array); + } + + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + + allocate(size: number): Uint8Array { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + + allocateUnsafe(size: number): Uint8Array { + return webByteUtils.allocate(size); + }, + + equals(a: Uint8Array, b: Uint8Array): boolean { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + + fromNumberArray(array: number[]): Uint8Array { + return Uint8Array.from(array); + }, + + fromBase64(base64: string): Uint8Array { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + + toBase64(uint8array: Uint8Array): string { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591(codePoints: string): Uint8Array { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591(uint8array: Uint8Array): string { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + + fromHex(hex: string): Uint8Array { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + + return Uint8Array.from(buffer); + }, + + toHex(uint8array: Uint8Array): string { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + + toUTF8(uint8array: Uint8Array, start: number, end: number, fatal: boolean): string { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + + if (fatal) { + try { + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + } catch (cause) { + throw new BSONError('Invalid UTF-8 string in BSON document', { cause }); + } + } + return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end)); + }, + + utf8ByteLength(input: string): number { + return new TextEncoder().encode(input).byteLength; + }, + + encodeUTF8Into(uint8array: Uint8Array, source: string, byteOffset: number): number { + const bytes = new TextEncoder().encode(source); + uint8array.set(bytes, byteOffset); + return bytes.byteLength; + }, + + randomBytes: webRandomBytes +}; diff --git a/nodejs/node_modules/bson/src/validate_utf8.ts b/nodejs/node_modules/bson/src/validate_utf8.ts new file mode 100644 index 00000000..e1da934c --- /dev/null +++ b/nodejs/node_modules/bson/src/validate_utf8.ts @@ -0,0 +1,47 @@ +const FIRST_BIT = 0x80; +const FIRST_TWO_BITS = 0xc0; +const FIRST_THREE_BITS = 0xe0; +const FIRST_FOUR_BITS = 0xf0; +const FIRST_FIVE_BITS = 0xf8; + +const TWO_BIT_CHAR = 0xc0; +const THREE_BIT_CHAR = 0xe0; +const FOUR_BIT_CHAR = 0xf0; +const CONTINUING_CHAR = 0x80; + +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +export function validateUtf8( + bytes: { [index: number]: number }, + start: number, + end: number +): boolean { + let continuation = 0; + + for (let i = start; i < end; i += 1) { + const byte = bytes[i]; + + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } else { + return false; + } + } + } + + return !continuation; +} diff --git a/nodejs/node_modules/bson/vendor/base64/LICENSE-MIT.txt b/nodejs/node_modules/bson/vendor/base64/LICENSE-MIT.txt new file mode 100644 index 00000000..a41e0a7e --- /dev/null +++ b/nodejs/node_modules/bson/vendor/base64/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/bson/vendor/base64/README.md b/nodejs/node_modules/bson/vendor/base64/README.md new file mode 100644 index 00000000..ab0ef251 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/base64/README.md @@ -0,0 +1,112 @@ +# base64 [![Build status](https://travis-ci.org/mathiasbynens/base64.svg?branch=master)](https://travis-ci.org/mathiasbynens/base64) [![Code coverage status](http://img.shields.io/coveralls/mathiasbynens/base64/master.svg)](https://coveralls.io/r/mathiasbynens/base64) + +_base64_ is a robust base64 encoder/decoder that is fully compatible with [`atob()` and `btoa()`](https://html.spec.whatwg.org/multipage/webappapis.html#atob), written in JavaScript. The base64-encoding and -decoding algorithms it uses are fully [RFC 4648](https://tools.ietf.org/html/rfc4648#section-4) compliant. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install base-64 +``` + +In a browser: + +```html + +``` + +In [Narwhal](http://narwhaljs.org/), [Node.js](https://nodejs.org/), and [RingoJS](http://ringojs.org/): + +```js +var base64 = require('base-64'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('base64.js'); +``` + +Using an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require( + { + 'paths': { + 'base64': 'path/to/base64' + } + }, + ['base64'], + function(base64) { + console.log(base64); + } +); +``` + +## API + +### `base64.version` + +A string representing the semantic version number. + +### `base64.encode(input)` + +This function takes a byte string (the `input` parameter) and encodes it according to base64. The input data must be in the form of a string containing only characters in the range from U+0000 to U+00FF, each representing a binary byte with values `0x00` to `0xFF`. The `base64.encode()` function is designed to be fully compatible with [`btoa()` as described in the HTML Standard](https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-btoa). + +```js +var encodedData = base64.encode(input); +``` + +To base64-encode any Unicode string, [encode it as UTF-8 first](https://github.com/mathiasbynens/utf8.js#utf8encodestring): + +```js +var base64 = require('base-64'); +var utf8 = require('utf8'); + +var text = 'foo © bar 𝌆 baz'; +var bytes = utf8.encode(text); +var encoded = base64.encode(bytes); +console.log(encoded); +// → 'Zm9vIMKpIGJhciDwnYyGIGJheg==' +``` + +### `base64.decode(input)` + +This function takes a base64-encoded string (the `input` parameter) and decodes it. The return value is in the form of a string containing only characters in the range from U+0000 to U+00FF, each representing a binary byte with values `0x00` to `0xFF`. The `base64.decode()` function is designed to be fully compatible with [`atob()` as described in the HTML Standard](https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-atob). + +```js +var decodedData = base64.decode(encodedData); +``` + +To base64-decode UTF-8-encoded data back into a Unicode string, [UTF-8-decode it](https://github.com/mathiasbynens/utf8.js#utf8decodebytestring) after base64-decoding it: + +```js +var encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg=='; +var bytes = base64.decode(encoded); +var text = utf8.decode(bytes); +console.log(text); +// → 'foo © bar 𝌆 baz' +``` + +## Support + +_base64_ is designed to work in at least Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.9, PhantomJS 1.9.0, Rhino 1.7RC4, as well as old and modern versions of Chrome, Firefox, Safari, Opera, and Internet Explorer. + +## Unit tests & code coverage + +After cloning this repository, run `npm install` to install the dependencies needed for development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. + +Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`. + +To generate the code coverage report, use `grunt cover`. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +_base64_ is available under the [MIT](https://mths.be/mit) license. diff --git a/nodejs/node_modules/bson/vendor/base64/base64.js b/nodejs/node_modules/bson/vendor/base64/base64.js new file mode 100644 index 00000000..611b4461 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/base64/base64.js @@ -0,0 +1,157 @@ +/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */ +;(function(root) { + + // Detect free variables `exports`. + var freeExports = typeof exports == 'object' && exports; + + // Detect free variable `module`. + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + + /*--------------------------------------------------------------------------*/ + + var InvalidCharacterError = function(message) { + this.message = message; + }; + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + var error = function(message) { + // Note: the error messages used throughout this file match those used by + // the native `atob`/`btoa` implementation in Chromium. + throw new InvalidCharacterError(message); + }; + + var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + // http://whatwg.org/html/common-microsyntaxes.html#space-character + var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; + + // `decode` is designed to be fully compatible with `atob` as described in the + // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob + // The optimized base64-decoding algorithm used is based on @atk’s excellent + // implementation. https://gist.github.com/atk/1020396 + var decode = function(input) { + input = String(input) + .replace(REGEX_SPACE_CHARACTERS, ''); + var length = input.length; + if (length % 4 == 0) { + input = input.replace(/==?$/, ''); + length = input.length; + } + if ( + length % 4 == 1 || + // http://whatwg.org/C#alphanumeric-ascii-characters + /[^+a-zA-Z0-9/]/.test(input) + ) { + error( + 'Invalid character: the string to be decoded is not correctly encoded.' + ); + } + var bitCounter = 0; + var bitStorage; + var buffer; + var output = ''; + var position = -1; + while (++position < length) { + buffer = TABLE.indexOf(input.charAt(position)); + bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; + // Unless this is the first of a group of 4 characters… + if (bitCounter++ % 4) { + // …convert the first 8 bits to a single ASCII character. + output += String.fromCharCode( + 0xFF & bitStorage >> (-2 * bitCounter & 6) + ); + } + } + return output; + }; + + // `encode` is designed to be fully compatible with `btoa` as described in the + // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa + var encode = function(input) { + input = String(input); + if (/[^\0-\xFF]/.test(input)) { + // Note: no need to special-case astral symbols here, as surrogates are + // matched, and the input is supposed to only contain ASCII anyway. + error( + 'The string to be encoded contains characters outside of the ' + + 'Latin1 range.' + ); + } + var padding = input.length % 3; + var output = ''; + var position = -1; + var a; + var b; + var c; + var buffer; + // Make sure any padding is handled outside of the loop. + var length = input.length - padding; + + while (++position < length) { + // Read three bytes, i.e. 24 bits. + a = input.charCodeAt(position) << 16; + b = input.charCodeAt(++position) << 8; + c = input.charCodeAt(++position); + buffer = a + b + c; + // Turn the 24 bits into four chunks of 6 bits each, and append the + // matching character for each of them to the output. + output += ( + TABLE.charAt(buffer >> 18 & 0x3F) + + TABLE.charAt(buffer >> 12 & 0x3F) + + TABLE.charAt(buffer >> 6 & 0x3F) + + TABLE.charAt(buffer & 0x3F) + ); + } + + if (padding == 2) { + a = input.charCodeAt(position) << 8; + b = input.charCodeAt(++position); + buffer = a + b; + output += ( + TABLE.charAt(buffer >> 10) + + TABLE.charAt((buffer >> 4) & 0x3F) + + TABLE.charAt((buffer << 2) & 0x3F) + + '=' + ); + } else if (padding == 1) { + buffer = input.charCodeAt(position); + output += ( + TABLE.charAt(buffer >> 2) + + TABLE.charAt((buffer << 4) & 0x3F) + + '==' + ); + } + + return output; + }; + + var base64 = { + 'encode': encode, + 'decode': decode, + 'version': '1.0.0' + }; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return base64; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = base64; + } else { // in Narwhal or RingoJS v0.7.0- + for (var key in base64) { + base64.hasOwnProperty(key) && (freeExports[key] = base64[key]); + } + } + } else { // in Rhino or a web browser + root.base64 = base64; + } + +}(this)); diff --git a/nodejs/node_modules/bson/vendor/base64/package.json b/nodejs/node_modules/bson/vendor/base64/package.json new file mode 100644 index 00000000..479b0a18 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/base64/package.json @@ -0,0 +1,43 @@ +{ + "name": "base-64", + "version": "1.0.0", + "description": "A robust base64 encoder/decoder that is fully compatible with `atob()` and `btoa()`, written in JavaScript.", + "homepage": "https://mths.be/base64", + "main": "base64.js", + "keywords": [ + "codec", + "decoder", + "encoder", + "base64", + "atob", + "btoa" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/base64.git" + }, + "bugs": "https://github.com/mathiasbynens/base64/issues", + "files": [ + "LICENSE-MIT.txt", + "base64.js" + ], + "scripts": { + "test": "mocha tests/tests.js", + "build": "grunt build" + }, + "devDependencies": { + "coveralls": "^2.11.4", + "grunt": "^0.4.5", + "grunt-cli": "^1.3.2", + "grunt-shell": "^1.1.2", + "grunt-template": "^0.2.3", + "istanbul": "^0.4.0", + "mocha": "^6.2.0", + "regenerate": "^1.2.1" + } +} diff --git a/nodejs/node_modules/bson/vendor/text-encoding/LICENSE.md b/nodejs/node_modules/bson/vendor/text-encoding/LICENSE.md new file mode 100644 index 00000000..5ab10466 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/text-encoding/LICENSE.md @@ -0,0 +1,237 @@ +The encoding indexes, algorithms, and many comments in the code +derive from the Encoding Standard https://encoding.spec.whatwg.org/ + +Otherwise, the code of this repository is released under the Unlicense +license and is also dual-licensed under an Apache 2.0 license. Both +are included below. + +# Unlicense + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to + +# Apache 2.0 License + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/nodejs/node_modules/bson/vendor/text-encoding/README.md b/nodejs/node_modules/bson/vendor/text-encoding/README.md new file mode 100644 index 00000000..b9af0e31 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/text-encoding/README.md @@ -0,0 +1,111 @@ +text-encoding +============== + +This is a polyfill for the [Encoding Living +Standard](https://encoding.spec.whatwg.org/) API for the Web, allowing +encoding and decoding of textual data to and from Typed Array buffers +for binary data in JavaScript. + +By default it adheres to the spec and does not support *encoding* to +legacy encodings, only *decoding*. It is also implemented to match the +specification's algorithms, rather than for performance. The intended +use is within Web pages, so it has no dependency on server frameworks +or particular module schemes. + +Basic examples and tests are included. + +### Install ### + +There are a few ways you can get and use the `text-encoding` library. + +### HTML Page Usage ### + +Clone the repo and include the files directly: + +```html + + + +``` + +This is the only use case the developer cares about. If you want those +fancy module and/or package manager things that are popular these days +you should probably use a different library. + +#### Package Managers #### + +The package is published to **npm** and **bower** as `text-encoding`. +Use through these is not really supported, since they aren't used by +the developer of the library. Using `require()` in interesting ways +probably breaks. Patches welcome, as long as they don't break the +basic use of the files via ` +``` + +To support the legacy encodings (which may be stateful), the +TextEncoder `encode()` method accepts an optional dictionary and +`stream` option, e.g. `encoder.encode(string, {stream: true});` This +is not needed for standard encoding since the input is always in +complete code points. diff --git a/nodejs/node_modules/bson/vendor/text-encoding/index.js b/nodejs/node_modules/bson/vendor/text-encoding/index.js new file mode 100644 index 00000000..cc57d658 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/text-encoding/index.js @@ -0,0 +1,9 @@ +// This is free and unencumbered software released into the public domain. +// See LICENSE.md for more information. + +var encoding = require("./lib/encoding.js"); + +module.exports = { + TextEncoder: encoding.TextEncoder, + TextDecoder: encoding.TextDecoder, +}; diff --git a/nodejs/node_modules/bson/vendor/text-encoding/lib/encoding-indexes.js b/nodejs/node_modules/bson/vendor/text-encoding/lib/encoding-indexes.js new file mode 100644 index 00000000..4f170c3b --- /dev/null +++ b/nodejs/node_modules/bson/vendor/text-encoding/lib/encoding-indexes.js @@ -0,0 +1,47 @@ +(function(global) { + 'use strict'; + + if (typeof module !== "undefined" && module.exports) { + module.exports = global; + } + + global["encoding-indexes"] = +{ + "big5":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,17392,19506,17923,17830,17784,160359,19831,17843,162993,19682,163013,15253,18230,18244,19527,19520,148159,144919,160594,159371,159954,19543,172881,18255,17882,19589,162924,19719,19108,18081,158499,29221,154196,137827,146950,147297,26189,22267,null,32149,22813,166841,15860,38708,162799,23515,138590,23204,13861,171696,23249,23479,23804,26478,34195,170309,29793,29853,14453,138579,145054,155681,16108,153822,15093,31484,40855,147809,166157,143850,133770,143966,17162,33924,40854,37935,18736,34323,22678,38730,37400,31184,31282,26208,27177,34973,29772,31685,26498,31276,21071,36934,13542,29636,155065,29894,40903,22451,18735,21580,16689,145038,22552,31346,162661,35727,18094,159368,16769,155033,31662,140476,40904,140481,140489,140492,40905,34052,144827,16564,40906,17633,175615,25281,28782,40907,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,12736,12737,12738,12739,12740,131340,12741,131281,131277,12742,12743,131275,139240,12744,131274,12745,12746,12747,12748,131342,12749,12750,256,193,461,192,274,201,282,200,332,211,465,210,null,7870,null,7872,202,257,225,462,224,593,275,233,283,232,299,237,464,236,333,243,466,242,363,250,468,249,470,472,474,476,252,null,7871,null,7873,234,609,9178,9179,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,172969,135493,null,25866,null,null,20029,28381,40270,37343,null,null,161589,25745,20250,20264,20392,20822,20852,20892,20964,21153,21160,21307,21326,21457,21464,22242,22768,22788,22791,22834,22836,23398,23454,23455,23706,24198,24635,25993,26622,26628,26725,27982,28860,30005,32420,32428,32442,32455,32463,32479,32518,32567,33402,33487,33647,35270,35774,35810,36710,36711,36718,29713,31996,32205,26950,31433,21031,null,null,null,null,37260,30904,37214,32956,null,36107,33014,133607,null,null,32927,40647,19661,40393,40460,19518,171510,159758,40458,172339,13761,null,28314,33342,29977,null,18705,39532,39567,40857,31111,164972,138698,132560,142054,20004,20097,20096,20103,20159,20203,20279,13388,20413,15944,20483,20616,13437,13459,13477,20870,22789,20955,20988,20997,20105,21113,21136,21287,13767,21417,13649,21424,13651,21442,21539,13677,13682,13953,21651,21667,21684,21689,21712,21743,21784,21795,21800,13720,21823,13733,13759,21975,13765,163204,21797,null,134210,134421,151851,21904,142534,14828,131905,36422,150968,169189,16467,164030,30586,142392,14900,18389,164189,158194,151018,25821,134524,135092,134357,135412,25741,36478,134806,134155,135012,142505,164438,148691,null,134470,170573,164073,18420,151207,142530,39602,14951,169460,16365,13574,152263,169940,161992,142660,40302,38933,null,17369,155813,25780,21731,142668,142282,135287,14843,135279,157402,157462,162208,25834,151634,134211,36456,139681,166732,132913,null,18443,131497,16378,22643,142733,null,148936,132348,155799,134988,134550,21881,16571,17338,null,19124,141926,135325,33194,39157,134556,25465,14846,141173,36288,22177,25724,15939,null,173569,134665,142031,142537,null,135368,145858,14738,14854,164507,13688,155209,139463,22098,134961,142514,169760,13500,27709,151099,null,null,161140,142987,139784,173659,167117,134778,134196,157724,32659,135375,141315,141625,13819,152035,134796,135053,134826,16275,134960,134471,135503,134732,null,134827,134057,134472,135360,135485,16377,140950,25650,135085,144372,161337,142286,134526,134527,142417,142421,14872,134808,135367,134958,173618,158544,167122,167321,167114,38314,21708,33476,21945,null,171715,39974,39606,161630,142830,28992,33133,33004,23580,157042,33076,14231,21343,164029,37302,134906,134671,134775,134907,13789,151019,13833,134358,22191,141237,135369,134672,134776,135288,135496,164359,136277,134777,151120,142756,23124,135197,135198,135413,135414,22428,134673,161428,164557,135093,134779,151934,14083,135094,135552,152280,172733,149978,137274,147831,164476,22681,21096,13850,153405,31666,23400,18432,19244,40743,18919,39967,39821,154484,143677,22011,13810,22153,20008,22786,138177,194680,38737,131206,20059,20155,13630,23587,24401,24516,14586,25164,25909,27514,27701,27706,28780,29227,20012,29357,149737,32594,31035,31993,32595,156266,13505,null,156491,32770,32896,157202,158033,21341,34916,35265,161970,35744,36125,38021,38264,38271,38376,167439,38886,39029,39118,39134,39267,170000,40060,40479,40644,27503,63751,20023,131207,38429,25143,38050,null,20539,28158,171123,40870,15817,34959,147790,28791,23797,19232,152013,13657,154928,24866,166450,36775,37366,29073,26393,29626,144001,172295,15499,137600,19216,30948,29698,20910,165647,16393,27235,172730,16931,34319,133743,31274,170311,166634,38741,28749,21284,139390,37876,30425,166371,40871,30685,20131,20464,20668,20015,20247,40872,21556,32139,22674,22736,138678,24210,24217,24514,141074,25995,144377,26905,27203,146531,27903,null,29184,148741,29580,16091,150035,23317,29881,35715,154788,153237,31379,31724,31939,32364,33528,34199,40873,34960,40874,36537,40875,36815,34143,39392,37409,40876,167353,136255,16497,17058,23066,null,null,null,39016,26475,17014,22333,null,34262,149883,33471,160013,19585,159092,23931,158485,159678,40877,40878,23446,40879,26343,32347,28247,31178,15752,17603,143958,141206,17306,17718,null,23765,146202,35577,23672,15634,144721,23928,40882,29015,17752,147692,138787,19575,14712,13386,131492,158785,35532,20404,131641,22975,33132,38998,170234,24379,134047,null,139713,166253,16642,18107,168057,16135,40883,172469,16632,14294,18167,158790,16764,165554,160767,17773,14548,152730,17761,17691,19849,19579,19830,17898,16328,150287,13921,17630,17597,16877,23870,23880,23894,15868,14351,23972,23993,14368,14392,24130,24253,24357,24451,14600,14612,14655,14669,24791,24893,23781,14729,25015,25017,25039,14776,25132,25232,25317,25368,14840,22193,14851,25570,25595,25607,25690,14923,25792,23829,22049,40863,14999,25990,15037,26111,26195,15090,26258,15138,26390,15170,26532,26624,15192,26698,26756,15218,15217,15227,26889,26947,29276,26980,27039,27013,15292,27094,15325,27237,27252,27249,27266,15340,27289,15346,27307,27317,27348,27382,27521,27585,27626,27765,27818,15563,27906,27910,27942,28033,15599,28068,28081,28181,28184,28201,28294,166336,28347,28386,28378,40831,28392,28393,28452,28468,15686,147265,28545,28606,15722,15733,29111,23705,15754,28716,15761,28752,28756,28783,28799,28809,131877,17345,13809,134872,147159,22462,159443,28990,153568,13902,27042,166889,23412,31305,153825,169177,31333,31357,154028,31419,31408,31426,31427,29137,156813,16842,31450,31453,31466,16879,21682,154625,31499,31573,31529,152334,154878,31650,31599,33692,154548,158847,31696,33825,31634,31672,154912,15789,154725,33938,31738,31750,31797,154817,31812,31875,149634,31910,26237,148856,31945,31943,31974,31860,31987,31989,31950,32359,17693,159300,32093,159446,29837,32137,32171,28981,32179,32210,147543,155689,32228,15635,32245,137209,32229,164717,32285,155937,155994,32366,32402,17195,37996,32295,32576,32577,32583,31030,156368,39393,32663,156497,32675,136801,131176,17756,145254,17667,164666,32762,156809,32773,32776,32797,32808,32815,172167,158915,32827,32828,32865,141076,18825,157222,146915,157416,26405,32935,166472,33031,33050,22704,141046,27775,156824,151480,25831,136330,33304,137310,27219,150117,150165,17530,33321,133901,158290,146814,20473,136445,34018,33634,158474,149927,144688,137075,146936,33450,26907,194964,16859,34123,33488,33562,134678,137140,14017,143741,144730,33403,33506,33560,147083,159139,158469,158615,144846,15807,33565,21996,33669,17675,159141,33708,33729,33747,13438,159444,27223,34138,13462,159298,143087,33880,154596,33905,15827,17636,27303,33866,146613,31064,33960,158614,159351,159299,34014,33807,33681,17568,33939,34020,154769,16960,154816,17731,34100,23282,159385,17703,34163,17686,26559,34326,165413,165435,34241,159880,34306,136578,159949,194994,17770,34344,13896,137378,21495,160666,34430,34673,172280,34798,142375,34737,34778,34831,22113,34412,26710,17935,34885,34886,161248,146873,161252,34910,34972,18011,34996,34997,25537,35013,30583,161551,35207,35210,35238,35241,35239,35260,166437,35303,162084,162493,35484,30611,37374,35472,162393,31465,162618,147343,18195,162616,29052,35596,35615,152624,152933,35647,35660,35661,35497,150138,35728,35739,35503,136927,17941,34895,35995,163156,163215,195028,14117,163155,36054,163224,163261,36114,36099,137488,36059,28764,36113,150729,16080,36215,36265,163842,135188,149898,15228,164284,160012,31463,36525,36534,36547,37588,36633,36653,164709,164882,36773,37635,172703,133712,36787,18730,166366,165181,146875,24312,143970,36857,172052,165564,165121,140069,14720,159447,36919,165180,162494,36961,165228,165387,37032,165651,37060,165606,37038,37117,37223,15088,37289,37316,31916,166195,138889,37390,27807,37441,37474,153017,37561,166598,146587,166668,153051,134449,37676,37739,166625,166891,28815,23235,166626,166629,18789,37444,166892,166969,166911,37747,37979,36540,38277,38310,37926,38304,28662,17081,140922,165592,135804,146990,18911,27676,38523,38550,16748,38563,159445,25050,38582,30965,166624,38589,21452,18849,158904,131700,156688,168111,168165,150225,137493,144138,38705,34370,38710,18959,17725,17797,150249,28789,23361,38683,38748,168405,38743,23370,168427,38751,37925,20688,143543,143548,38793,38815,38833,38846,38848,38866,38880,152684,38894,29724,169011,38911,38901,168989,162170,19153,38964,38963,38987,39014,15118,160117,15697,132656,147804,153350,39114,39095,39112,39111,19199,159015,136915,21936,39137,39142,39148,37752,39225,150057,19314,170071,170245,39413,39436,39483,39440,39512,153381,14020,168113,170965,39648,39650,170757,39668,19470,39700,39725,165376,20532,39732,158120,14531,143485,39760,39744,171326,23109,137315,39822,148043,39938,39935,39948,171624,40404,171959,172434,172459,172257,172323,172511,40318,40323,172340,40462,26760,40388,139611,172435,172576,137531,172595,40249,172217,172724,40592,40597,40606,40610,19764,40618,40623,148324,40641,15200,14821,15645,20274,14270,166955,40706,40712,19350,37924,159138,40727,40726,40761,22175,22154,40773,39352,168075,38898,33919,40802,40809,31452,40846,29206,19390,149877,149947,29047,150008,148296,150097,29598,166874,137466,31135,166270,167478,37737,37875,166468,37612,37761,37835,166252,148665,29207,16107,30578,31299,28880,148595,148472,29054,137199,28835,137406,144793,16071,137349,152623,137208,14114,136955,137273,14049,137076,137425,155467,14115,136896,22363,150053,136190,135848,136134,136374,34051,145062,34051,33877,149908,160101,146993,152924,147195,159826,17652,145134,170397,159526,26617,14131,15381,15847,22636,137506,26640,16471,145215,147681,147595,147727,158753,21707,22174,157361,22162,135135,134056,134669,37830,166675,37788,20216,20779,14361,148534,20156,132197,131967,20299,20362,153169,23144,131499,132043,14745,131850,132116,13365,20265,131776,167603,131701,35546,131596,20120,20685,20749,20386,20227,150030,147082,20290,20526,20588,20609,20428,20453,20568,20732,20825,20827,20829,20830,28278,144789,147001,147135,28018,137348,147081,20904,20931,132576,17629,132259,132242,132241,36218,166556,132878,21081,21156,133235,21217,37742,18042,29068,148364,134176,149932,135396,27089,134685,29817,16094,29849,29716,29782,29592,19342,150204,147597,21456,13700,29199,147657,21940,131909,21709,134086,22301,37469,38644,37734,22493,22413,22399,13886,22731,23193,166470,136954,137071,136976,23084,22968,37519,23166,23247,23058,153926,137715,137313,148117,14069,27909,29763,23073,155267,23169,166871,132115,37856,29836,135939,28933,18802,37896,166395,37821,14240,23582,23710,24158,24136,137622,137596,146158,24269,23375,137475,137476,14081,137376,14045,136958,14035,33066,166471,138682,144498,166312,24332,24334,137511,137131,23147,137019,23364,34324,161277,34912,24702,141408,140843,24539,16056,140719,140734,168072,159603,25024,131134,131142,140827,24985,24984,24693,142491,142599,149204,168269,25713,149093,142186,14889,142114,144464,170218,142968,25399,173147,25782,25393,25553,149987,142695,25252,142497,25659,25963,26994,15348,143502,144045,149897,144043,21773,144096,137433,169023,26318,144009,143795,15072,16784,152964,166690,152975,136956,152923,152613,30958,143619,137258,143924,13412,143887,143746,148169,26254,159012,26219,19347,26160,161904,138731,26211,144082,144097,26142,153714,14545,145466,145340,15257,145314,144382,29904,15254,26511,149034,26806,26654,15300,27326,14435,145365,148615,27187,27218,27337,27397,137490,25873,26776,27212,15319,27258,27479,147392,146586,37792,37618,166890,166603,37513,163870,166364,37991,28069,28427,149996,28007,147327,15759,28164,147516,23101,28170,22599,27940,30786,28987,148250,148086,28913,29264,29319,29332,149391,149285,20857,150180,132587,29818,147192,144991,150090,149783,155617,16134,16049,150239,166947,147253,24743,16115,29900,29756,37767,29751,17567,159210,17745,30083,16227,150745,150790,16216,30037,30323,173510,15129,29800,166604,149931,149902,15099,15821,150094,16127,149957,149747,37370,22322,37698,166627,137316,20703,152097,152039,30584,143922,30478,30479,30587,149143,145281,14942,149744,29752,29851,16063,150202,150215,16584,150166,156078,37639,152961,30750,30861,30856,30930,29648,31065,161601,153315,16654,31131,33942,31141,27181,147194,31290,31220,16750,136934,16690,37429,31217,134476,149900,131737,146874,137070,13719,21867,13680,13994,131540,134157,31458,23129,141045,154287,154268,23053,131675,30960,23082,154566,31486,16889,31837,31853,16913,154547,155324,155302,31949,150009,137136,31886,31868,31918,27314,32220,32263,32211,32590,156257,155996,162632,32151,155266,17002,158581,133398,26582,131150,144847,22468,156690,156664,149858,32733,31527,133164,154345,154947,31500,155150,39398,34373,39523,27164,144447,14818,150007,157101,39455,157088,33920,160039,158929,17642,33079,17410,32966,33033,33090,157620,39107,158274,33378,33381,158289,33875,159143,34320,160283,23174,16767,137280,23339,137377,23268,137432,34464,195004,146831,34861,160802,23042,34926,20293,34951,35007,35046,35173,35149,153219,35156,161669,161668,166901,166873,166812,166393,16045,33955,18165,18127,14322,35389,35356,169032,24397,37419,148100,26068,28969,28868,137285,40301,35999,36073,163292,22938,30659,23024,17262,14036,36394,36519,150537,36656,36682,17140,27736,28603,140065,18587,28537,28299,137178,39913,14005,149807,37051,37015,21873,18694,37307,37892,166475,16482,166652,37927,166941,166971,34021,35371,38297,38311,38295,38294,167220,29765,16066,149759,150082,148458,16103,143909,38543,167655,167526,167525,16076,149997,150136,147438,29714,29803,16124,38721,168112,26695,18973,168083,153567,38749,37736,166281,166950,166703,156606,37562,23313,35689,18748,29689,147995,38811,38769,39224,134950,24001,166853,150194,38943,169178,37622,169431,37349,17600,166736,150119,166756,39132,166469,16128,37418,18725,33812,39227,39245,162566,15869,39323,19311,39338,39516,166757,153800,27279,39457,23294,39471,170225,19344,170312,39356,19389,19351,37757,22642,135938,22562,149944,136424,30788,141087,146872,26821,15741,37976,14631,24912,141185,141675,24839,40015,40019,40059,39989,39952,39807,39887,171565,39839,172533,172286,40225,19630,147716,40472,19632,40204,172468,172269,172275,170287,40357,33981,159250,159711,158594,34300,17715,159140,159364,159216,33824,34286,159232,145367,155748,31202,144796,144960,18733,149982,15714,37851,37566,37704,131775,30905,37495,37965,20452,13376,36964,152925,30781,30804,30902,30795,137047,143817,149825,13978,20338,28634,28633,28702,28702,21524,147893,22459,22771,22410,40214,22487,28980,13487,147884,29163,158784,151447,23336,137141,166473,24844,23246,23051,17084,148616,14124,19323,166396,37819,37816,137430,134941,33906,158912,136211,148218,142374,148417,22932,146871,157505,32168,155995,155812,149945,149899,166394,37605,29666,16105,29876,166755,137375,16097,150195,27352,29683,29691,16086,150078,150164,137177,150118,132007,136228,149989,29768,149782,28837,149878,37508,29670,37727,132350,37681,166606,166422,37766,166887,153045,18741,166530,29035,149827,134399,22180,132634,134123,134328,21762,31172,137210,32254,136898,150096,137298,17710,37889,14090,166592,149933,22960,137407,137347,160900,23201,14050,146779,14000,37471,23161,166529,137314,37748,15565,133812,19094,14730,20724,15721,15692,136092,29045,17147,164376,28175,168164,17643,27991,163407,28775,27823,15574,147437,146989,28162,28428,15727,132085,30033,14012,13512,18048,16090,18545,22980,37486,18750,36673,166940,158656,22546,22472,14038,136274,28926,148322,150129,143331,135856,140221,26809,26983,136088,144613,162804,145119,166531,145366,144378,150687,27162,145069,158903,33854,17631,17614,159014,159057,158850,159710,28439,160009,33597,137018,33773,158848,159827,137179,22921,23170,137139,23137,23153,137477,147964,14125,23023,137020,14023,29070,37776,26266,148133,23150,23083,148115,27179,147193,161590,148571,148170,28957,148057,166369,20400,159016,23746,148686,163405,148413,27148,148054,135940,28838,28979,148457,15781,27871,194597,150095,32357,23019,23855,15859,24412,150109,137183,32164,33830,21637,146170,144128,131604,22398,133333,132633,16357,139166,172726,28675,168283,23920,29583,31955,166489,168992,20424,32743,29389,29456,162548,29496,29497,153334,29505,29512,16041,162584,36972,29173,149746,29665,33270,16074,30476,16081,27810,22269,29721,29726,29727,16098,16112,16116,16122,29907,16142,16211,30018,30061,30066,30093,16252,30152,30172,16320,30285,16343,30324,16348,30330,151388,29064,22051,35200,22633,16413,30531,16441,26465,16453,13787,30616,16490,16495,23646,30654,30667,22770,30744,28857,30748,16552,30777,30791,30801,30822,33864,152885,31027,26627,31026,16643,16649,31121,31129,36795,31238,36796,16743,31377,16818,31420,33401,16836,31439,31451,16847,20001,31586,31596,31611,31762,31771,16992,17018,31867,31900,17036,31928,17044,31981,36755,28864,134351,32207,32212,32208,32253,32686,32692,29343,17303,32800,32805,31545,32814,32817,32852,15820,22452,28832,32951,33001,17389,33036,29482,33038,33042,30048,33044,17409,15161,33110,33113,33114,17427,22586,33148,33156,17445,33171,17453,33189,22511,33217,33252,33364,17551,33446,33398,33482,33496,33535,17584,33623,38505,27018,33797,28917,33892,24803,33928,17668,33982,34017,34040,34064,34104,34130,17723,34159,34160,34272,17783,34418,34450,34482,34543,38469,34699,17926,17943,34990,35071,35108,35143,35217,162151,35369,35384,35476,35508,35921,36052,36082,36124,18328,22623,36291,18413,20206,36410,21976,22356,36465,22005,36528,18487,36558,36578,36580,36589,36594,36791,36801,36810,36812,36915,39364,18605,39136,37395,18718,37416,37464,37483,37553,37550,37567,37603,37611,37619,37620,37629,37699,37764,37805,18757,18769,40639,37911,21249,37917,37933,37950,18794,37972,38009,38189,38306,18855,38388,38451,18917,26528,18980,38720,18997,38834,38850,22100,19172,24808,39097,19225,39153,22596,39182,39193,20916,39196,39223,39234,39261,39266,19312,39365,19357,39484,39695,31363,39785,39809,39901,39921,39924,19565,39968,14191,138178,40265,39994,40702,22096,40339,40381,40384,40444,38134,36790,40571,40620,40625,40637,40646,38108,40674,40689,40696,31432,40772,131220,131767,132000,26906,38083,22956,132311,22592,38081,14265,132565,132629,132726,136890,22359,29043,133826,133837,134079,21610,194619,134091,21662,134139,134203,134227,134245,134268,24807,134285,22138,134325,134365,134381,134511,134578,134600,26965,39983,34725,134660,134670,134871,135056,134957,134771,23584,135100,24075,135260,135247,135286,26398,135291,135304,135318,13895,135359,135379,135471,135483,21348,33965,135907,136053,135990,35713,136567,136729,137155,137159,20088,28859,137261,137578,137773,137797,138282,138352,138412,138952,25283,138965,139029,29080,26709,139333,27113,14024,139900,140247,140282,141098,141425,141647,33533,141671,141715,142037,35237,142056,36768,142094,38840,142143,38983,39613,142412,null,142472,142519,154600,142600,142610,142775,142741,142914,143220,143308,143411,143462,144159,144350,24497,26184,26303,162425,144743,144883,29185,149946,30679,144922,145174,32391,131910,22709,26382,26904,146087,161367,155618,146961,147129,161278,139418,18640,19128,147737,166554,148206,148237,147515,148276,148374,150085,132554,20946,132625,22943,138920,15294,146687,148484,148694,22408,149108,14747,149295,165352,170441,14178,139715,35678,166734,39382,149522,149755,150037,29193,150208,134264,22885,151205,151430,132985,36570,151596,21135,22335,29041,152217,152601,147274,150183,21948,152646,152686,158546,37332,13427,152895,161330,152926,18200,152930,152934,153543,149823,153693,20582,13563,144332,24798,153859,18300,166216,154286,154505,154630,138640,22433,29009,28598,155906,162834,36950,156082,151450,35682,156674,156746,23899,158711,36662,156804,137500,35562,150006,156808,147439,156946,19392,157119,157365,141083,37989,153569,24981,23079,194765,20411,22201,148769,157436,20074,149812,38486,28047,158909,13848,35191,157593,157806,156689,157790,29151,157895,31554,168128,133649,157990,37124,158009,31301,40432,158202,39462,158253,13919,156777,131105,31107,158260,158555,23852,144665,33743,158621,18128,158884,30011,34917,159150,22710,14108,140685,159819,160205,15444,160384,160389,37505,139642,160395,37680,160486,149968,27705,38047,160848,134904,34855,35061,141606,164979,137137,28344,150058,137248,14756,14009,23568,31203,17727,26294,171181,170148,35139,161740,161880,22230,16607,136714,14753,145199,164072,136133,29101,33638,162269,168360,23143,19639,159919,166315,162301,162314,162571,163174,147834,31555,31102,163849,28597,172767,27139,164632,21410,159239,37823,26678,38749,164207,163875,158133,136173,143919,163912,23941,166960,163971,22293,38947,166217,23979,149896,26046,27093,21458,150181,147329,15377,26422,163984,164084,164142,139169,164175,164233,164271,164378,164614,164655,164746,13770,164968,165546,18682,25574,166230,30728,37461,166328,17394,166375,17375,166376,166726,166868,23032,166921,36619,167877,168172,31569,168208,168252,15863,168286,150218,36816,29327,22155,169191,169449,169392,169400,169778,170193,170313,170346,170435,170536,170766,171354,171419,32415,171768,171811,19620,38215,172691,29090,172799,19857,36882,173515,19868,134300,36798,21953,36794,140464,36793,150163,17673,32383,28502,27313,20202,13540,166700,161949,14138,36480,137205,163876,166764,166809,162366,157359,15851,161365,146615,153141,153942,20122,155265,156248,22207,134765,36366,23405,147080,150686,25566,25296,137206,137339,25904,22061,154698,21530,152337,15814,171416,19581,22050,22046,32585,155352,22901,146752,34672,19996,135146,134473,145082,33047,40286,36120,30267,40005,30286,30649,37701,21554,33096,33527,22053,33074,33816,32957,21994,31074,22083,21526,134813,13774,22021,22001,26353,164578,13869,30004,22000,21946,21655,21874,134209,134294,24272,151880,134774,142434,134818,40619,32090,21982,135285,25245,38765,21652,36045,29174,37238,25596,25529,25598,21865,142147,40050,143027,20890,13535,134567,20903,21581,21790,21779,30310,36397,157834,30129,32950,34820,34694,35015,33206,33820,135361,17644,29444,149254,23440,33547,157843,22139,141044,163119,147875,163187,159440,160438,37232,135641,37384,146684,173737,134828,134905,29286,138402,18254,151490,163833,135147,16634,40029,25887,142752,18675,149472,171388,135148,134666,24674,161187,135149,null,155720,135559,29091,32398,40272,19994,19972,13687,23309,27826,21351,13996,14812,21373,13989,149016,22682,150382,33325,21579,22442,154261,133497,null,14930,140389,29556,171692,19721,39917,146686,171824,19547,151465,169374,171998,33884,146870,160434,157619,145184,25390,32037,147191,146988,14890,36872,21196,15988,13946,17897,132238,30272,23280,134838,30842,163630,22695,16575,22140,39819,23924,30292,173108,40581,19681,30201,14331,24857,143578,148466,null,22109,135849,22439,149859,171526,21044,159918,13741,27722,40316,31830,39737,22494,137068,23635,25811,169168,156469,160100,34477,134440,159010,150242,134513,null,20990,139023,23950,38659,138705,40577,36940,31519,39682,23761,31651,25192,25397,39679,31695,39722,31870,39726,31810,31878,39957,31740,39689,40727,39963,149822,40794,21875,23491,20477,40600,20466,21088,15878,21201,22375,20566,22967,24082,38856,40363,36700,21609,38836,39232,38842,21292,24880,26924,21466,39946,40194,19515,38465,27008,20646,30022,137069,39386,21107,null,37209,38529,37212,null,37201,167575,25471,159011,27338,22033,37262,30074,25221,132092,29519,31856,154657,146685,null,149785,30422,39837,20010,134356,33726,34882,null,23626,27072,20717,22394,21023,24053,20174,27697,131570,20281,21660,21722,21146,36226,13822,24332,13811,null,27474,37244,40869,39831,38958,39092,39610,40616,40580,29050,31508,null,27642,34840,32632,null,22048,173642,36471,40787,null,36308,36431,40476,36353,25218,164733,36392,36469,31443,150135,31294,30936,27882,35431,30215,166490,40742,27854,34774,30147,172722,30803,194624,36108,29410,29553,35629,29442,29937,36075,150203,34351,24506,34976,17591,null,137275,159237,null,35454,140571,null,24829,30311,39639,40260,37742,39823,34805,null,34831,36087,29484,38689,39856,13782,29362,19463,31825,39242,155993,24921,19460,40598,24957,null,22367,24943,25254,25145,25294,14940,25058,21418,144373,25444,26626,13778,23895,166850,36826,167481,null,20697,138566,30982,21298,38456,134971,16485,null,30718,null,31938,155418,31962,31277,32870,32867,32077,29957,29938,35220,33306,26380,32866,160902,32859,29936,33027,30500,35209,157644,30035,159441,34729,34766,33224,34700,35401,36013,35651,30507,29944,34010,13877,27058,36262,null,35241,29800,28089,34753,147473,29927,15835,29046,24740,24988,15569,29026,24695,null,32625,166701,29264,24809,19326,21024,15384,146631,155351,161366,152881,137540,135934,170243,159196,159917,23745,156077,166415,145015,131310,157766,151310,17762,23327,156492,40784,40614,156267,12288,65292,12289,12290,65294,8231,65307,65306,65311,65281,65072,8230,8229,65104,65105,65106,183,65108,65109,65110,65111,65372,8211,65073,8212,65075,9588,65076,65103,65288,65289,65077,65078,65371,65373,65079,65080,12308,12309,65081,65082,12304,12305,65083,65084,12298,12299,65085,65086,12296,12297,65087,65088,12300,12301,65089,65090,12302,12303,65091,65092,65113,65114,65115,65116,65117,65118,8216,8217,8220,8221,12317,12318,8245,8242,65283,65286,65290,8251,167,12291,9675,9679,9651,9650,9678,9734,9733,9671,9670,9633,9632,9661,9660,12963,8453,175,65507,65343,717,65097,65098,65101,65102,65099,65100,65119,65120,65121,65291,65293,215,247,177,8730,65308,65310,65309,8806,8807,8800,8734,8786,8801,65122,65123,65124,65125,65126,65374,8745,8746,8869,8736,8735,8895,13266,13265,8747,8750,8757,8756,9792,9794,8853,8857,8593,8595,8592,8594,8598,8599,8601,8600,8741,8739,65295,65340,8725,65128,65284,65509,12306,65504,65505,65285,65312,8451,8457,65129,65130,65131,13269,13212,13213,13214,13262,13217,13198,13199,13252,176,20825,20827,20830,20829,20833,20835,21991,29929,31950,9601,9602,9603,9604,9605,9606,9607,9608,9615,9614,9613,9612,9611,9610,9609,9532,9524,9516,9508,9500,9620,9472,9474,9621,9484,9488,9492,9496,9581,9582,9584,9583,9552,9566,9578,9569,9698,9699,9701,9700,9585,9586,9587,65296,65297,65298,65299,65300,65301,65302,65303,65304,65305,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,12321,12322,12323,12324,12325,12326,12327,12328,12329,21313,21316,21317,65313,65314,65315,65316,65317,65318,65319,65320,65321,65322,65323,65324,65325,65326,65327,65328,65329,65330,65331,65332,65333,65334,65335,65336,65337,65338,65345,65346,65347,65348,65349,65350,65351,65352,65353,65354,65355,65356,65357,65358,65359,65360,65361,65362,65363,65364,65365,65366,65367,65368,65369,65370,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,963,964,965,966,967,968,969,12549,12550,12551,12552,12553,12554,12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570,12571,12572,12573,12574,12575,12576,12577,12578,12579,12580,12581,12582,12583,12584,12585,729,713,714,711,715,9216,9217,9218,9219,9220,9221,9222,9223,9224,9225,9226,9227,9228,9229,9230,9231,9232,9233,9234,9235,9236,9237,9238,9239,9240,9241,9242,9243,9244,9245,9246,9247,9249,8364,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,19968,20057,19969,19971,20035,20061,20102,20108,20154,20799,20837,20843,20960,20992,20993,21147,21269,21313,21340,21448,19977,19979,19976,19978,20011,20024,20961,20037,20040,20063,20062,20110,20129,20800,20995,21242,21315,21449,21475,22303,22763,22805,22823,22899,23376,23377,23379,23544,23567,23586,23608,23665,24029,24037,24049,24050,24051,24062,24178,24318,24331,24339,25165,19985,19984,19981,20013,20016,20025,20043,23609,20104,20113,20117,20114,20116,20130,20161,20160,20163,20166,20167,20173,20170,20171,20164,20803,20801,20839,20845,20846,20844,20887,20982,20998,20999,21000,21243,21246,21247,21270,21305,21320,21319,21317,21342,21380,21451,21450,21453,22764,22825,22827,22826,22829,23380,23569,23588,23610,23663,24052,24187,24319,24340,24341,24515,25096,25142,25163,25166,25903,25991,26007,26020,26041,26085,26352,26376,26408,27424,27490,27513,27595,27604,27611,27663,27700,28779,29226,29238,29243,29255,29273,29275,29356,29579,19993,19990,19989,19988,19992,20027,20045,20047,20046,20197,20184,20180,20181,20182,20183,20195,20196,20185,20190,20805,20804,20873,20874,20908,20985,20986,20984,21002,21152,21151,21253,21254,21271,21277,20191,21322,21321,21345,21344,21359,21358,21435,21487,21476,21491,21484,21486,21481,21480,21500,21496,21493,21483,21478,21482,21490,21489,21488,21477,21485,21499,22235,22234,22806,22830,22833,22900,22902,23381,23427,23612,24040,24039,24038,24066,24067,24179,24188,24321,24344,24343,24517,25098,25171,25172,25170,25169,26021,26086,26414,26412,26410,26411,26413,27491,27597,27665,27664,27704,27713,27712,27710,29359,29572,29577,29916,29926,29976,29983,29992,29993,30000,30001,30002,30003,30091,30333,30382,30399,30446,30683,30690,30707,31034,31166,31348,31435,19998,19999,20050,20051,20073,20121,20132,20134,20133,20223,20233,20249,20234,20245,20237,20240,20241,20239,20210,20214,20219,20208,20211,20221,20225,20235,20809,20807,20806,20808,20840,20849,20877,20912,21015,21009,21010,21006,21014,21155,21256,21281,21280,21360,21361,21513,21519,21516,21514,21520,21505,21515,21508,21521,21517,21512,21507,21518,21510,21522,22240,22238,22237,22323,22320,22312,22317,22316,22319,22313,22809,22810,22839,22840,22916,22904,22915,22909,22905,22914,22913,23383,23384,23431,23432,23429,23433,23546,23574,23673,24030,24070,24182,24180,24335,24347,24537,24534,25102,25100,25101,25104,25187,25179,25176,25910,26089,26088,26092,26093,26354,26355,26377,26429,26420,26417,26421,27425,27492,27515,27670,27741,27735,27737,27743,27744,27728,27733,27745,27739,27725,27726,28784,29279,29277,30334,31481,31859,31992,32566,32650,32701,32769,32771,32780,32786,32819,32895,32905,32907,32908,33251,33258,33267,33276,33292,33307,33311,33390,33394,33406,34411,34880,34892,34915,35199,38433,20018,20136,20301,20303,20295,20311,20318,20276,20315,20309,20272,20304,20305,20285,20282,20280,20291,20308,20284,20294,20323,20316,20320,20271,20302,20278,20313,20317,20296,20314,20812,20811,20813,20853,20918,20919,21029,21028,21033,21034,21032,21163,21161,21162,21164,21283,21363,21365,21533,21549,21534,21566,21542,21582,21543,21574,21571,21555,21576,21570,21531,21545,21578,21561,21563,21560,21550,21557,21558,21536,21564,21568,21553,21547,21535,21548,22250,22256,22244,22251,22346,22353,22336,22349,22343,22350,22334,22352,22351,22331,22767,22846,22941,22930,22952,22942,22947,22937,22934,22925,22948,22931,22922,22949,23389,23388,23386,23387,23436,23435,23439,23596,23616,23617,23615,23614,23696,23697,23700,23692,24043,24076,24207,24199,24202,24311,24324,24351,24420,24418,24439,24441,24536,24524,24535,24525,24561,24555,24568,24554,25106,25105,25220,25239,25238,25216,25206,25225,25197,25226,25212,25214,25209,25203,25234,25199,25240,25198,25237,25235,25233,25222,25913,25915,25912,26097,26356,26463,26446,26447,26448,26449,26460,26454,26462,26441,26438,26464,26451,26455,27493,27599,27714,27742,27801,27777,27784,27785,27781,27803,27754,27770,27792,27760,27788,27752,27798,27794,27773,27779,27762,27774,27764,27782,27766,27789,27796,27800,27778,28790,28796,28797,28792,29282,29281,29280,29380,29378,29590,29996,29995,30007,30008,30338,30447,30691,31169,31168,31167,31350,31995,32597,32918,32915,32925,32920,32923,32922,32946,33391,33426,33419,33421,35211,35282,35328,35895,35910,35925,35997,36196,36208,36275,36523,36554,36763,36784,36802,36806,36805,36804,24033,37009,37026,37034,37030,37027,37193,37318,37324,38450,38446,38449,38442,38444,20006,20054,20083,20107,20123,20126,20139,20140,20335,20381,20365,20339,20351,20332,20379,20363,20358,20355,20336,20341,20360,20329,20347,20374,20350,20367,20369,20346,20820,20818,20821,20841,20855,20854,20856,20925,20989,21051,21048,21047,21050,21040,21038,21046,21057,21182,21179,21330,21332,21331,21329,21350,21367,21368,21369,21462,21460,21463,21619,21621,21654,21624,21653,21632,21627,21623,21636,21650,21638,21628,21648,21617,21622,21644,21658,21602,21608,21643,21629,21646,22266,22403,22391,22378,22377,22369,22374,22372,22396,22812,22857,22855,22856,22852,22868,22974,22971,22996,22969,22958,22993,22982,22992,22989,22987,22995,22986,22959,22963,22994,22981,23391,23396,23395,23447,23450,23448,23452,23449,23451,23578,23624,23621,23622,23735,23713,23736,23721,23723,23729,23731,24088,24090,24086,24085,24091,24081,24184,24218,24215,24220,24213,24214,24310,24358,24359,24361,24448,24449,24447,24444,24541,24544,24573,24565,24575,24591,24596,24623,24629,24598,24618,24597,24609,24615,24617,24619,24603,25110,25109,25151,25150,25152,25215,25289,25292,25284,25279,25282,25273,25298,25307,25259,25299,25300,25291,25288,25256,25277,25276,25296,25305,25287,25293,25269,25306,25265,25304,25302,25303,25286,25260,25294,25918,26023,26044,26106,26132,26131,26124,26118,26114,26126,26112,26127,26133,26122,26119,26381,26379,26477,26507,26517,26481,26524,26483,26487,26503,26525,26519,26479,26480,26495,26505,26494,26512,26485,26522,26515,26492,26474,26482,27427,27494,27495,27519,27667,27675,27875,27880,27891,27825,27852,27877,27827,27837,27838,27836,27874,27819,27861,27859,27832,27844,27833,27841,27822,27863,27845,27889,27839,27835,27873,27867,27850,27820,27887,27868,27862,27872,28821,28814,28818,28810,28825,29228,29229,29240,29256,29287,29289,29376,29390,29401,29399,29392,29609,29608,29599,29611,29605,30013,30109,30105,30106,30340,30402,30450,30452,30693,30717,31038,31040,31041,31177,31176,31354,31353,31482,31998,32596,32652,32651,32773,32954,32933,32930,32945,32929,32939,32937,32948,32938,32943,33253,33278,33293,33459,33437,33433,33453,33469,33439,33465,33457,33452,33445,33455,33464,33443,33456,33470,33463,34382,34417,21021,34920,36555,36814,36820,36817,37045,37048,37041,37046,37319,37329,38263,38272,38428,38464,38463,38459,38468,38466,38585,38632,38738,38750,20127,20141,20142,20449,20405,20399,20415,20448,20433,20431,20445,20419,20406,20440,20447,20426,20439,20398,20432,20420,20418,20442,20430,20446,20407,20823,20882,20881,20896,21070,21059,21066,21069,21068,21067,21063,21191,21193,21187,21185,21261,21335,21371,21402,21467,21676,21696,21672,21710,21705,21688,21670,21683,21703,21698,21693,21674,21697,21700,21704,21679,21675,21681,21691,21673,21671,21695,22271,22402,22411,22432,22435,22434,22478,22446,22419,22869,22865,22863,22862,22864,23004,23000,23039,23011,23016,23043,23013,23018,23002,23014,23041,23035,23401,23459,23462,23460,23458,23461,23553,23630,23631,23629,23627,23769,23762,24055,24093,24101,24095,24189,24224,24230,24314,24328,24365,24421,24456,24453,24458,24459,24455,24460,24457,24594,24605,24608,24613,24590,24616,24653,24688,24680,24674,24646,24643,24684,24683,24682,24676,25153,25308,25366,25353,25340,25325,25345,25326,25341,25351,25329,25335,25327,25324,25342,25332,25361,25346,25919,25925,26027,26045,26082,26149,26157,26144,26151,26159,26143,26152,26161,26148,26359,26623,26579,26609,26580,26576,26604,26550,26543,26613,26601,26607,26564,26577,26548,26586,26597,26552,26575,26590,26611,26544,26585,26594,26589,26578,27498,27523,27526,27573,27602,27607,27679,27849,27915,27954,27946,27969,27941,27916,27953,27934,27927,27963,27965,27966,27958,27931,27893,27961,27943,27960,27945,27950,27957,27918,27947,28843,28858,28851,28844,28847,28845,28856,28846,28836,29232,29298,29295,29300,29417,29408,29409,29623,29642,29627,29618,29645,29632,29619,29978,29997,30031,30028,30030,30027,30123,30116,30117,30114,30115,30328,30342,30343,30344,30408,30406,30403,30405,30465,30457,30456,30473,30475,30462,30460,30471,30684,30722,30740,30732,30733,31046,31049,31048,31047,31161,31162,31185,31186,31179,31359,31361,31487,31485,31869,32002,32005,32000,32009,32007,32004,32006,32568,32654,32703,32772,32784,32781,32785,32822,32982,32997,32986,32963,32964,32972,32993,32987,32974,32990,32996,32989,33268,33314,33511,33539,33541,33507,33499,33510,33540,33509,33538,33545,33490,33495,33521,33537,33500,33492,33489,33502,33491,33503,33519,33542,34384,34425,34427,34426,34893,34923,35201,35284,35336,35330,35331,35998,36000,36212,36211,36276,36557,36556,36848,36838,36834,36842,36837,36845,36843,36836,36840,37066,37070,37057,37059,37195,37194,37325,38274,38480,38475,38476,38477,38754,38761,38859,38893,38899,38913,39080,39131,39135,39318,39321,20056,20147,20492,20493,20515,20463,20518,20517,20472,20521,20502,20486,20540,20511,20506,20498,20497,20474,20480,20500,20520,20465,20513,20491,20505,20504,20467,20462,20525,20522,20478,20523,20489,20860,20900,20901,20898,20941,20940,20934,20939,21078,21084,21076,21083,21085,21290,21375,21407,21405,21471,21736,21776,21761,21815,21756,21733,21746,21766,21754,21780,21737,21741,21729,21769,21742,21738,21734,21799,21767,21757,21775,22275,22276,22466,22484,22475,22467,22537,22799,22871,22872,22874,23057,23064,23068,23071,23067,23059,23020,23072,23075,23081,23077,23052,23049,23403,23640,23472,23475,23478,23476,23470,23477,23481,23480,23556,23633,23637,23632,23789,23805,23803,23786,23784,23792,23798,23809,23796,24046,24109,24107,24235,24237,24231,24369,24466,24465,24464,24665,24675,24677,24656,24661,24685,24681,24687,24708,24735,24730,24717,24724,24716,24709,24726,25159,25331,25352,25343,25422,25406,25391,25429,25410,25414,25423,25417,25402,25424,25405,25386,25387,25384,25421,25420,25928,25929,26009,26049,26053,26178,26185,26191,26179,26194,26188,26181,26177,26360,26388,26389,26391,26657,26680,26696,26694,26707,26681,26690,26708,26665,26803,26647,26700,26705,26685,26612,26704,26688,26684,26691,26666,26693,26643,26648,26689,27530,27529,27575,27683,27687,27688,27686,27684,27888,28010,28053,28040,28039,28006,28024,28023,27993,28051,28012,28041,28014,27994,28020,28009,28044,28042,28025,28037,28005,28052,28874,28888,28900,28889,28872,28879,29241,29305,29436,29433,29437,29432,29431,29574,29677,29705,29678,29664,29674,29662,30036,30045,30044,30042,30041,30142,30149,30151,30130,30131,30141,30140,30137,30146,30136,30347,30384,30410,30413,30414,30505,30495,30496,30504,30697,30768,30759,30776,30749,30772,30775,30757,30765,30752,30751,30770,31061,31056,31072,31071,31062,31070,31069,31063,31066,31204,31203,31207,31199,31206,31209,31192,31364,31368,31449,31494,31505,31881,32033,32023,32011,32010,32032,32034,32020,32016,32021,32026,32028,32013,32025,32027,32570,32607,32660,32709,32705,32774,32792,32789,32793,32791,32829,32831,33009,33026,33008,33029,33005,33012,33030,33016,33011,33032,33021,33034,33020,33007,33261,33260,33280,33296,33322,33323,33320,33324,33467,33579,33618,33620,33610,33592,33616,33609,33589,33588,33615,33586,33593,33590,33559,33600,33585,33576,33603,34388,34442,34474,34451,34468,34473,34444,34467,34460,34928,34935,34945,34946,34941,34937,35352,35344,35342,35340,35349,35338,35351,35347,35350,35343,35345,35912,35962,35961,36001,36002,36215,36524,36562,36564,36559,36785,36865,36870,36855,36864,36858,36852,36867,36861,36869,36856,37013,37089,37085,37090,37202,37197,37196,37336,37341,37335,37340,37337,38275,38498,38499,38497,38491,38493,38500,38488,38494,38587,39138,39340,39592,39640,39717,39730,39740,20094,20602,20605,20572,20551,20547,20556,20570,20553,20581,20598,20558,20565,20597,20596,20599,20559,20495,20591,20589,20828,20885,20976,21098,21103,21202,21209,21208,21205,21264,21263,21273,21311,21312,21310,21443,26364,21830,21866,21862,21828,21854,21857,21827,21834,21809,21846,21839,21845,21807,21860,21816,21806,21852,21804,21859,21811,21825,21847,22280,22283,22281,22495,22533,22538,22534,22496,22500,22522,22530,22581,22519,22521,22816,22882,23094,23105,23113,23142,23146,23104,23100,23138,23130,23110,23114,23408,23495,23493,23492,23490,23487,23494,23561,23560,23559,23648,23644,23645,23815,23814,23822,23835,23830,23842,23825,23849,23828,23833,23844,23847,23831,24034,24120,24118,24115,24119,24247,24248,24246,24245,24254,24373,24375,24407,24428,24425,24427,24471,24473,24478,24472,24481,24480,24476,24703,24739,24713,24736,24744,24779,24756,24806,24765,24773,24763,24757,24796,24764,24792,24789,24774,24799,24760,24794,24775,25114,25115,25160,25504,25511,25458,25494,25506,25509,25463,25447,25496,25514,25457,25513,25481,25475,25499,25451,25512,25476,25480,25497,25505,25516,25490,25487,25472,25467,25449,25448,25466,25949,25942,25937,25945,25943,21855,25935,25944,25941,25940,26012,26011,26028,26063,26059,26060,26062,26205,26202,26212,26216,26214,26206,26361,21207,26395,26753,26799,26786,26771,26805,26751,26742,26801,26791,26775,26800,26755,26820,26797,26758,26757,26772,26781,26792,26783,26785,26754,27442,27578,27627,27628,27691,28046,28092,28147,28121,28082,28129,28108,28132,28155,28154,28165,28103,28107,28079,28113,28078,28126,28153,28088,28151,28149,28101,28114,28186,28085,28122,28139,28120,28138,28145,28142,28136,28102,28100,28074,28140,28095,28134,28921,28937,28938,28925,28911,29245,29309,29313,29468,29467,29462,29459,29465,29575,29701,29706,29699,29702,29694,29709,29920,29942,29943,29980,29986,30053,30054,30050,30064,30095,30164,30165,30133,30154,30157,30350,30420,30418,30427,30519,30526,30524,30518,30520,30522,30827,30787,30798,31077,31080,31085,31227,31378,31381,31520,31528,31515,31532,31526,31513,31518,31534,31890,31895,31893,32070,32067,32113,32046,32057,32060,32064,32048,32051,32068,32047,32066,32050,32049,32573,32670,32666,32716,32718,32722,32796,32842,32838,33071,33046,33059,33067,33065,33072,33060,33282,33333,33335,33334,33337,33678,33694,33688,33656,33698,33686,33725,33707,33682,33674,33683,33673,33696,33655,33659,33660,33670,33703,34389,24426,34503,34496,34486,34500,34485,34502,34507,34481,34479,34505,34899,34974,34952,34987,34962,34966,34957,34955,35219,35215,35370,35357,35363,35365,35377,35373,35359,35355,35362,35913,35930,36009,36012,36011,36008,36010,36007,36199,36198,36286,36282,36571,36575,36889,36877,36890,36887,36899,36895,36893,36880,36885,36894,36896,36879,36898,36886,36891,36884,37096,37101,37117,37207,37326,37365,37350,37347,37351,37357,37353,38281,38506,38517,38515,38520,38512,38516,38518,38519,38508,38592,38634,38633,31456,31455,38914,38915,39770,40165,40565,40575,40613,40635,20642,20621,20613,20633,20625,20608,20630,20632,20634,26368,20977,21106,21108,21109,21097,21214,21213,21211,21338,21413,21883,21888,21927,21884,21898,21917,21912,21890,21916,21930,21908,21895,21899,21891,21939,21934,21919,21822,21938,21914,21947,21932,21937,21886,21897,21931,21913,22285,22575,22570,22580,22564,22576,22577,22561,22557,22560,22777,22778,22880,23159,23194,23167,23186,23195,23207,23411,23409,23506,23500,23507,23504,23562,23563,23601,23884,23888,23860,23879,24061,24133,24125,24128,24131,24190,24266,24257,24258,24260,24380,24429,24489,24490,24488,24785,24801,24754,24758,24800,24860,24867,24826,24853,24816,24827,24820,24936,24817,24846,24822,24841,24832,24850,25119,25161,25507,25484,25551,25536,25577,25545,25542,25549,25554,25571,25552,25569,25558,25581,25582,25462,25588,25578,25563,25682,25562,25593,25950,25958,25954,25955,26001,26000,26031,26222,26224,26228,26230,26223,26257,26234,26238,26231,26366,26367,26399,26397,26874,26837,26848,26840,26839,26885,26847,26869,26862,26855,26873,26834,26866,26851,26827,26829,26893,26898,26894,26825,26842,26990,26875,27454,27450,27453,27544,27542,27580,27631,27694,27695,27692,28207,28216,28244,28193,28210,28263,28234,28192,28197,28195,28187,28251,28248,28196,28246,28270,28205,28198,28271,28212,28237,28218,28204,28227,28189,28222,28363,28297,28185,28238,28259,28228,28274,28265,28255,28953,28954,28966,28976,28961,28982,29038,28956,29260,29316,29312,29494,29477,29492,29481,29754,29738,29747,29730,29733,29749,29750,29748,29743,29723,29734,29736,29989,29990,30059,30058,30178,30171,30179,30169,30168,30174,30176,30331,30332,30358,30355,30388,30428,30543,30701,30813,30828,30831,31245,31240,31243,31237,31232,31384,31383,31382,31461,31459,31561,31574,31558,31568,31570,31572,31565,31563,31567,31569,31903,31909,32094,32080,32104,32085,32043,32110,32114,32097,32102,32098,32112,32115,21892,32724,32725,32779,32850,32901,33109,33108,33099,33105,33102,33081,33094,33086,33100,33107,33140,33298,33308,33769,33795,33784,33805,33760,33733,33803,33729,33775,33777,33780,33879,33802,33776,33804,33740,33789,33778,33738,33848,33806,33796,33756,33799,33748,33759,34395,34527,34521,34541,34516,34523,34532,34512,34526,34903,35009,35010,34993,35203,35222,35387,35424,35413,35422,35388,35393,35412,35419,35408,35398,35380,35386,35382,35414,35937,35970,36015,36028,36019,36029,36033,36027,36032,36020,36023,36022,36031,36024,36234,36229,36225,36302,36317,36299,36314,36305,36300,36315,36294,36603,36600,36604,36764,36910,36917,36913,36920,36914,36918,37122,37109,37129,37118,37219,37221,37327,37396,37397,37411,37385,37406,37389,37392,37383,37393,38292,38287,38283,38289,38291,38290,38286,38538,38542,38539,38525,38533,38534,38541,38514,38532,38593,38597,38596,38598,38599,38639,38642,38860,38917,38918,38920,39143,39146,39151,39145,39154,39149,39342,39341,40643,40653,40657,20098,20653,20661,20658,20659,20677,20670,20652,20663,20667,20655,20679,21119,21111,21117,21215,21222,21220,21218,21219,21295,21983,21992,21971,21990,21966,21980,21959,21969,21987,21988,21999,21978,21985,21957,21958,21989,21961,22290,22291,22622,22609,22616,22615,22618,22612,22635,22604,22637,22602,22626,22610,22603,22887,23233,23241,23244,23230,23229,23228,23219,23234,23218,23913,23919,24140,24185,24265,24264,24338,24409,24492,24494,24858,24847,24904,24863,24819,24859,24825,24833,24840,24910,24908,24900,24909,24894,24884,24871,24845,24838,24887,25121,25122,25619,25662,25630,25642,25645,25661,25644,25615,25628,25620,25613,25654,25622,25623,25606,25964,26015,26032,26263,26249,26247,26248,26262,26244,26264,26253,26371,27028,26989,26970,26999,26976,26964,26997,26928,27010,26954,26984,26987,26974,26963,27001,27014,26973,26979,26971,27463,27506,27584,27583,27603,27645,28322,28335,28371,28342,28354,28304,28317,28359,28357,28325,28312,28348,28346,28331,28369,28310,28316,28356,28372,28330,28327,28340,29006,29017,29033,29028,29001,29031,29020,29036,29030,29004,29029,29022,28998,29032,29014,29242,29266,29495,29509,29503,29502,29807,29786,29781,29791,29790,29761,29759,29785,29787,29788,30070,30072,30208,30192,30209,30194,30193,30202,30207,30196,30195,30430,30431,30555,30571,30566,30558,30563,30585,30570,30572,30556,30565,30568,30562,30702,30862,30896,30871,30872,30860,30857,30844,30865,30867,30847,31098,31103,31105,33836,31165,31260,31258,31264,31252,31263,31262,31391,31392,31607,31680,31584,31598,31591,31921,31923,31925,32147,32121,32145,32129,32143,32091,32622,32617,32618,32626,32681,32680,32676,32854,32856,32902,32900,33137,33136,33144,33125,33134,33139,33131,33145,33146,33126,33285,33351,33922,33911,33853,33841,33909,33894,33899,33865,33900,33883,33852,33845,33889,33891,33897,33901,33862,34398,34396,34399,34553,34579,34568,34567,34560,34558,34555,34562,34563,34566,34570,34905,35039,35028,35033,35036,35032,35037,35041,35018,35029,35026,35228,35299,35435,35442,35443,35430,35433,35440,35463,35452,35427,35488,35441,35461,35437,35426,35438,35436,35449,35451,35390,35432,35938,35978,35977,36042,36039,36040,36036,36018,36035,36034,36037,36321,36319,36328,36335,36339,36346,36330,36324,36326,36530,36611,36617,36606,36618,36767,36786,36939,36938,36947,36930,36948,36924,36949,36944,36935,36943,36942,36941,36945,36926,36929,37138,37143,37228,37226,37225,37321,37431,37463,37432,37437,37440,37438,37467,37451,37476,37457,37428,37449,37453,37445,37433,37439,37466,38296,38552,38548,38549,38605,38603,38601,38602,38647,38651,38649,38646,38742,38772,38774,38928,38929,38931,38922,38930,38924,39164,39156,39165,39166,39347,39345,39348,39649,40169,40578,40718,40723,40736,20711,20718,20709,20694,20717,20698,20693,20687,20689,20721,20686,20713,20834,20979,21123,21122,21297,21421,22014,22016,22043,22039,22013,22036,22022,22025,22029,22030,22007,22038,22047,22024,22032,22006,22296,22294,22645,22654,22659,22675,22666,22649,22661,22653,22781,22821,22818,22820,22890,22889,23265,23270,23273,23255,23254,23256,23267,23413,23518,23527,23521,23525,23526,23528,23522,23524,23519,23565,23650,23940,23943,24155,24163,24149,24151,24148,24275,24278,24330,24390,24432,24505,24903,24895,24907,24951,24930,24931,24927,24922,24920,24949,25130,25735,25688,25684,25764,25720,25695,25722,25681,25703,25652,25709,25723,25970,26017,26071,26070,26274,26280,26269,27036,27048,27029,27073,27054,27091,27083,27035,27063,27067,27051,27060,27088,27085,27053,27084,27046,27075,27043,27465,27468,27699,28467,28436,28414,28435,28404,28457,28478,28448,28460,28431,28418,28450,28415,28399,28422,28465,28472,28466,28451,28437,28459,28463,28552,28458,28396,28417,28402,28364,28407,29076,29081,29053,29066,29060,29074,29246,29330,29334,29508,29520,29796,29795,29802,29808,29805,29956,30097,30247,30221,30219,30217,30227,30433,30435,30596,30589,30591,30561,30913,30879,30887,30899,30889,30883,31118,31119,31117,31278,31281,31402,31401,31469,31471,31649,31637,31627,31605,31639,31645,31636,31631,31672,31623,31620,31929,31933,31934,32187,32176,32156,32189,32190,32160,32202,32180,32178,32177,32186,32162,32191,32181,32184,32173,32210,32199,32172,32624,32736,32737,32735,32862,32858,32903,33104,33152,33167,33160,33162,33151,33154,33255,33274,33287,33300,33310,33355,33993,33983,33990,33988,33945,33950,33970,33948,33995,33976,33984,34003,33936,33980,34001,33994,34623,34588,34619,34594,34597,34612,34584,34645,34615,34601,35059,35074,35060,35065,35064,35069,35048,35098,35055,35494,35468,35486,35491,35469,35489,35475,35492,35498,35493,35496,35480,35473,35482,35495,35946,35981,35980,36051,36049,36050,36203,36249,36245,36348,36628,36626,36629,36627,36771,36960,36952,36956,36963,36953,36958,36962,36957,36955,37145,37144,37150,37237,37240,37239,37236,37496,37504,37509,37528,37526,37499,37523,37532,37544,37500,37521,38305,38312,38313,38307,38309,38308,38553,38556,38555,38604,38610,38656,38780,38789,38902,38935,38936,39087,39089,39171,39173,39180,39177,39361,39599,39600,39654,39745,39746,40180,40182,40179,40636,40763,40778,20740,20736,20731,20725,20729,20738,20744,20745,20741,20956,21127,21128,21129,21133,21130,21232,21426,22062,22075,22073,22066,22079,22068,22057,22099,22094,22103,22132,22070,22063,22064,22656,22687,22686,22707,22684,22702,22697,22694,22893,23305,23291,23307,23285,23308,23304,23534,23532,23529,23531,23652,23653,23965,23956,24162,24159,24161,24290,24282,24287,24285,24291,24288,24392,24433,24503,24501,24950,24935,24942,24925,24917,24962,24956,24944,24939,24958,24999,24976,25003,24974,25004,24986,24996,24980,25006,25134,25705,25711,25721,25758,25778,25736,25744,25776,25765,25747,25749,25769,25746,25774,25773,25771,25754,25772,25753,25762,25779,25973,25975,25976,26286,26283,26292,26289,27171,27167,27112,27137,27166,27161,27133,27169,27155,27146,27123,27138,27141,27117,27153,27472,27470,27556,27589,27590,28479,28540,28548,28497,28518,28500,28550,28525,28507,28536,28526,28558,28538,28528,28516,28567,28504,28373,28527,28512,28511,29087,29100,29105,29096,29270,29339,29518,29527,29801,29835,29827,29822,29824,30079,30240,30249,30239,30244,30246,30241,30242,30362,30394,30436,30606,30599,30604,30609,30603,30923,30917,30906,30922,30910,30933,30908,30928,31295,31292,31296,31293,31287,31291,31407,31406,31661,31665,31684,31668,31686,31687,31681,31648,31692,31946,32224,32244,32239,32251,32216,32236,32221,32232,32227,32218,32222,32233,32158,32217,32242,32249,32629,32631,32687,32745,32806,33179,33180,33181,33184,33178,33176,34071,34109,34074,34030,34092,34093,34067,34065,34083,34081,34068,34028,34085,34047,34054,34690,34676,34678,34656,34662,34680,34664,34649,34647,34636,34643,34907,34909,35088,35079,35090,35091,35093,35082,35516,35538,35527,35524,35477,35531,35576,35506,35529,35522,35519,35504,35542,35533,35510,35513,35547,35916,35918,35948,36064,36062,36070,36068,36076,36077,36066,36067,36060,36074,36065,36205,36255,36259,36395,36368,36381,36386,36367,36393,36383,36385,36382,36538,36637,36635,36639,36649,36646,36650,36636,36638,36645,36969,36974,36968,36973,36983,37168,37165,37159,37169,37255,37257,37259,37251,37573,37563,37559,37610,37548,37604,37569,37555,37564,37586,37575,37616,37554,38317,38321,38660,38662,38663,38665,38752,38797,38795,38799,38945,38955,38940,39091,39178,39187,39186,39192,39389,39376,39391,39387,39377,39381,39378,39385,39607,39662,39663,39719,39749,39748,39799,39791,40198,40201,40195,40617,40638,40654,22696,40786,20754,20760,20756,20752,20757,20864,20906,20957,21137,21139,21235,22105,22123,22137,22121,22116,22136,22122,22120,22117,22129,22127,22124,22114,22134,22721,22718,22727,22725,22894,23325,23348,23416,23536,23566,24394,25010,24977,25001,24970,25037,25014,25022,25034,25032,25136,25797,25793,25803,25787,25788,25818,25796,25799,25794,25805,25791,25810,25812,25790,25972,26310,26313,26297,26308,26311,26296,27197,27192,27194,27225,27243,27224,27193,27204,27234,27233,27211,27207,27189,27231,27208,27481,27511,27653,28610,28593,28577,28611,28580,28609,28583,28595,28608,28601,28598,28582,28576,28596,29118,29129,29136,29138,29128,29141,29113,29134,29145,29148,29123,29124,29544,29852,29859,29848,29855,29854,29922,29964,29965,30260,30264,30266,30439,30437,30624,30622,30623,30629,30952,30938,30956,30951,31142,31309,31310,31302,31308,31307,31418,31705,31761,31689,31716,31707,31713,31721,31718,31957,31958,32266,32273,32264,32283,32291,32286,32285,32265,32272,32633,32690,32752,32753,32750,32808,33203,33193,33192,33275,33288,33368,33369,34122,34137,34120,34152,34153,34115,34121,34157,34154,34142,34691,34719,34718,34722,34701,34913,35114,35122,35109,35115,35105,35242,35238,35558,35578,35563,35569,35584,35548,35559,35566,35582,35585,35586,35575,35565,35571,35574,35580,35947,35949,35987,36084,36420,36401,36404,36418,36409,36405,36667,36655,36664,36659,36776,36774,36981,36980,36984,36978,36988,36986,37172,37266,37664,37686,37624,37683,37679,37666,37628,37675,37636,37658,37648,37670,37665,37653,37678,37657,38331,38567,38568,38570,38613,38670,38673,38678,38669,38675,38671,38747,38748,38758,38808,38960,38968,38971,38967,38957,38969,38948,39184,39208,39198,39195,39201,39194,39405,39394,39409,39608,39612,39675,39661,39720,39825,40213,40227,40230,40232,40210,40219,40664,40660,40845,40860,20778,20767,20769,20786,21237,22158,22144,22160,22149,22151,22159,22741,22739,22737,22734,23344,23338,23332,23418,23607,23656,23996,23994,23997,23992,24171,24396,24509,25033,25026,25031,25062,25035,25138,25140,25806,25802,25816,25824,25840,25830,25836,25841,25826,25837,25986,25987,26329,26326,27264,27284,27268,27298,27292,27355,27299,27262,27287,27280,27296,27484,27566,27610,27656,28632,28657,28639,28640,28635,28644,28651,28655,28544,28652,28641,28649,28629,28654,28656,29159,29151,29166,29158,29157,29165,29164,29172,29152,29237,29254,29552,29554,29865,29872,29862,29864,30278,30274,30284,30442,30643,30634,30640,30636,30631,30637,30703,30967,30970,30964,30959,30977,31143,31146,31319,31423,31751,31757,31742,31735,31756,31712,31968,31964,31966,31970,31967,31961,31965,32302,32318,32326,32311,32306,32323,32299,32317,32305,32325,32321,32308,32313,32328,32309,32319,32303,32580,32755,32764,32881,32882,32880,32879,32883,33222,33219,33210,33218,33216,33215,33213,33225,33214,33256,33289,33393,34218,34180,34174,34204,34193,34196,34223,34203,34183,34216,34186,34407,34752,34769,34739,34770,34758,34731,34747,34746,34760,34763,35131,35126,35140,35128,35133,35244,35598,35607,35609,35611,35594,35616,35613,35588,35600,35905,35903,35955,36090,36093,36092,36088,36091,36264,36425,36427,36424,36426,36676,36670,36674,36677,36671,36991,36989,36996,36993,36994,36992,37177,37283,37278,37276,37709,37762,37672,37749,37706,37733,37707,37656,37758,37740,37723,37744,37722,37716,38346,38347,38348,38344,38342,38577,38584,38614,38684,38686,38816,38867,38982,39094,39221,39425,39423,39854,39851,39850,39853,40251,40255,40587,40655,40670,40668,40669,40667,40766,40779,21474,22165,22190,22745,22744,23352,24413,25059,25139,25844,25842,25854,25862,25850,25851,25847,26039,26332,26406,27315,27308,27331,27323,27320,27330,27310,27311,27487,27512,27567,28681,28683,28670,28678,28666,28689,28687,29179,29180,29182,29176,29559,29557,29863,29887,29973,30294,30296,30290,30653,30655,30651,30652,30990,31150,31329,31330,31328,31428,31429,31787,31783,31786,31774,31779,31777,31975,32340,32341,32350,32346,32353,32338,32345,32584,32761,32763,32887,32886,33229,33231,33290,34255,34217,34253,34256,34249,34224,34234,34233,34214,34799,34796,34802,34784,35206,35250,35316,35624,35641,35628,35627,35920,36101,36441,36451,36454,36452,36447,36437,36544,36681,36685,36999,36995,37000,37291,37292,37328,37780,37770,37782,37794,37811,37806,37804,37808,37784,37786,37783,38356,38358,38352,38357,38626,38620,38617,38619,38622,38692,38819,38822,38829,38905,38989,38991,38988,38990,38995,39098,39230,39231,39229,39214,39333,39438,39617,39683,39686,39759,39758,39757,39882,39881,39933,39880,39872,40273,40285,40288,40672,40725,40748,20787,22181,22750,22751,22754,23541,40848,24300,25074,25079,25078,25077,25856,25871,26336,26333,27365,27357,27354,27347,28699,28703,28712,28698,28701,28693,28696,29190,29197,29272,29346,29560,29562,29885,29898,29923,30087,30086,30303,30305,30663,31001,31153,31339,31337,31806,31807,31800,31805,31799,31808,32363,32365,32377,32361,32362,32645,32371,32694,32697,32696,33240,34281,34269,34282,34261,34276,34277,34295,34811,34821,34829,34809,34814,35168,35167,35158,35166,35649,35676,35672,35657,35674,35662,35663,35654,35673,36104,36106,36476,36466,36487,36470,36460,36474,36468,36692,36686,36781,37002,37003,37297,37294,37857,37841,37855,37827,37832,37852,37853,37846,37858,37837,37848,37860,37847,37864,38364,38580,38627,38698,38695,38753,38876,38907,39006,39000,39003,39100,39237,39241,39446,39449,39693,39912,39911,39894,39899,40329,40289,40306,40298,40300,40594,40599,40595,40628,21240,22184,22199,22198,22196,22204,22756,23360,23363,23421,23542,24009,25080,25082,25880,25876,25881,26342,26407,27372,28734,28720,28722,29200,29563,29903,30306,30309,31014,31018,31020,31019,31431,31478,31820,31811,31821,31983,31984,36782,32381,32380,32386,32588,32768,33242,33382,34299,34297,34321,34298,34310,34315,34311,34314,34836,34837,35172,35258,35320,35696,35692,35686,35695,35679,35691,36111,36109,36489,36481,36485,36482,37300,37323,37912,37891,37885,38369,38704,39108,39250,39249,39336,39467,39472,39479,39477,39955,39949,40569,40629,40680,40751,40799,40803,40801,20791,20792,22209,22208,22210,22804,23660,24013,25084,25086,25885,25884,26005,26345,27387,27396,27386,27570,28748,29211,29351,29910,29908,30313,30675,31824,32399,32396,32700,34327,34349,34330,34851,34850,34849,34847,35178,35180,35261,35700,35703,35709,36115,36490,36493,36491,36703,36783,37306,37934,37939,37941,37946,37944,37938,37931,38370,38712,38713,38706,38911,39015,39013,39255,39493,39491,39488,39486,39631,39764,39761,39981,39973,40367,40372,40386,40376,40605,40687,40729,40796,40806,40807,20796,20795,22216,22218,22217,23423,24020,24018,24398,25087,25892,27402,27489,28753,28760,29568,29924,30090,30318,30316,31155,31840,31839,32894,32893,33247,35186,35183,35324,35712,36118,36119,36497,36499,36705,37192,37956,37969,37970,38717,38718,38851,38849,39019,39253,39509,39501,39634,39706,40009,39985,39998,39995,40403,40407,40756,40812,40810,40852,22220,24022,25088,25891,25899,25898,26348,27408,29914,31434,31844,31843,31845,32403,32406,32404,33250,34360,34367,34865,35722,37008,37007,37987,37984,37988,38760,39023,39260,39514,39515,39511,39635,39636,39633,40020,40023,40022,40421,40607,40692,22225,22761,25900,28766,30321,30322,30679,32592,32648,34870,34873,34914,35731,35730,35734,33399,36123,37312,37994,38722,38728,38724,38854,39024,39519,39714,39768,40031,40441,40442,40572,40573,40711,40823,40818,24307,27414,28771,31852,31854,34875,35264,36513,37313,38002,38000,39025,39262,39638,39715,40652,28772,30682,35738,38007,38857,39522,39525,32412,35740,36522,37317,38013,38014,38012,40055,40056,40695,35924,38015,40474,29224,39530,39729,40475,40478,31858,9312,9313,9314,9315,9316,9317,9318,9319,9320,9321,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,20022,20031,20101,20128,20866,20886,20907,21241,21304,21353,21430,22794,23424,24027,12083,24191,24308,24400,24417,25908,26080,30098,30326,36789,38582,168,710,12541,12542,12445,12446,12291,20189,12293,12294,12295,12540,65339,65341,10045,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,1040,1041,1042,1043,1044,1045,1025,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1105,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,8679,8632,8633,12751,131276,20058,131210,20994,17553,40880,20872,40881,161287,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,65506,65508,65287,65282,12849,8470,8481,12443,12444,11904,11908,11910,11911,11912,11914,11916,11917,11925,11932,11933,11941,11943,11946,11948,11950,11958,11964,11966,11974,11978,11980,11981,11983,11990,11991,11998,12003,null,null,null,643,592,603,596,629,339,248,331,650,618,20034,20060,20981,21274,21378,19975,19980,20039,20109,22231,64012,23662,24435,19983,20871,19982,20014,20115,20162,20169,20168,20888,21244,21356,21433,22304,22787,22828,23568,24063,26081,27571,27596,27668,29247,20017,20028,20200,20188,20201,20193,20189,20186,21004,21276,21324,22306,22307,22807,22831,23425,23428,23570,23611,23668,23667,24068,24192,24194,24521,25097,25168,27669,27702,27715,27711,27707,29358,29360,29578,31160,32906,38430,20238,20248,20268,20213,20244,20209,20224,20215,20232,20253,20226,20229,20258,20243,20228,20212,20242,20913,21011,21001,21008,21158,21282,21279,21325,21386,21511,22241,22239,22318,22314,22324,22844,22912,22908,22917,22907,22910,22903,22911,23382,23573,23589,23676,23674,23675,23678,24031,24181,24196,24322,24346,24436,24533,24532,24527,25180,25182,25188,25185,25190,25186,25177,25184,25178,25189,26095,26094,26430,26425,26424,26427,26426,26431,26428,26419,27672,27718,27730,27740,27727,27722,27732,27723,27724,28785,29278,29364,29365,29582,29994,30335,31349,32593,33400,33404,33408,33405,33407,34381,35198,37017,37015,37016,37019,37012,38434,38436,38432,38435,20310,20283,20322,20297,20307,20324,20286,20327,20306,20319,20289,20312,20269,20275,20287,20321,20879,20921,21020,21022,21025,21165,21166,21257,21347,21362,21390,21391,21552,21559,21546,21588,21573,21529,21532,21541,21528,21565,21583,21569,21544,21540,21575,22254,22247,22245,22337,22341,22348,22345,22347,22354,22790,22848,22950,22936,22944,22935,22926,22946,22928,22927,22951,22945,23438,23442,23592,23594,23693,23695,23688,23691,23689,23698,23690,23686,23699,23701,24032,24074,24078,24203,24201,24204,24200,24205,24325,24349,24440,24438,24530,24529,24528,24557,24552,24558,24563,24545,24548,24547,24570,24559,24567,24571,24576,24564,25146,25219,25228,25230,25231,25236,25223,25201,25211,25210,25200,25217,25224,25207,25213,25202,25204,25911,26096,26100,26099,26098,26101,26437,26439,26457,26453,26444,26440,26461,26445,26458,26443,27600,27673,27674,27768,27751,27755,27780,27787,27791,27761,27759,27753,27802,27757,27783,27797,27804,27750,27763,27749,27771,27790,28788,28794,29283,29375,29373,29379,29382,29377,29370,29381,29589,29591,29587,29588,29586,30010,30009,30100,30101,30337,31037,32820,32917,32921,32912,32914,32924,33424,33423,33413,33422,33425,33427,33418,33411,33412,35960,36809,36799,37023,37025,37029,37022,37031,37024,38448,38440,38447,38445,20019,20376,20348,20357,20349,20352,20359,20342,20340,20361,20356,20343,20300,20375,20330,20378,20345,20353,20344,20368,20380,20372,20382,20370,20354,20373,20331,20334,20894,20924,20926,21045,21042,21043,21062,21041,21180,21258,21259,21308,21394,21396,21639,21631,21633,21649,21634,21640,21611,21626,21630,21605,21612,21620,21606,21645,21615,21601,21600,21656,21603,21607,21604,22263,22265,22383,22386,22381,22379,22385,22384,22390,22400,22389,22395,22387,22388,22370,22376,22397,22796,22853,22965,22970,22991,22990,22962,22988,22977,22966,22972,22979,22998,22961,22973,22976,22984,22964,22983,23394,23397,23443,23445,23620,23623,23726,23716,23712,23733,23727,23720,23724,23711,23715,23725,23714,23722,23719,23709,23717,23734,23728,23718,24087,24084,24089,24360,24354,24355,24356,24404,24450,24446,24445,24542,24549,24621,24614,24601,24626,24587,24628,24586,24599,24627,24602,24606,24620,24610,24589,24592,24622,24595,24593,24588,24585,24604,25108,25149,25261,25268,25297,25278,25258,25270,25290,25262,25267,25263,25275,25257,25264,25272,25917,26024,26043,26121,26108,26116,26130,26120,26107,26115,26123,26125,26117,26109,26129,26128,26358,26378,26501,26476,26510,26514,26486,26491,26520,26502,26500,26484,26509,26508,26490,26527,26513,26521,26499,26493,26497,26488,26489,26516,27429,27520,27518,27614,27677,27795,27884,27883,27886,27865,27830,27860,27821,27879,27831,27856,27842,27834,27843,27846,27885,27890,27858,27869,27828,27786,27805,27776,27870,27840,27952,27853,27847,27824,27897,27855,27881,27857,28820,28824,28805,28819,28806,28804,28817,28822,28802,28826,28803,29290,29398,29387,29400,29385,29404,29394,29396,29402,29388,29393,29604,29601,29613,29606,29602,29600,29612,29597,29917,29928,30015,30016,30014,30092,30104,30383,30451,30449,30448,30453,30712,30716,30713,30715,30714,30711,31042,31039,31173,31352,31355,31483,31861,31997,32821,32911,32942,32931,32952,32949,32941,33312,33440,33472,33451,33434,33432,33435,33461,33447,33454,33468,33438,33466,33460,33448,33441,33449,33474,33444,33475,33462,33442,34416,34415,34413,34414,35926,36818,36811,36819,36813,36822,36821,36823,37042,37044,37039,37043,37040,38457,38461,38460,38458,38467,20429,20421,20435,20402,20425,20427,20417,20436,20444,20441,20411,20403,20443,20423,20438,20410,20416,20409,20460,21060,21065,21184,21186,21309,21372,21399,21398,21401,21400,21690,21665,21677,21669,21711,21699,33549,21687,21678,21718,21686,21701,21702,21664,21616,21692,21666,21694,21618,21726,21680,22453,22430,22431,22436,22412,22423,22429,22427,22420,22424,22415,22425,22437,22426,22421,22772,22797,22867,23009,23006,23022,23040,23025,23005,23034,23037,23036,23030,23012,23026,23031,23003,23017,23027,23029,23008,23038,23028,23021,23464,23628,23760,23768,23756,23767,23755,23771,23774,23770,23753,23751,23754,23766,23763,23764,23759,23752,23750,23758,23775,23800,24057,24097,24098,24099,24096,24100,24240,24228,24226,24219,24227,24229,24327,24366,24406,24454,24631,24633,24660,24690,24670,24645,24659,24647,24649,24667,24652,24640,24642,24671,24612,24644,24664,24678,24686,25154,25155,25295,25357,25355,25333,25358,25347,25323,25337,25359,25356,25336,25334,25344,25363,25364,25338,25365,25339,25328,25921,25923,26026,26047,26166,26145,26162,26165,26140,26150,26146,26163,26155,26170,26141,26164,26169,26158,26383,26384,26561,26610,26568,26554,26588,26555,26616,26584,26560,26551,26565,26603,26596,26591,26549,26573,26547,26615,26614,26606,26595,26562,26553,26574,26599,26608,26546,26620,26566,26605,26572,26542,26598,26587,26618,26569,26570,26563,26602,26571,27432,27522,27524,27574,27606,27608,27616,27680,27681,27944,27956,27949,27935,27964,27967,27922,27914,27866,27955,27908,27929,27962,27930,27921,27904,27933,27970,27905,27928,27959,27907,27919,27968,27911,27936,27948,27912,27938,27913,27920,28855,28831,28862,28849,28848,28833,28852,28853,28841,29249,29257,29258,29292,29296,29299,29294,29386,29412,29416,29419,29407,29418,29414,29411,29573,29644,29634,29640,29637,29625,29622,29621,29620,29675,29631,29639,29630,29635,29638,29624,29643,29932,29934,29998,30023,30024,30119,30122,30329,30404,30472,30467,30468,30469,30474,30455,30459,30458,30695,30696,30726,30737,30738,30725,30736,30735,30734,30729,30723,30739,31050,31052,31051,31045,31044,31189,31181,31183,31190,31182,31360,31358,31441,31488,31489,31866,31864,31865,31871,31872,31873,32003,32008,32001,32600,32657,32653,32702,32775,32782,32783,32788,32823,32984,32967,32992,32977,32968,32962,32976,32965,32995,32985,32988,32970,32981,32969,32975,32983,32998,32973,33279,33313,33428,33497,33534,33529,33543,33512,33536,33493,33594,33515,33494,33524,33516,33505,33522,33525,33548,33531,33526,33520,33514,33508,33504,33530,33523,33517,34423,34420,34428,34419,34881,34894,34919,34922,34921,35283,35332,35335,36210,36835,36833,36846,36832,37105,37053,37055,37077,37061,37054,37063,37067,37064,37332,37331,38484,38479,38481,38483,38474,38478,20510,20485,20487,20499,20514,20528,20507,20469,20468,20531,20535,20524,20470,20471,20503,20508,20512,20519,20533,20527,20529,20494,20826,20884,20883,20938,20932,20933,20936,20942,21089,21082,21074,21086,21087,21077,21090,21197,21262,21406,21798,21730,21783,21778,21735,21747,21732,21786,21759,21764,21768,21739,21777,21765,21745,21770,21755,21751,21752,21728,21774,21763,21771,22273,22274,22476,22578,22485,22482,22458,22470,22461,22460,22456,22454,22463,22471,22480,22457,22465,22798,22858,23065,23062,23085,23086,23061,23055,23063,23050,23070,23091,23404,23463,23469,23468,23555,23638,23636,23788,23807,23790,23793,23799,23808,23801,24105,24104,24232,24238,24234,24236,24371,24368,24423,24669,24666,24679,24641,24738,24712,24704,24722,24705,24733,24707,24725,24731,24727,24711,24732,24718,25113,25158,25330,25360,25430,25388,25412,25413,25398,25411,25572,25401,25419,25418,25404,25385,25409,25396,25432,25428,25433,25389,25415,25395,25434,25425,25400,25431,25408,25416,25930,25926,26054,26051,26052,26050,26186,26207,26183,26193,26386,26387,26655,26650,26697,26674,26675,26683,26699,26703,26646,26673,26652,26677,26667,26669,26671,26702,26692,26676,26653,26642,26644,26662,26664,26670,26701,26682,26661,26656,27436,27439,27437,27441,27444,27501,32898,27528,27622,27620,27624,27619,27618,27623,27685,28026,28003,28004,28022,27917,28001,28050,27992,28002,28013,28015,28049,28045,28143,28031,28038,27998,28007,28000,28055,28016,28028,27999,28034,28056,27951,28008,28043,28030,28032,28036,27926,28035,28027,28029,28021,28048,28892,28883,28881,28893,28875,32569,28898,28887,28882,28894,28896,28884,28877,28869,28870,28871,28890,28878,28897,29250,29304,29303,29302,29440,29434,29428,29438,29430,29427,29435,29441,29651,29657,29669,29654,29628,29671,29667,29673,29660,29650,29659,29652,29661,29658,29655,29656,29672,29918,29919,29940,29941,29985,30043,30047,30128,30145,30139,30148,30144,30143,30134,30138,30346,30409,30493,30491,30480,30483,30482,30499,30481,30485,30489,30490,30498,30503,30755,30764,30754,30773,30767,30760,30766,30763,30753,30761,30771,30762,30769,31060,31067,31055,31068,31059,31058,31057,31211,31212,31200,31214,31213,31210,31196,31198,31197,31366,31369,31365,31371,31372,31370,31367,31448,31504,31492,31507,31493,31503,31496,31498,31502,31497,31506,31876,31889,31882,31884,31880,31885,31877,32030,32029,32017,32014,32024,32022,32019,32031,32018,32015,32012,32604,32609,32606,32608,32605,32603,32662,32658,32707,32706,32704,32790,32830,32825,33018,33010,33017,33013,33025,33019,33024,33281,33327,33317,33587,33581,33604,33561,33617,33573,33622,33599,33601,33574,33564,33570,33602,33614,33563,33578,33544,33596,33613,33558,33572,33568,33591,33583,33577,33607,33605,33612,33619,33566,33580,33611,33575,33608,34387,34386,34466,34472,34454,34445,34449,34462,34439,34455,34438,34443,34458,34437,34469,34457,34465,34471,34453,34456,34446,34461,34448,34452,34883,34884,34925,34933,34934,34930,34944,34929,34943,34927,34947,34942,34932,34940,35346,35911,35927,35963,36004,36003,36214,36216,36277,36279,36278,36561,36563,36862,36853,36866,36863,36859,36868,36860,36854,37078,37088,37081,37082,37091,37087,37093,37080,37083,37079,37084,37092,37200,37198,37199,37333,37346,37338,38492,38495,38588,39139,39647,39727,20095,20592,20586,20577,20574,20576,20563,20555,20573,20594,20552,20557,20545,20571,20554,20578,20501,20549,20575,20585,20587,20579,20580,20550,20544,20590,20595,20567,20561,20944,21099,21101,21100,21102,21206,21203,21293,21404,21877,21878,21820,21837,21840,21812,21802,21841,21858,21814,21813,21808,21842,21829,21772,21810,21861,21838,21817,21832,21805,21819,21824,21835,22282,22279,22523,22548,22498,22518,22492,22516,22528,22509,22525,22536,22520,22539,22515,22479,22535,22510,22499,22514,22501,22508,22497,22542,22524,22544,22503,22529,22540,22513,22505,22512,22541,22532,22876,23136,23128,23125,23143,23134,23096,23093,23149,23120,23135,23141,23148,23123,23140,23127,23107,23133,23122,23108,23131,23112,23182,23102,23117,23097,23116,23152,23145,23111,23121,23126,23106,23132,23410,23406,23489,23488,23641,23838,23819,23837,23834,23840,23820,23848,23821,23846,23845,23823,23856,23826,23843,23839,23854,24126,24116,24241,24244,24249,24242,24243,24374,24376,24475,24470,24479,24714,24720,24710,24766,24752,24762,24787,24788,24783,24804,24793,24797,24776,24753,24795,24759,24778,24767,24771,24781,24768,25394,25445,25482,25474,25469,25533,25502,25517,25501,25495,25515,25486,25455,25479,25488,25454,25519,25461,25500,25453,25518,25468,25508,25403,25503,25464,25477,25473,25489,25485,25456,25939,26061,26213,26209,26203,26201,26204,26210,26392,26745,26759,26768,26780,26733,26734,26798,26795,26966,26735,26787,26796,26793,26741,26740,26802,26767,26743,26770,26748,26731,26738,26794,26752,26737,26750,26779,26774,26763,26784,26761,26788,26744,26747,26769,26764,26762,26749,27446,27443,27447,27448,27537,27535,27533,27534,27532,27690,28096,28075,28084,28083,28276,28076,28137,28130,28087,28150,28116,28160,28104,28128,28127,28118,28094,28133,28124,28125,28123,28148,28106,28093,28141,28144,28090,28117,28098,28111,28105,28112,28146,28115,28157,28119,28109,28131,28091,28922,28941,28919,28951,28916,28940,28912,28932,28915,28944,28924,28927,28934,28947,28928,28920,28918,28939,28930,28942,29310,29307,29308,29311,29469,29463,29447,29457,29464,29450,29448,29439,29455,29470,29576,29686,29688,29685,29700,29697,29693,29703,29696,29690,29692,29695,29708,29707,29684,29704,30052,30051,30158,30162,30159,30155,30156,30161,30160,30351,30345,30419,30521,30511,30509,30513,30514,30516,30515,30525,30501,30523,30517,30792,30802,30793,30797,30794,30796,30758,30789,30800,31076,31079,31081,31082,31075,31083,31073,31163,31226,31224,31222,31223,31375,31380,31376,31541,31559,31540,31525,31536,31522,31524,31539,31512,31530,31517,31537,31531,31533,31535,31538,31544,31514,31523,31892,31896,31894,31907,32053,32061,32056,32054,32058,32069,32044,32041,32065,32071,32062,32063,32074,32059,32040,32611,32661,32668,32669,32667,32714,32715,32717,32720,32721,32711,32719,32713,32799,32798,32795,32839,32835,32840,33048,33061,33049,33051,33069,33055,33068,33054,33057,33045,33063,33053,33058,33297,33336,33331,33338,33332,33330,33396,33680,33699,33704,33677,33658,33651,33700,33652,33679,33665,33685,33689,33653,33684,33705,33661,33667,33676,33693,33691,33706,33675,33662,33701,33711,33672,33687,33712,33663,33702,33671,33710,33654,33690,34393,34390,34495,34487,34498,34497,34501,34490,34480,34504,34489,34483,34488,34508,34484,34491,34492,34499,34493,34494,34898,34953,34965,34984,34978,34986,34970,34961,34977,34975,34968,34983,34969,34971,34967,34980,34988,34956,34963,34958,35202,35286,35289,35285,35376,35367,35372,35358,35897,35899,35932,35933,35965,36005,36221,36219,36217,36284,36290,36281,36287,36289,36568,36574,36573,36572,36567,36576,36577,36900,36875,36881,36892,36876,36897,37103,37098,37104,37108,37106,37107,37076,37099,37100,37097,37206,37208,37210,37203,37205,37356,37364,37361,37363,37368,37348,37369,37354,37355,37367,37352,37358,38266,38278,38280,38524,38509,38507,38513,38511,38591,38762,38916,39141,39319,20635,20629,20628,20638,20619,20643,20611,20620,20622,20637,20584,20636,20626,20610,20615,20831,20948,21266,21265,21412,21415,21905,21928,21925,21933,21879,22085,21922,21907,21896,21903,21941,21889,21923,21906,21924,21885,21900,21926,21887,21909,21921,21902,22284,22569,22583,22553,22558,22567,22563,22568,22517,22600,22565,22556,22555,22579,22591,22582,22574,22585,22584,22573,22572,22587,22881,23215,23188,23199,23162,23202,23198,23160,23206,23164,23205,23212,23189,23214,23095,23172,23178,23191,23171,23179,23209,23163,23165,23180,23196,23183,23187,23197,23530,23501,23499,23508,23505,23498,23502,23564,23600,23863,23875,23915,23873,23883,23871,23861,23889,23886,23893,23859,23866,23890,23869,23857,23897,23874,23865,23881,23864,23868,23858,23862,23872,23877,24132,24129,24408,24486,24485,24491,24777,24761,24780,24802,24782,24772,24852,24818,24842,24854,24837,24821,24851,24824,24828,24830,24769,24835,24856,24861,24848,24831,24836,24843,25162,25492,25521,25520,25550,25573,25576,25583,25539,25757,25587,25546,25568,25590,25557,25586,25589,25697,25567,25534,25565,25564,25540,25560,25555,25538,25543,25548,25547,25544,25584,25559,25561,25906,25959,25962,25956,25948,25960,25957,25996,26013,26014,26030,26064,26066,26236,26220,26235,26240,26225,26233,26218,26226,26369,26892,26835,26884,26844,26922,26860,26858,26865,26895,26838,26871,26859,26852,26870,26899,26896,26867,26849,26887,26828,26888,26992,26804,26897,26863,26822,26900,26872,26832,26877,26876,26856,26891,26890,26903,26830,26824,26845,26846,26854,26868,26833,26886,26836,26857,26901,26917,26823,27449,27451,27455,27452,27540,27543,27545,27541,27581,27632,27634,27635,27696,28156,28230,28231,28191,28233,28296,28220,28221,28229,28258,28203,28223,28225,28253,28275,28188,28211,28235,28224,28241,28219,28163,28206,28254,28264,28252,28257,28209,28200,28256,28273,28267,28217,28194,28208,28243,28261,28199,28280,28260,28279,28245,28281,28242,28262,28213,28214,28250,28960,28958,28975,28923,28974,28977,28963,28965,28962,28978,28959,28968,28986,28955,29259,29274,29320,29321,29318,29317,29323,29458,29451,29488,29474,29489,29491,29479,29490,29485,29478,29475,29493,29452,29742,29740,29744,29739,29718,29722,29729,29741,29745,29732,29731,29725,29737,29728,29746,29947,29999,30063,30060,30183,30170,30177,30182,30173,30175,30180,30167,30357,30354,30426,30534,30535,30532,30541,30533,30538,30542,30539,30540,30686,30700,30816,30820,30821,30812,30829,30833,30826,30830,30832,30825,30824,30814,30818,31092,31091,31090,31088,31234,31242,31235,31244,31236,31385,31462,31460,31562,31547,31556,31560,31564,31566,31552,31576,31557,31906,31902,31912,31905,32088,32111,32099,32083,32086,32103,32106,32079,32109,32092,32107,32082,32084,32105,32081,32095,32078,32574,32575,32613,32614,32674,32672,32673,32727,32849,32847,32848,33022,32980,33091,33098,33106,33103,33095,33085,33101,33082,33254,33262,33271,33272,33273,33284,33340,33341,33343,33397,33595,33743,33785,33827,33728,33768,33810,33767,33764,33788,33782,33808,33734,33736,33771,33763,33727,33793,33757,33765,33752,33791,33761,33739,33742,33750,33781,33737,33801,33807,33758,33809,33798,33730,33779,33749,33786,33735,33745,33770,33811,33731,33772,33774,33732,33787,33751,33762,33819,33755,33790,34520,34530,34534,34515,34531,34522,34538,34525,34539,34524,34540,34537,34519,34536,34513,34888,34902,34901,35002,35031,35001,35000,35008,35006,34998,35004,34999,35005,34994,35073,35017,35221,35224,35223,35293,35290,35291,35406,35405,35385,35417,35392,35415,35416,35396,35397,35410,35400,35409,35402,35404,35407,35935,35969,35968,36026,36030,36016,36025,36021,36228,36224,36233,36312,36307,36301,36295,36310,36316,36303,36309,36313,36296,36311,36293,36591,36599,36602,36601,36582,36590,36581,36597,36583,36584,36598,36587,36593,36588,36596,36585,36909,36916,36911,37126,37164,37124,37119,37116,37128,37113,37115,37121,37120,37127,37125,37123,37217,37220,37215,37218,37216,37377,37386,37413,37379,37402,37414,37391,37388,37376,37394,37375,37373,37382,37380,37415,37378,37404,37412,37401,37399,37381,37398,38267,38285,38284,38288,38535,38526,38536,38537,38531,38528,38594,38600,38595,38641,38640,38764,38768,38766,38919,39081,39147,40166,40697,20099,20100,20150,20669,20671,20678,20654,20676,20682,20660,20680,20674,20656,20673,20666,20657,20683,20681,20662,20664,20951,21114,21112,21115,21116,21955,21979,21964,21968,21963,21962,21981,21952,21972,21956,21993,21951,21970,21901,21967,21973,21986,21974,21960,22002,21965,21977,21954,22292,22611,22632,22628,22607,22605,22601,22639,22613,22606,22621,22617,22629,22619,22589,22627,22641,22780,23239,23236,23243,23226,23224,23217,23221,23216,23231,23240,23227,23238,23223,23232,23242,23220,23222,23245,23225,23184,23510,23512,23513,23583,23603,23921,23907,23882,23909,23922,23916,23902,23912,23911,23906,24048,24143,24142,24138,24141,24139,24261,24268,24262,24267,24263,24384,24495,24493,24823,24905,24906,24875,24901,24886,24882,24878,24902,24879,24911,24873,24896,25120,37224,25123,25125,25124,25541,25585,25579,25616,25618,25609,25632,25636,25651,25667,25631,25621,25624,25657,25655,25634,25635,25612,25638,25648,25640,25665,25653,25647,25610,25626,25664,25637,25639,25611,25575,25627,25646,25633,25614,25967,26002,26067,26246,26252,26261,26256,26251,26250,26265,26260,26232,26400,26982,26975,26936,26958,26978,26993,26943,26949,26986,26937,26946,26967,26969,27002,26952,26953,26933,26988,26931,26941,26981,26864,27000,26932,26985,26944,26991,26948,26998,26968,26945,26996,26956,26939,26955,26935,26972,26959,26961,26930,26962,26927,27003,26940,27462,27461,27459,27458,27464,27457,27547,64013,27643,27644,27641,27639,27640,28315,28374,28360,28303,28352,28319,28307,28308,28320,28337,28345,28358,28370,28349,28353,28318,28361,28343,28336,28365,28326,28367,28338,28350,28355,28380,28376,28313,28306,28302,28301,28324,28321,28351,28339,28368,28362,28311,28334,28323,28999,29012,29010,29027,29024,28993,29021,29026,29042,29048,29034,29025,28994,29016,28995,29003,29040,29023,29008,29011,28996,29005,29018,29263,29325,29324,29329,29328,29326,29500,29506,29499,29498,29504,29514,29513,29764,29770,29771,29778,29777,29783,29760,29775,29776,29774,29762,29766,29773,29780,29921,29951,29950,29949,29981,30073,30071,27011,30191,30223,30211,30199,30206,30204,30201,30200,30224,30203,30198,30189,30197,30205,30361,30389,30429,30549,30559,30560,30546,30550,30554,30569,30567,30548,30553,30573,30688,30855,30874,30868,30863,30852,30869,30853,30854,30881,30851,30841,30873,30848,30870,30843,31100,31106,31101,31097,31249,31256,31257,31250,31255,31253,31266,31251,31259,31248,31395,31394,31390,31467,31590,31588,31597,31604,31593,31602,31589,31603,31601,31600,31585,31608,31606,31587,31922,31924,31919,32136,32134,32128,32141,32127,32133,32122,32142,32123,32131,32124,32140,32148,32132,32125,32146,32621,32619,32615,32616,32620,32678,32677,32679,32731,32732,32801,33124,33120,33143,33116,33129,33115,33122,33138,26401,33118,33142,33127,33135,33092,33121,33309,33353,33348,33344,33346,33349,34033,33855,33878,33910,33913,33935,33933,33893,33873,33856,33926,33895,33840,33869,33917,33882,33881,33908,33907,33885,34055,33886,33847,33850,33844,33914,33859,33912,33842,33861,33833,33753,33867,33839,33858,33837,33887,33904,33849,33870,33868,33874,33903,33989,33934,33851,33863,33846,33843,33896,33918,33860,33835,33888,33876,33902,33872,34571,34564,34551,34572,34554,34518,34549,34637,34552,34574,34569,34561,34550,34573,34565,35030,35019,35021,35022,35038,35035,35034,35020,35024,35205,35227,35295,35301,35300,35297,35296,35298,35292,35302,35446,35462,35455,35425,35391,35447,35458,35460,35445,35459,35457,35444,35450,35900,35915,35914,35941,35940,35942,35974,35972,35973,36044,36200,36201,36241,36236,36238,36239,36237,36243,36244,36240,36242,36336,36320,36332,36337,36334,36304,36329,36323,36322,36327,36338,36331,36340,36614,36607,36609,36608,36613,36615,36616,36610,36619,36946,36927,36932,36937,36925,37136,37133,37135,37137,37142,37140,37131,37134,37230,37231,37448,37458,37424,37434,37478,37427,37477,37470,37507,37422,37450,37446,37485,37484,37455,37472,37479,37487,37430,37473,37488,37425,37460,37475,37456,37490,37454,37459,37452,37462,37426,38303,38300,38302,38299,38546,38547,38545,38551,38606,38650,38653,38648,38645,38771,38775,38776,38770,38927,38925,38926,39084,39158,39161,39343,39346,39344,39349,39597,39595,39771,40170,40173,40167,40576,40701,20710,20692,20695,20712,20723,20699,20714,20701,20708,20691,20716,20720,20719,20707,20704,20952,21120,21121,21225,21227,21296,21420,22055,22037,22028,22034,22012,22031,22044,22017,22035,22018,22010,22045,22020,22015,22009,22665,22652,22672,22680,22662,22657,22655,22644,22667,22650,22663,22673,22670,22646,22658,22664,22651,22676,22671,22782,22891,23260,23278,23269,23253,23274,23258,23277,23275,23283,23266,23264,23259,23276,23262,23261,23257,23272,23263,23415,23520,23523,23651,23938,23936,23933,23942,23930,23937,23927,23946,23945,23944,23934,23932,23949,23929,23935,24152,24153,24147,24280,24273,24279,24270,24284,24277,24281,24274,24276,24388,24387,24431,24502,24876,24872,24897,24926,24945,24947,24914,24915,24946,24940,24960,24948,24916,24954,24923,24933,24891,24938,24929,24918,25129,25127,25131,25643,25677,25691,25693,25716,25718,25714,25715,25725,25717,25702,25766,25678,25730,25694,25692,25675,25683,25696,25680,25727,25663,25708,25707,25689,25701,25719,25971,26016,26273,26272,26271,26373,26372,26402,27057,27062,27081,27040,27086,27030,27056,27052,27068,27025,27033,27022,27047,27021,27049,27070,27055,27071,27076,27069,27044,27092,27065,27082,27034,27087,27059,27027,27050,27041,27038,27097,27031,27024,27074,27061,27045,27078,27466,27469,27467,27550,27551,27552,27587,27588,27646,28366,28405,28401,28419,28453,28408,28471,28411,28462,28425,28494,28441,28442,28455,28440,28475,28434,28397,28426,28470,28531,28409,28398,28461,28480,28464,28476,28469,28395,28423,28430,28483,28421,28413,28406,28473,28444,28412,28474,28447,28429,28446,28424,28449,29063,29072,29065,29056,29061,29058,29071,29051,29062,29057,29079,29252,29267,29335,29333,29331,29507,29517,29521,29516,29794,29811,29809,29813,29810,29799,29806,29952,29954,29955,30077,30096,30230,30216,30220,30229,30225,30218,30228,30392,30593,30588,30597,30594,30574,30592,30575,30590,30595,30898,30890,30900,30893,30888,30846,30891,30878,30885,30880,30892,30882,30884,31128,31114,31115,31126,31125,31124,31123,31127,31112,31122,31120,31275,31306,31280,31279,31272,31270,31400,31403,31404,31470,31624,31644,31626,31633,31632,31638,31629,31628,31643,31630,31621,31640,21124,31641,31652,31618,31931,31935,31932,31930,32167,32183,32194,32163,32170,32193,32192,32197,32157,32206,32196,32198,32203,32204,32175,32185,32150,32188,32159,32166,32174,32169,32161,32201,32627,32738,32739,32741,32734,32804,32861,32860,33161,33158,33155,33159,33165,33164,33163,33301,33943,33956,33953,33951,33978,33998,33986,33964,33966,33963,33977,33972,33985,33997,33962,33946,33969,34000,33949,33959,33979,33954,33940,33991,33996,33947,33961,33967,33960,34006,33944,33974,33999,33952,34007,34004,34002,34011,33968,33937,34401,34611,34595,34600,34667,34624,34606,34590,34593,34585,34587,34627,34604,34625,34622,34630,34592,34610,34602,34605,34620,34578,34618,34609,34613,34626,34598,34599,34616,34596,34586,34608,34577,35063,35047,35057,35058,35066,35070,35054,35068,35062,35067,35056,35052,35051,35229,35233,35231,35230,35305,35307,35304,35499,35481,35467,35474,35471,35478,35901,35944,35945,36053,36047,36055,36246,36361,36354,36351,36365,36349,36362,36355,36359,36358,36357,36350,36352,36356,36624,36625,36622,36621,37155,37148,37152,37154,37151,37149,37146,37156,37153,37147,37242,37234,37241,37235,37541,37540,37494,37531,37498,37536,37524,37546,37517,37542,37530,37547,37497,37527,37503,37539,37614,37518,37506,37525,37538,37501,37512,37537,37514,37510,37516,37529,37543,37502,37511,37545,37533,37515,37421,38558,38561,38655,38744,38781,38778,38782,38787,38784,38786,38779,38788,38785,38783,38862,38861,38934,39085,39086,39170,39168,39175,39325,39324,39363,39353,39355,39354,39362,39357,39367,39601,39651,39655,39742,39743,39776,39777,39775,40177,40178,40181,40615,20735,20739,20784,20728,20742,20743,20726,20734,20747,20748,20733,20746,21131,21132,21233,21231,22088,22082,22092,22069,22081,22090,22089,22086,22104,22106,22080,22067,22077,22060,22078,22072,22058,22074,22298,22699,22685,22705,22688,22691,22703,22700,22693,22689,22783,23295,23284,23293,23287,23286,23299,23288,23298,23289,23297,23303,23301,23311,23655,23961,23959,23967,23954,23970,23955,23957,23968,23964,23969,23962,23966,24169,24157,24160,24156,32243,24283,24286,24289,24393,24498,24971,24963,24953,25009,25008,24994,24969,24987,24979,25007,25005,24991,24978,25002,24993,24973,24934,25011,25133,25710,25712,25750,25760,25733,25751,25756,25743,25739,25738,25740,25763,25759,25704,25777,25752,25974,25978,25977,25979,26034,26035,26293,26288,26281,26290,26295,26282,26287,27136,27142,27159,27109,27128,27157,27121,27108,27168,27135,27116,27106,27163,27165,27134,27175,27122,27118,27156,27127,27111,27200,27144,27110,27131,27149,27132,27115,27145,27140,27160,27173,27151,27126,27174,27143,27124,27158,27473,27557,27555,27554,27558,27649,27648,27647,27650,28481,28454,28542,28551,28614,28562,28557,28553,28556,28514,28495,28549,28506,28566,28534,28524,28546,28501,28530,28498,28496,28503,28564,28563,28509,28416,28513,28523,28541,28519,28560,28499,28555,28521,28543,28565,28515,28535,28522,28539,29106,29103,29083,29104,29088,29082,29097,29109,29085,29093,29086,29092,29089,29098,29084,29095,29107,29336,29338,29528,29522,29534,29535,29536,29533,29531,29537,29530,29529,29538,29831,29833,29834,29830,29825,29821,29829,29832,29820,29817,29960,29959,30078,30245,30238,30233,30237,30236,30243,30234,30248,30235,30364,30365,30366,30363,30605,30607,30601,30600,30925,30907,30927,30924,30929,30926,30932,30920,30915,30916,30921,31130,31137,31136,31132,31138,31131,27510,31289,31410,31412,31411,31671,31691,31678,31660,31694,31663,31673,31690,31669,31941,31944,31948,31947,32247,32219,32234,32231,32215,32225,32259,32250,32230,32246,32241,32240,32238,32223,32630,32684,32688,32685,32749,32747,32746,32748,32742,32744,32868,32871,33187,33183,33182,33173,33186,33177,33175,33302,33359,33363,33362,33360,33358,33361,34084,34107,34063,34048,34089,34062,34057,34061,34079,34058,34087,34076,34043,34091,34042,34056,34060,34036,34090,34034,34069,34039,34027,34035,34044,34066,34026,34025,34070,34046,34088,34077,34094,34050,34045,34078,34038,34097,34086,34023,34024,34032,34031,34041,34072,34080,34096,34059,34073,34095,34402,34646,34659,34660,34679,34785,34675,34648,34644,34651,34642,34657,34650,34641,34654,34669,34666,34640,34638,34655,34653,34671,34668,34682,34670,34652,34661,34639,34683,34677,34658,34663,34665,34906,35077,35084,35092,35083,35095,35096,35097,35078,35094,35089,35086,35081,35234,35236,35235,35309,35312,35308,35535,35526,35512,35539,35537,35540,35541,35515,35543,35518,35520,35525,35544,35523,35514,35517,35545,35902,35917,35983,36069,36063,36057,36072,36058,36061,36071,36256,36252,36257,36251,36384,36387,36389,36388,36398,36373,36379,36374,36369,36377,36390,36391,36372,36370,36376,36371,36380,36375,36378,36652,36644,36632,36634,36640,36643,36630,36631,36979,36976,36975,36967,36971,37167,37163,37161,37162,37170,37158,37166,37253,37254,37258,37249,37250,37252,37248,37584,37571,37572,37568,37593,37558,37583,37617,37599,37592,37609,37591,37597,37580,37615,37570,37608,37578,37576,37582,37606,37581,37589,37577,37600,37598,37607,37585,37587,37557,37601,37574,37556,38268,38316,38315,38318,38320,38564,38562,38611,38661,38664,38658,38746,38794,38798,38792,38864,38863,38942,38941,38950,38953,38952,38944,38939,38951,39090,39176,39162,39185,39188,39190,39191,39189,39388,39373,39375,39379,39380,39374,39369,39382,39384,39371,39383,39372,39603,39660,39659,39667,39666,39665,39750,39747,39783,39796,39793,39782,39798,39797,39792,39784,39780,39788,40188,40186,40189,40191,40183,40199,40192,40185,40187,40200,40197,40196,40579,40659,40719,40720,20764,20755,20759,20762,20753,20958,21300,21473,22128,22112,22126,22131,22118,22115,22125,22130,22110,22135,22300,22299,22728,22717,22729,22719,22714,22722,22716,22726,23319,23321,23323,23329,23316,23315,23312,23318,23336,23322,23328,23326,23535,23980,23985,23977,23975,23989,23984,23982,23978,23976,23986,23981,23983,23988,24167,24168,24166,24175,24297,24295,24294,24296,24293,24395,24508,24989,25000,24982,25029,25012,25030,25025,25036,25018,25023,25016,24972,25815,25814,25808,25807,25801,25789,25737,25795,25819,25843,25817,25907,25983,25980,26018,26312,26302,26304,26314,26315,26319,26301,26299,26298,26316,26403,27188,27238,27209,27239,27186,27240,27198,27229,27245,27254,27227,27217,27176,27226,27195,27199,27201,27242,27236,27216,27215,27220,27247,27241,27232,27196,27230,27222,27221,27213,27214,27206,27477,27476,27478,27559,27562,27563,27592,27591,27652,27651,27654,28589,28619,28579,28615,28604,28622,28616,28510,28612,28605,28574,28618,28584,28676,28581,28590,28602,28588,28586,28623,28607,28600,28578,28617,28587,28621,28591,28594,28592,29125,29122,29119,29112,29142,29120,29121,29131,29140,29130,29127,29135,29117,29144,29116,29126,29146,29147,29341,29342,29545,29542,29543,29548,29541,29547,29546,29823,29850,29856,29844,29842,29845,29857,29963,30080,30255,30253,30257,30269,30259,30268,30261,30258,30256,30395,30438,30618,30621,30625,30620,30619,30626,30627,30613,30617,30615,30941,30953,30949,30954,30942,30947,30939,30945,30946,30957,30943,30944,31140,31300,31304,31303,31414,31416,31413,31409,31415,31710,31715,31719,31709,31701,31717,31706,31720,31737,31700,31722,31714,31708,31723,31704,31711,31954,31956,31959,31952,31953,32274,32289,32279,32268,32287,32288,32275,32270,32284,32277,32282,32290,32267,32271,32278,32269,32276,32293,32292,32579,32635,32636,32634,32689,32751,32810,32809,32876,33201,33190,33198,33209,33205,33195,33200,33196,33204,33202,33207,33191,33266,33365,33366,33367,34134,34117,34155,34125,34131,34145,34136,34112,34118,34148,34113,34146,34116,34129,34119,34147,34110,34139,34161,34126,34158,34165,34133,34151,34144,34188,34150,34141,34132,34149,34156,34403,34405,34404,34715,34703,34711,34707,34706,34696,34689,34710,34712,34681,34695,34723,34693,34704,34705,34717,34692,34708,34716,34714,34697,35102,35110,35120,35117,35118,35111,35121,35106,35113,35107,35119,35116,35103,35313,35552,35554,35570,35572,35573,35549,35604,35556,35551,35568,35528,35550,35553,35560,35583,35567,35579,35985,35986,35984,36085,36078,36081,36080,36083,36204,36206,36261,36263,36403,36414,36408,36416,36421,36406,36412,36413,36417,36400,36415,36541,36662,36654,36661,36658,36665,36663,36660,36982,36985,36987,36998,37114,37171,37173,37174,37267,37264,37265,37261,37263,37671,37662,37640,37663,37638,37647,37754,37688,37692,37659,37667,37650,37633,37702,37677,37646,37645,37579,37661,37626,37669,37651,37625,37623,37684,37634,37668,37631,37673,37689,37685,37674,37652,37644,37643,37630,37641,37632,37627,37654,38332,38349,38334,38329,38330,38326,38335,38325,38333,38569,38612,38667,38674,38672,38809,38807,38804,38896,38904,38965,38959,38962,39204,39199,39207,39209,39326,39406,39404,39397,39396,39408,39395,39402,39401,39399,39609,39615,39604,39611,39670,39674,39673,39671,39731,39808,39813,39815,39804,39806,39803,39810,39827,39826,39824,39802,39829,39805,39816,40229,40215,40224,40222,40212,40233,40221,40216,40226,40208,40217,40223,40584,40582,40583,40622,40621,40661,40662,40698,40722,40765,20774,20773,20770,20772,20768,20777,21236,22163,22156,22157,22150,22148,22147,22142,22146,22143,22145,22742,22740,22735,22738,23341,23333,23346,23331,23340,23335,23334,23343,23342,23419,23537,23538,23991,24172,24170,24510,24507,25027,25013,25020,25063,25056,25061,25060,25064,25054,25839,25833,25827,25835,25828,25832,25985,25984,26038,26074,26322,27277,27286,27265,27301,27273,27295,27291,27297,27294,27271,27283,27278,27285,27267,27304,27300,27281,27263,27302,27290,27269,27276,27282,27483,27565,27657,28620,28585,28660,28628,28643,28636,28653,28647,28646,28638,28658,28637,28642,28648,29153,29169,29160,29170,29156,29168,29154,29555,29550,29551,29847,29874,29867,29840,29866,29869,29873,29861,29871,29968,29969,29970,29967,30084,30275,30280,30281,30279,30372,30441,30645,30635,30642,30647,30646,30644,30641,30632,30704,30963,30973,30978,30971,30972,30962,30981,30969,30974,30980,31147,31144,31324,31323,31318,31320,31316,31322,31422,31424,31425,31749,31759,31730,31744,31743,31739,31758,31732,31755,31731,31746,31753,31747,31745,31736,31741,31750,31728,31729,31760,31754,31976,32301,32316,32322,32307,38984,32312,32298,32329,32320,32327,32297,32332,32304,32315,32310,32324,32314,32581,32639,32638,32637,32756,32754,32812,33211,33220,33228,33226,33221,33223,33212,33257,33371,33370,33372,34179,34176,34191,34215,34197,34208,34187,34211,34171,34212,34202,34206,34167,34172,34185,34209,34170,34168,34135,34190,34198,34182,34189,34201,34205,34177,34210,34178,34184,34181,34169,34166,34200,34192,34207,34408,34750,34730,34733,34757,34736,34732,34745,34741,34748,34734,34761,34755,34754,34764,34743,34735,34756,34762,34740,34742,34751,34744,34749,34782,34738,35125,35123,35132,35134,35137,35154,35127,35138,35245,35247,35246,35314,35315,35614,35608,35606,35601,35589,35595,35618,35599,35602,35605,35591,35597,35592,35590,35612,35603,35610,35919,35952,35954,35953,35951,35989,35988,36089,36207,36430,36429,36435,36432,36428,36423,36675,36672,36997,36990,37176,37274,37282,37275,37273,37279,37281,37277,37280,37793,37763,37807,37732,37718,37703,37756,37720,37724,37750,37705,37712,37713,37728,37741,37775,37708,37738,37753,37719,37717,37714,37711,37745,37751,37755,37729,37726,37731,37735,37760,37710,37721,38343,38336,38345,38339,38341,38327,38574,38576,38572,38688,38687,38680,38685,38681,38810,38817,38812,38814,38813,38869,38868,38897,38977,38980,38986,38985,38981,38979,39205,39211,39212,39210,39219,39218,39215,39213,39217,39216,39320,39331,39329,39426,39418,39412,39415,39417,39416,39414,39419,39421,39422,39420,39427,39614,39678,39677,39681,39676,39752,39834,39848,39838,39835,39846,39841,39845,39844,39814,39842,39840,39855,40243,40257,40295,40246,40238,40239,40241,40248,40240,40261,40258,40259,40254,40247,40256,40253,32757,40237,40586,40585,40589,40624,40648,40666,40699,40703,40740,40739,40738,40788,40864,20785,20781,20782,22168,22172,22167,22170,22173,22169,22896,23356,23657,23658,24000,24173,24174,25048,25055,25069,25070,25073,25066,25072,25067,25046,25065,25855,25860,25853,25848,25857,25859,25852,26004,26075,26330,26331,26328,27333,27321,27325,27361,27334,27322,27318,27319,27335,27316,27309,27486,27593,27659,28679,28684,28685,28673,28677,28692,28686,28671,28672,28667,28710,28668,28663,28682,29185,29183,29177,29187,29181,29558,29880,29888,29877,29889,29886,29878,29883,29890,29972,29971,30300,30308,30297,30288,30291,30295,30298,30374,30397,30444,30658,30650,30975,30988,30995,30996,30985,30992,30994,30993,31149,31148,31327,31772,31785,31769,31776,31775,31789,31773,31782,31784,31778,31781,31792,32348,32336,32342,32355,32344,32354,32351,32337,32352,32343,32339,32693,32691,32759,32760,32885,33233,33234,33232,33375,33374,34228,34246,34240,34243,34242,34227,34229,34237,34247,34244,34239,34251,34254,34248,34245,34225,34230,34258,34340,34232,34231,34238,34409,34791,34790,34786,34779,34795,34794,34789,34783,34803,34788,34772,34780,34771,34797,34776,34787,34724,34775,34777,34817,34804,34792,34781,35155,35147,35151,35148,35142,35152,35153,35145,35626,35623,35619,35635,35632,35637,35655,35631,35644,35646,35633,35621,35639,35622,35638,35630,35620,35643,35645,35642,35906,35957,35993,35992,35991,36094,36100,36098,36096,36444,36450,36448,36439,36438,36446,36453,36455,36443,36442,36449,36445,36457,36436,36678,36679,36680,36683,37160,37178,37179,37182,37288,37285,37287,37295,37290,37813,37772,37778,37815,37787,37789,37769,37799,37774,37802,37790,37798,37781,37768,37785,37791,37773,37809,37777,37810,37796,37800,37812,37795,37797,38354,38355,38353,38579,38615,38618,24002,38623,38616,38621,38691,38690,38693,38828,38830,38824,38827,38820,38826,38818,38821,38871,38873,38870,38872,38906,38992,38993,38994,39096,39233,39228,39226,39439,39435,39433,39437,39428,39441,39434,39429,39431,39430,39616,39644,39688,39684,39685,39721,39733,39754,39756,39755,39879,39878,39875,39871,39873,39861,39864,39891,39862,39876,39865,39869,40284,40275,40271,40266,40283,40267,40281,40278,40268,40279,40274,40276,40287,40280,40282,40590,40588,40671,40705,40704,40726,40741,40747,40746,40745,40744,40780,40789,20788,20789,21142,21239,21428,22187,22189,22182,22183,22186,22188,22746,22749,22747,22802,23357,23358,23359,24003,24176,24511,25083,25863,25872,25869,25865,25868,25870,25988,26078,26077,26334,27367,27360,27340,27345,27353,27339,27359,27356,27344,27371,27343,27341,27358,27488,27568,27660,28697,28711,28704,28694,28715,28705,28706,28707,28713,28695,28708,28700,28714,29196,29194,29191,29186,29189,29349,29350,29348,29347,29345,29899,29893,29879,29891,29974,30304,30665,30666,30660,30705,31005,31003,31009,31004,30999,31006,31152,31335,31336,31795,31804,31801,31788,31803,31980,31978,32374,32373,32376,32368,32375,32367,32378,32370,32372,32360,32587,32586,32643,32646,32695,32765,32766,32888,33239,33237,33380,33377,33379,34283,34289,34285,34265,34273,34280,34266,34263,34284,34290,34296,34264,34271,34275,34268,34257,34288,34278,34287,34270,34274,34816,34810,34819,34806,34807,34825,34828,34827,34822,34812,34824,34815,34826,34818,35170,35162,35163,35159,35169,35164,35160,35165,35161,35208,35255,35254,35318,35664,35656,35658,35648,35667,35670,35668,35659,35669,35665,35650,35666,35671,35907,35959,35958,35994,36102,36103,36105,36268,36266,36269,36267,36461,36472,36467,36458,36463,36475,36546,36690,36689,36687,36688,36691,36788,37184,37183,37296,37293,37854,37831,37839,37826,37850,37840,37881,37868,37836,37849,37801,37862,37834,37844,37870,37859,37845,37828,37838,37824,37842,37863,38269,38362,38363,38625,38697,38699,38700,38696,38694,38835,38839,38838,38877,38878,38879,39004,39001,39005,38999,39103,39101,39099,39102,39240,39239,39235,39334,39335,39450,39445,39461,39453,39460,39451,39458,39456,39463,39459,39454,39452,39444,39618,39691,39690,39694,39692,39735,39914,39915,39904,39902,39908,39910,39906,39920,39892,39895,39916,39900,39897,39909,39893,39905,39898,40311,40321,40330,40324,40328,40305,40320,40312,40326,40331,40332,40317,40299,40308,40309,40304,40297,40325,40307,40315,40322,40303,40313,40319,40327,40296,40596,40593,40640,40700,40749,40768,40769,40781,40790,40791,40792,21303,22194,22197,22195,22755,23365,24006,24007,24302,24303,24512,24513,25081,25879,25878,25877,25875,26079,26344,26339,26340,27379,27376,27370,27368,27385,27377,27374,27375,28732,28725,28719,28727,28724,28721,28738,28728,28735,28730,28729,28736,28731,28723,28737,29203,29204,29352,29565,29564,29882,30379,30378,30398,30445,30668,30670,30671,30669,30706,31013,31011,31015,31016,31012,31017,31154,31342,31340,31341,31479,31817,31816,31818,31815,31813,31982,32379,32382,32385,32384,32698,32767,32889,33243,33241,33291,33384,33385,34338,34303,34305,34302,34331,34304,34294,34308,34313,34309,34316,34301,34841,34832,34833,34839,34835,34838,35171,35174,35257,35319,35680,35690,35677,35688,35683,35685,35687,35693,36270,36486,36488,36484,36697,36694,36695,36693,36696,36698,37005,37187,37185,37303,37301,37298,37299,37899,37907,37883,37920,37903,37908,37886,37909,37904,37928,37913,37901,37877,37888,37879,37895,37902,37910,37906,37882,37897,37880,37898,37887,37884,37900,37878,37905,37894,38366,38368,38367,38702,38703,38841,38843,38909,38910,39008,39010,39011,39007,39105,39106,39248,39246,39257,39244,39243,39251,39474,39476,39473,39468,39466,39478,39465,39470,39480,39469,39623,39626,39622,39696,39698,39697,39947,39944,39927,39941,39954,39928,40000,39943,39950,39942,39959,39956,39945,40351,40345,40356,40349,40338,40344,40336,40347,40352,40340,40348,40362,40343,40353,40346,40354,40360,40350,40355,40383,40361,40342,40358,40359,40601,40603,40602,40677,40676,40679,40678,40752,40750,40795,40800,40798,40797,40793,40849,20794,20793,21144,21143,22211,22205,22206,23368,23367,24011,24015,24305,25085,25883,27394,27388,27395,27384,27392,28739,28740,28746,28744,28745,28741,28742,29213,29210,29209,29566,29975,30314,30672,31021,31025,31023,31828,31827,31986,32394,32391,32392,32395,32390,32397,32589,32699,32816,33245,34328,34346,34342,34335,34339,34332,34329,34343,34350,34337,34336,34345,34334,34341,34857,34845,34843,34848,34852,34844,34859,34890,35181,35177,35182,35179,35322,35705,35704,35653,35706,35707,36112,36116,36271,36494,36492,36702,36699,36701,37190,37188,37189,37305,37951,37947,37942,37929,37949,37948,37936,37945,37930,37943,37932,37952,37937,38373,38372,38371,38709,38714,38847,38881,39012,39113,39110,39104,39256,39254,39481,39485,39494,39492,39490,39489,39482,39487,39629,39701,39703,39704,39702,39738,39762,39979,39965,39964,39980,39971,39976,39977,39972,39969,40375,40374,40380,40385,40391,40394,40399,40382,40389,40387,40379,40373,40398,40377,40378,40364,40392,40369,40365,40396,40371,40397,40370,40570,40604,40683,40686,40685,40731,40728,40730,40753,40782,40805,40804,40850,20153,22214,22213,22219,22897,23371,23372,24021,24017,24306,25889,25888,25894,25890,27403,27400,27401,27661,28757,28758,28759,28754,29214,29215,29353,29567,29912,29909,29913,29911,30317,30381,31029,31156,31344,31345,31831,31836,31833,31835,31834,31988,31985,32401,32591,32647,33246,33387,34356,34357,34355,34348,34354,34358,34860,34856,34854,34858,34853,35185,35263,35262,35323,35710,35716,35714,35718,35717,35711,36117,36501,36500,36506,36498,36496,36502,36503,36704,36706,37191,37964,37968,37962,37963,37967,37959,37957,37960,37961,37958,38719,38883,39018,39017,39115,39252,39259,39502,39507,39508,39500,39503,39496,39498,39497,39506,39504,39632,39705,39723,39739,39766,39765,40006,40008,39999,40004,39993,39987,40001,39996,39991,39988,39986,39997,39990,40411,40402,40414,40410,40395,40400,40412,40401,40415,40425,40409,40408,40406,40437,40405,40413,40630,40688,40757,40755,40754,40770,40811,40853,40866,20797,21145,22760,22759,22898,23373,24024,34863,24399,25089,25091,25092,25897,25893,26006,26347,27409,27410,27407,27594,28763,28762,29218,29570,29569,29571,30320,30676,31847,31846,32405,33388,34362,34368,34361,34364,34353,34363,34366,34864,34866,34862,34867,35190,35188,35187,35326,35724,35726,35723,35720,35909,36121,36504,36708,36707,37308,37986,37973,37981,37975,37982,38852,38853,38912,39510,39513,39710,39711,39712,40018,40024,40016,40010,40013,40011,40021,40025,40012,40014,40443,40439,40431,40419,40427,40440,40420,40438,40417,40430,40422,40434,40432,40418,40428,40436,40435,40424,40429,40642,40656,40690,40691,40710,40732,40760,40759,40758,40771,40783,40817,40816,40814,40815,22227,22221,23374,23661,25901,26349,26350,27411,28767,28769,28765,28768,29219,29915,29925,30677,31032,31159,31158,31850,32407,32649,33389,34371,34872,34871,34869,34891,35732,35733,36510,36511,36512,36509,37310,37309,37314,37995,37992,37993,38629,38726,38723,38727,38855,38885,39518,39637,39769,40035,40039,40038,40034,40030,40032,40450,40446,40455,40451,40454,40453,40448,40449,40457,40447,40445,40452,40608,40734,40774,40820,40821,40822,22228,25902,26040,27416,27417,27415,27418,28770,29222,29354,30680,30681,31033,31849,31851,31990,32410,32408,32411,32409,33248,33249,34374,34375,34376,35193,35194,35196,35195,35327,35736,35737,36517,36516,36515,37998,37997,37999,38001,38003,38729,39026,39263,40040,40046,40045,40459,40461,40464,40463,40466,40465,40609,40693,40713,40775,40824,40827,40826,40825,22302,28774,31855,34876,36274,36518,37315,38004,38008,38006,38005,39520,40052,40051,40049,40053,40468,40467,40694,40714,40868,28776,28773,31991,34410,34878,34877,34879,35742,35996,36521,36553,38731,39027,39028,39116,39265,39339,39524,39526,39527,39716,40469,40471,40776,25095,27422,29223,34380,36520,38018,38016,38017,39529,39528,39726,40473,29225,34379,35743,38019,40057,40631,30325,39531,40058,40477,28777,28778,40612,40830,40777,40856,30849,37561,35023,22715,24658,31911,23290,9556,9574,9559,9568,9580,9571,9562,9577,9565,9554,9572,9557,9566,9578,9569,9560,9575,9563,9555,9573,9558,9567,9579,9570,9561,9576,9564,9553,9552,9581,9582,9584,9583,65517,132423,37595,132575,147397,34124,17077,29679,20917,13897,149826,166372,37700,137691,33518,146632,30780,26436,25311,149811,166314,131744,158643,135941,20395,140525,20488,159017,162436,144896,150193,140563,20521,131966,24484,131968,131911,28379,132127,20605,20737,13434,20750,39020,14147,33814,149924,132231,20832,144308,20842,134143,139516,131813,140592,132494,143923,137603,23426,34685,132531,146585,20914,20920,40244,20937,20943,20945,15580,20947,150182,20915,20962,21314,20973,33741,26942,145197,24443,21003,21030,21052,21173,21079,21140,21177,21189,31765,34114,21216,34317,158483,21253,166622,21833,28377,147328,133460,147436,21299,21316,134114,27851,136998,26651,29653,24650,16042,14540,136936,29149,17570,21357,21364,165547,21374,21375,136598,136723,30694,21395,166555,21408,21419,21422,29607,153458,16217,29596,21441,21445,27721,20041,22526,21465,15019,134031,21472,147435,142755,21494,134263,21523,28793,21803,26199,27995,21613,158547,134516,21853,21647,21668,18342,136973,134877,15796,134477,166332,140952,21831,19693,21551,29719,21894,21929,22021,137431,147514,17746,148533,26291,135348,22071,26317,144010,26276,26285,22093,22095,30961,22257,38791,21502,22272,22255,22253,166758,13859,135759,22342,147877,27758,28811,22338,14001,158846,22502,136214,22531,136276,148323,22566,150517,22620,22698,13665,22752,22748,135740,22779,23551,22339,172368,148088,37843,13729,22815,26790,14019,28249,136766,23076,21843,136850,34053,22985,134478,158849,159018,137180,23001,137211,137138,159142,28017,137256,136917,23033,159301,23211,23139,14054,149929,23159,14088,23190,29797,23251,159649,140628,15749,137489,14130,136888,24195,21200,23414,25992,23420,162318,16388,18525,131588,23509,24928,137780,154060,132517,23539,23453,19728,23557,138052,23571,29646,23572,138405,158504,23625,18653,23685,23785,23791,23947,138745,138807,23824,23832,23878,138916,23738,24023,33532,14381,149761,139337,139635,33415,14390,15298,24110,27274,24181,24186,148668,134355,21414,20151,24272,21416,137073,24073,24308,164994,24313,24315,14496,24316,26686,37915,24333,131521,194708,15070,18606,135994,24378,157832,140240,24408,140401,24419,38845,159342,24434,37696,166454,24487,23990,15711,152144,139114,159992,140904,37334,131742,166441,24625,26245,137335,14691,15815,13881,22416,141236,31089,15936,24734,24740,24755,149890,149903,162387,29860,20705,23200,24932,33828,24898,194726,159442,24961,20980,132694,24967,23466,147383,141407,25043,166813,170333,25040,14642,141696,141505,24611,24924,25886,25483,131352,25285,137072,25301,142861,25452,149983,14871,25656,25592,136078,137212,25744,28554,142902,38932,147596,153373,25825,25829,38011,14950,25658,14935,25933,28438,150056,150051,25989,25965,25951,143486,26037,149824,19255,26065,16600,137257,26080,26083,24543,144384,26136,143863,143864,26180,143780,143781,26187,134773,26215,152038,26227,26228,138813,143921,165364,143816,152339,30661,141559,39332,26370,148380,150049,15147,27130,145346,26462,26471,26466,147917,168173,26583,17641,26658,28240,37436,26625,144358,159136,26717,144495,27105,27147,166623,26995,26819,144845,26881,26880,15666,14849,144956,15232,26540,26977,166474,17148,26934,27032,15265,132041,33635,20624,27129,144985,139562,27205,145155,27293,15347,26545,27336,168348,15373,27421,133411,24798,27445,27508,141261,28341,146139,132021,137560,14144,21537,146266,27617,147196,27612,27703,140427,149745,158545,27738,33318,27769,146876,17605,146877,147876,149772,149760,146633,14053,15595,134450,39811,143865,140433,32655,26679,159013,159137,159211,28054,27996,28284,28420,149887,147589,159346,34099,159604,20935,27804,28189,33838,166689,28207,146991,29779,147330,31180,28239,23185,143435,28664,14093,28573,146992,28410,136343,147517,17749,37872,28484,28508,15694,28532,168304,15675,28575,147780,28627,147601,147797,147513,147440,147380,147775,20959,147798,147799,147776,156125,28747,28798,28839,28801,28876,28885,28886,28895,16644,15848,29108,29078,148087,28971,28997,23176,29002,29038,23708,148325,29007,37730,148161,28972,148570,150055,150050,29114,166888,28861,29198,37954,29205,22801,37955,29220,37697,153093,29230,29248,149876,26813,29269,29271,15957,143428,26637,28477,29314,29482,29483,149539,165931,18669,165892,29480,29486,29647,29610,134202,158254,29641,29769,147938,136935,150052,26147,14021,149943,149901,150011,29687,29717,26883,150054,29753,132547,16087,29788,141485,29792,167602,29767,29668,29814,33721,29804,14128,29812,37873,27180,29826,18771,150156,147807,150137,166799,23366,166915,137374,29896,137608,29966,29929,29982,167641,137803,23511,167596,37765,30029,30026,30055,30062,151426,16132,150803,30094,29789,30110,30132,30210,30252,30289,30287,30319,30326,156661,30352,33263,14328,157969,157966,30369,30373,30391,30412,159647,33890,151709,151933,138780,30494,30502,30528,25775,152096,30552,144044,30639,166244,166248,136897,30708,30729,136054,150034,26826,30895,30919,30931,38565,31022,153056,30935,31028,30897,161292,36792,34948,166699,155779,140828,31110,35072,26882,31104,153687,31133,162617,31036,31145,28202,160038,16040,31174,168205,31188], + "euc-kr":[44034,44035,44037,44038,44043,44044,44045,44046,44047,44056,44062,44063,44065,44066,44067,44069,44070,44071,44072,44073,44074,44075,44078,44082,44083,44084,null,null,null,null,null,null,44085,44086,44087,44090,44091,44093,44094,44095,44097,44098,44099,44100,44101,44102,44103,44104,44105,44106,44108,44110,44111,44112,44113,44114,44115,44117,null,null,null,null,null,null,44118,44119,44121,44122,44123,44125,44126,44127,44128,44129,44130,44131,44132,44133,44134,44135,44136,44137,44138,44139,44140,44141,44142,44143,44146,44147,44149,44150,44153,44155,44156,44157,44158,44159,44162,44167,44168,44173,44174,44175,44177,44178,44179,44181,44182,44183,44184,44185,44186,44187,44190,44194,44195,44196,44197,44198,44199,44203,44205,44206,44209,44210,44211,44212,44213,44214,44215,44218,44222,44223,44224,44226,44227,44229,44230,44231,44233,44234,44235,44237,44238,44239,44240,44241,44242,44243,44244,44246,44248,44249,44250,44251,44252,44253,44254,44255,44258,44259,44261,44262,44265,44267,44269,44270,44274,44276,44279,44280,44281,44282,44283,44286,44287,44289,44290,44291,44293,44295,44296,44297,44298,44299,44302,44304,44306,44307,44308,44309,44310,44311,44313,44314,44315,44317,44318,44319,44321,44322,44323,44324,44325,44326,44327,44328,44330,44331,44334,44335,44336,44337,44338,44339,null,null,null,null,null,null,44342,44343,44345,44346,44347,44349,44350,44351,44352,44353,44354,44355,44358,44360,44362,44363,44364,44365,44366,44367,44369,44370,44371,44373,44374,44375,null,null,null,null,null,null,44377,44378,44379,44380,44381,44382,44383,44384,44386,44388,44389,44390,44391,44392,44393,44394,44395,44398,44399,44401,44402,44407,44408,44409,44410,44414,44416,44419,44420,44421,44422,44423,44426,44427,44429,44430,44431,44433,44434,44435,44436,44437,44438,44439,44440,44441,44442,44443,44446,44447,44448,44449,44450,44451,44453,44454,44455,44456,44457,44458,44459,44460,44461,44462,44463,44464,44465,44466,44467,44468,44469,44470,44472,44473,44474,44475,44476,44477,44478,44479,44482,44483,44485,44486,44487,44489,44490,44491,44492,44493,44494,44495,44498,44500,44501,44502,44503,44504,44505,44506,44507,44509,44510,44511,44513,44514,44515,44517,44518,44519,44520,44521,44522,44523,44524,44525,44526,44527,44528,44529,44530,44531,44532,44533,44534,44535,44538,44539,44541,44542,44546,44547,44548,44549,44550,44551,44554,44556,44558,44559,44560,44561,44562,44563,44565,44566,44567,44568,44569,44570,44571,44572,null,null,null,null,null,null,44573,44574,44575,44576,44577,44578,44579,44580,44581,44582,44583,44584,44585,44586,44587,44588,44589,44590,44591,44594,44595,44597,44598,44601,44603,44604,null,null,null,null,null,null,44605,44606,44607,44610,44612,44615,44616,44617,44619,44623,44625,44626,44627,44629,44631,44632,44633,44634,44635,44638,44642,44643,44644,44646,44647,44650,44651,44653,44654,44655,44657,44658,44659,44660,44661,44662,44663,44666,44670,44671,44672,44673,44674,44675,44678,44679,44680,44681,44682,44683,44685,44686,44687,44688,44689,44690,44691,44692,44693,44694,44695,44696,44697,44698,44699,44700,44701,44702,44703,44704,44705,44706,44707,44708,44709,44710,44711,44712,44713,44714,44715,44716,44717,44718,44719,44720,44721,44722,44723,44724,44725,44726,44727,44728,44729,44730,44731,44735,44737,44738,44739,44741,44742,44743,44744,44745,44746,44747,44750,44754,44755,44756,44757,44758,44759,44762,44763,44765,44766,44767,44768,44769,44770,44771,44772,44773,44774,44775,44777,44778,44780,44782,44783,44784,44785,44786,44787,44789,44790,44791,44793,44794,44795,44797,44798,44799,44800,44801,44802,44803,44804,44805,null,null,null,null,null,null,44806,44809,44810,44811,44812,44814,44815,44817,44818,44819,44820,44821,44822,44823,44824,44825,44826,44827,44828,44829,44830,44831,44832,44833,44834,44835,null,null,null,null,null,null,44836,44837,44838,44839,44840,44841,44842,44843,44846,44847,44849,44851,44853,44854,44855,44856,44857,44858,44859,44862,44864,44868,44869,44870,44871,44874,44875,44876,44877,44878,44879,44881,44882,44883,44884,44885,44886,44887,44888,44889,44890,44891,44894,44895,44896,44897,44898,44899,44902,44903,44904,44905,44906,44907,44908,44909,44910,44911,44912,44913,44914,44915,44916,44917,44918,44919,44920,44922,44923,44924,44925,44926,44927,44929,44930,44931,44933,44934,44935,44937,44938,44939,44940,44941,44942,44943,44946,44947,44948,44950,44951,44952,44953,44954,44955,44957,44958,44959,44960,44961,44962,44963,44964,44965,44966,44967,44968,44969,44970,44971,44972,44973,44974,44975,44976,44977,44978,44979,44980,44981,44982,44983,44986,44987,44989,44990,44991,44993,44994,44995,44996,44997,44998,45002,45004,45007,45008,45009,45010,45011,45013,45014,45015,45016,45017,45018,45019,45021,45022,45023,45024,45025,null,null,null,null,null,null,45026,45027,45028,45029,45030,45031,45034,45035,45036,45037,45038,45039,45042,45043,45045,45046,45047,45049,45050,45051,45052,45053,45054,45055,45058,45059,null,null,null,null,null,null,45061,45062,45063,45064,45065,45066,45067,45069,45070,45071,45073,45074,45075,45077,45078,45079,45080,45081,45082,45083,45086,45087,45088,45089,45090,45091,45092,45093,45094,45095,45097,45098,45099,45100,45101,45102,45103,45104,45105,45106,45107,45108,45109,45110,45111,45112,45113,45114,45115,45116,45117,45118,45119,45120,45121,45122,45123,45126,45127,45129,45131,45133,45135,45136,45137,45138,45142,45144,45146,45147,45148,45150,45151,45152,45153,45154,45155,45156,45157,45158,45159,45160,45161,45162,45163,45164,45165,45166,45167,45168,45169,45170,45171,45172,45173,45174,45175,45176,45177,45178,45179,45182,45183,45185,45186,45187,45189,45190,45191,45192,45193,45194,45195,45198,45200,45202,45203,45204,45205,45206,45207,45211,45213,45214,45219,45220,45221,45222,45223,45226,45232,45234,45238,45239,45241,45242,45243,45245,45246,45247,45248,45249,45250,45251,45254,45258,45259,45260,45261,45262,45263,45266,null,null,null,null,null,null,45267,45269,45270,45271,45273,45274,45275,45276,45277,45278,45279,45281,45282,45283,45284,45286,45287,45288,45289,45290,45291,45292,45293,45294,45295,45296,null,null,null,null,null,null,45297,45298,45299,45300,45301,45302,45303,45304,45305,45306,45307,45308,45309,45310,45311,45312,45313,45314,45315,45316,45317,45318,45319,45322,45325,45326,45327,45329,45332,45333,45334,45335,45338,45342,45343,45344,45345,45346,45350,45351,45353,45354,45355,45357,45358,45359,45360,45361,45362,45363,45366,45370,45371,45372,45373,45374,45375,45378,45379,45381,45382,45383,45385,45386,45387,45388,45389,45390,45391,45394,45395,45398,45399,45401,45402,45403,45405,45406,45407,45409,45410,45411,45412,45413,45414,45415,45416,45417,45418,45419,45420,45421,45422,45423,45424,45425,45426,45427,45428,45429,45430,45431,45434,45435,45437,45438,45439,45441,45443,45444,45445,45446,45447,45450,45452,45454,45455,45456,45457,45461,45462,45463,45465,45466,45467,45469,45470,45471,45472,45473,45474,45475,45476,45477,45478,45479,45481,45482,45483,45484,45485,45486,45487,45488,45489,45490,45491,45492,45493,45494,45495,45496,null,null,null,null,null,null,45497,45498,45499,45500,45501,45502,45503,45504,45505,45506,45507,45508,45509,45510,45511,45512,45513,45514,45515,45517,45518,45519,45521,45522,45523,45525,null,null,null,null,null,null,45526,45527,45528,45529,45530,45531,45534,45536,45537,45538,45539,45540,45541,45542,45543,45546,45547,45549,45550,45551,45553,45554,45555,45556,45557,45558,45559,45560,45562,45564,45566,45567,45568,45569,45570,45571,45574,45575,45577,45578,45581,45582,45583,45584,45585,45586,45587,45590,45592,45594,45595,45596,45597,45598,45599,45601,45602,45603,45604,45605,45606,45607,45608,45609,45610,45611,45612,45613,45614,45615,45616,45617,45618,45619,45621,45622,45623,45624,45625,45626,45627,45629,45630,45631,45632,45633,45634,45635,45636,45637,45638,45639,45640,45641,45642,45643,45644,45645,45646,45647,45648,45649,45650,45651,45652,45653,45654,45655,45657,45658,45659,45661,45662,45663,45665,45666,45667,45668,45669,45670,45671,45674,45675,45676,45677,45678,45679,45680,45681,45682,45683,45686,45687,45688,45689,45690,45691,45693,45694,45695,45696,45697,45698,45699,45702,45703,45704,45706,45707,45708,45709,45710,null,null,null,null,null,null,45711,45714,45715,45717,45718,45719,45723,45724,45725,45726,45727,45730,45732,45735,45736,45737,45739,45741,45742,45743,45745,45746,45747,45749,45750,45751,null,null,null,null,null,null,45752,45753,45754,45755,45756,45757,45758,45759,45760,45761,45762,45763,45764,45765,45766,45767,45770,45771,45773,45774,45775,45777,45779,45780,45781,45782,45783,45786,45788,45790,45791,45792,45793,45795,45799,45801,45802,45808,45809,45810,45814,45820,45821,45822,45826,45827,45829,45830,45831,45833,45834,45835,45836,45837,45838,45839,45842,45846,45847,45848,45849,45850,45851,45853,45854,45855,45856,45857,45858,45859,45860,45861,45862,45863,45864,45865,45866,45867,45868,45869,45870,45871,45872,45873,45874,45875,45876,45877,45878,45879,45880,45881,45882,45883,45884,45885,45886,45887,45888,45889,45890,45891,45892,45893,45894,45895,45896,45897,45898,45899,45900,45901,45902,45903,45904,45905,45906,45907,45911,45913,45914,45917,45920,45921,45922,45923,45926,45928,45930,45932,45933,45935,45938,45939,45941,45942,45943,45945,45946,45947,45948,45949,45950,45951,45954,45958,45959,45960,45961,45962,45963,45965,null,null,null,null,null,null,45966,45967,45969,45970,45971,45973,45974,45975,45976,45977,45978,45979,45980,45981,45982,45983,45986,45987,45988,45989,45990,45991,45993,45994,45995,45997,null,null,null,null,null,null,45998,45999,46000,46001,46002,46003,46004,46005,46006,46007,46008,46009,46010,46011,46012,46013,46014,46015,46016,46017,46018,46019,46022,46023,46025,46026,46029,46031,46033,46034,46035,46038,46040,46042,46044,46046,46047,46049,46050,46051,46053,46054,46055,46057,46058,46059,46060,46061,46062,46063,46064,46065,46066,46067,46068,46069,46070,46071,46072,46073,46074,46075,46077,46078,46079,46080,46081,46082,46083,46084,46085,46086,46087,46088,46089,46090,46091,46092,46093,46094,46095,46097,46098,46099,46100,46101,46102,46103,46105,46106,46107,46109,46110,46111,46113,46114,46115,46116,46117,46118,46119,46122,46124,46125,46126,46127,46128,46129,46130,46131,46133,46134,46135,46136,46137,46138,46139,46140,46141,46142,46143,46144,46145,46146,46147,46148,46149,46150,46151,46152,46153,46154,46155,46156,46157,46158,46159,46162,46163,46165,46166,46167,46169,46170,46171,46172,46173,46174,46175,46178,46180,46182,null,null,null,null,null,null,46183,46184,46185,46186,46187,46189,46190,46191,46192,46193,46194,46195,46196,46197,46198,46199,46200,46201,46202,46203,46204,46205,46206,46207,46209,46210,null,null,null,null,null,null,46211,46212,46213,46214,46215,46217,46218,46219,46220,46221,46222,46223,46224,46225,46226,46227,46228,46229,46230,46231,46232,46233,46234,46235,46236,46238,46239,46240,46241,46242,46243,46245,46246,46247,46249,46250,46251,46253,46254,46255,46256,46257,46258,46259,46260,46262,46264,46266,46267,46268,46269,46270,46271,46273,46274,46275,46277,46278,46279,46281,46282,46283,46284,46285,46286,46287,46289,46290,46291,46292,46294,46295,46296,46297,46298,46299,46302,46303,46305,46306,46309,46311,46312,46313,46314,46315,46318,46320,46322,46323,46324,46325,46326,46327,46329,46330,46331,46332,46333,46334,46335,46336,46337,46338,46339,46340,46341,46342,46343,46344,46345,46346,46347,46348,46349,46350,46351,46352,46353,46354,46355,46358,46359,46361,46362,46365,46366,46367,46368,46369,46370,46371,46374,46379,46380,46381,46382,46383,46386,46387,46389,46390,46391,46393,46394,46395,46396,46397,46398,46399,46402,46406,null,null,null,null,null,null,46407,46408,46409,46410,46414,46415,46417,46418,46419,46421,46422,46423,46424,46425,46426,46427,46430,46434,46435,46436,46437,46438,46439,46440,46441,46442,null,null,null,null,null,null,46443,46444,46445,46446,46447,46448,46449,46450,46451,46452,46453,46454,46455,46456,46457,46458,46459,46460,46461,46462,46463,46464,46465,46466,46467,46468,46469,46470,46471,46472,46473,46474,46475,46476,46477,46478,46479,46480,46481,46482,46483,46484,46485,46486,46487,46488,46489,46490,46491,46492,46493,46494,46495,46498,46499,46501,46502,46503,46505,46508,46509,46510,46511,46514,46518,46519,46520,46521,46522,46526,46527,46529,46530,46531,46533,46534,46535,46536,46537,46538,46539,46542,46546,46547,46548,46549,46550,46551,46553,46554,46555,46556,46557,46558,46559,46560,46561,46562,46563,46564,46565,46566,46567,46568,46569,46570,46571,46573,46574,46575,46576,46577,46578,46579,46580,46581,46582,46583,46584,46585,46586,46587,46588,46589,46590,46591,46592,46593,46594,46595,46596,46597,46598,46599,46600,46601,46602,46603,46604,46605,46606,46607,46610,46611,46613,46614,46615,46617,46618,46619,46620,46621,null,null,null,null,null,null,46622,46623,46624,46625,46626,46627,46628,46630,46631,46632,46633,46634,46635,46637,46638,46639,46640,46641,46642,46643,46645,46646,46647,46648,46649,46650,null,null,null,null,null,null,46651,46652,46653,46654,46655,46656,46657,46658,46659,46660,46661,46662,46663,46665,46666,46667,46668,46669,46670,46671,46672,46673,46674,46675,46676,46677,46678,46679,46680,46681,46682,46683,46684,46685,46686,46687,46688,46689,46690,46691,46693,46694,46695,46697,46698,46699,46700,46701,46702,46703,46704,46705,46706,46707,46708,46709,46710,46711,46712,46713,46714,46715,46716,46717,46718,46719,46720,46721,46722,46723,46724,46725,46726,46727,46728,46729,46730,46731,46732,46733,46734,46735,46736,46737,46738,46739,46740,46741,46742,46743,46744,46745,46746,46747,46750,46751,46753,46754,46755,46757,46758,46759,46760,46761,46762,46765,46766,46767,46768,46770,46771,46772,46773,46774,46775,46776,46777,46778,46779,46780,46781,46782,46783,46784,46785,46786,46787,46788,46789,46790,46791,46792,46793,46794,46795,46796,46797,46798,46799,46800,46801,46802,46803,46805,46806,46807,46808,46809,46810,46811,46812,46813,null,null,null,null,null,null,46814,46815,46816,46817,46818,46819,46820,46821,46822,46823,46824,46825,46826,46827,46828,46829,46830,46831,46833,46834,46835,46837,46838,46839,46841,46842,null,null,null,null,null,null,46843,46844,46845,46846,46847,46850,46851,46852,46854,46855,46856,46857,46858,46859,46860,46861,46862,46863,46864,46865,46866,46867,46868,46869,46870,46871,46872,46873,46874,46875,46876,46877,46878,46879,46880,46881,46882,46883,46884,46885,46886,46887,46890,46891,46893,46894,46897,46898,46899,46900,46901,46902,46903,46906,46908,46909,46910,46911,46912,46913,46914,46915,46917,46918,46919,46921,46922,46923,46925,46926,46927,46928,46929,46930,46931,46934,46935,46936,46937,46938,46939,46940,46941,46942,46943,46945,46946,46947,46949,46950,46951,46953,46954,46955,46956,46957,46958,46959,46962,46964,46966,46967,46968,46969,46970,46971,46974,46975,46977,46978,46979,46981,46982,46983,46984,46985,46986,46987,46990,46995,46996,46997,47002,47003,47005,47006,47007,47009,47010,47011,47012,47013,47014,47015,47018,47022,47023,47024,47025,47026,47027,47030,47031,47033,47034,47035,47036,47037,47038,47039,47040,47041,null,null,null,null,null,null,47042,47043,47044,47045,47046,47048,47050,47051,47052,47053,47054,47055,47056,47057,47058,47059,47060,47061,47062,47063,47064,47065,47066,47067,47068,47069,null,null,null,null,null,null,47070,47071,47072,47073,47074,47075,47076,47077,47078,47079,47080,47081,47082,47083,47086,47087,47089,47090,47091,47093,47094,47095,47096,47097,47098,47099,47102,47106,47107,47108,47109,47110,47114,47115,47117,47118,47119,47121,47122,47123,47124,47125,47126,47127,47130,47132,47134,47135,47136,47137,47138,47139,47142,47143,47145,47146,47147,47149,47150,47151,47152,47153,47154,47155,47158,47162,47163,47164,47165,47166,47167,47169,47170,47171,47173,47174,47175,47176,47177,47178,47179,47180,47181,47182,47183,47184,47186,47188,47189,47190,47191,47192,47193,47194,47195,47198,47199,47201,47202,47203,47205,47206,47207,47208,47209,47210,47211,47214,47216,47218,47219,47220,47221,47222,47223,47225,47226,47227,47229,47230,47231,47232,47233,47234,47235,47236,47237,47238,47239,47240,47241,47242,47243,47244,47246,47247,47248,47249,47250,47251,47252,47253,47254,47255,47256,47257,47258,47259,47260,47261,47262,47263,null,null,null,null,null,null,47264,47265,47266,47267,47268,47269,47270,47271,47273,47274,47275,47276,47277,47278,47279,47281,47282,47283,47285,47286,47287,47289,47290,47291,47292,47293,null,null,null,null,null,null,47294,47295,47298,47300,47302,47303,47304,47305,47306,47307,47309,47310,47311,47313,47314,47315,47317,47318,47319,47320,47321,47322,47323,47324,47326,47328,47330,47331,47332,47333,47334,47335,47338,47339,47341,47342,47343,47345,47346,47347,47348,47349,47350,47351,47354,47356,47358,47359,47360,47361,47362,47363,47365,47366,47367,47368,47369,47370,47371,47372,47373,47374,47375,47376,47377,47378,47379,47380,47381,47382,47383,47385,47386,47387,47388,47389,47390,47391,47393,47394,47395,47396,47397,47398,47399,47400,47401,47402,47403,47404,47405,47406,47407,47408,47409,47410,47411,47412,47413,47414,47415,47416,47417,47418,47419,47422,47423,47425,47426,47427,47429,47430,47431,47432,47433,47434,47435,47437,47438,47440,47442,47443,47444,47445,47446,47447,47450,47451,47453,47454,47455,47457,47458,47459,47460,47461,47462,47463,47466,47468,47470,47471,47472,47473,47474,47475,47478,47479,47481,47482,47483,47485,null,null,null,null,null,null,47486,47487,47488,47489,47490,47491,47494,47496,47499,47500,47503,47504,47505,47506,47507,47508,47509,47510,47511,47512,47513,47514,47515,47516,47517,47518,null,null,null,null,null,null,47519,47520,47521,47522,47523,47524,47525,47526,47527,47528,47529,47530,47531,47534,47535,47537,47538,47539,47541,47542,47543,47544,47545,47546,47547,47550,47552,47554,47555,47556,47557,47558,47559,47562,47563,47565,47571,47572,47573,47574,47575,47578,47580,47583,47584,47586,47590,47591,47593,47594,47595,47597,47598,47599,47600,47601,47602,47603,47606,47611,47612,47613,47614,47615,47618,47619,47620,47621,47622,47623,47625,47626,47627,47628,47629,47630,47631,47632,47633,47634,47635,47636,47638,47639,47640,47641,47642,47643,47644,47645,47646,47647,47648,47649,47650,47651,47652,47653,47654,47655,47656,47657,47658,47659,47660,47661,47662,47663,47664,47665,47666,47667,47668,47669,47670,47671,47674,47675,47677,47678,47679,47681,47683,47684,47685,47686,47687,47690,47692,47695,47696,47697,47698,47702,47703,47705,47706,47707,47709,47710,47711,47712,47713,47714,47715,47718,47722,47723,47724,47725,47726,47727,null,null,null,null,null,null,47730,47731,47733,47734,47735,47737,47738,47739,47740,47741,47742,47743,47744,47745,47746,47750,47752,47753,47754,47755,47757,47758,47759,47760,47761,47762,null,null,null,null,null,null,47763,47764,47765,47766,47767,47768,47769,47770,47771,47772,47773,47774,47775,47776,47777,47778,47779,47780,47781,47782,47783,47786,47789,47790,47791,47793,47795,47796,47797,47798,47799,47802,47804,47806,47807,47808,47809,47810,47811,47813,47814,47815,47817,47818,47819,47820,47821,47822,47823,47824,47825,47826,47827,47828,47829,47830,47831,47834,47835,47836,47837,47838,47839,47840,47841,47842,47843,47844,47845,47846,47847,47848,47849,47850,47851,47852,47853,47854,47855,47856,47857,47858,47859,47860,47861,47862,47863,47864,47865,47866,47867,47869,47870,47871,47873,47874,47875,47877,47878,47879,47880,47881,47882,47883,47884,47886,47888,47890,47891,47892,47893,47894,47895,47897,47898,47899,47901,47902,47903,47905,47906,47907,47908,47909,47910,47911,47912,47914,47916,47917,47918,47919,47920,47921,47922,47923,47927,47929,47930,47935,47936,47937,47938,47939,47942,47944,47946,47947,47948,47950,47953,47954,null,null,null,null,null,null,47955,47957,47958,47959,47961,47962,47963,47964,47965,47966,47967,47968,47970,47972,47973,47974,47975,47976,47977,47978,47979,47981,47982,47983,47984,47985,null,null,null,null,null,null,47986,47987,47988,47989,47990,47991,47992,47993,47994,47995,47996,47997,47998,47999,48000,48001,48002,48003,48004,48005,48006,48007,48009,48010,48011,48013,48014,48015,48017,48018,48019,48020,48021,48022,48023,48024,48025,48026,48027,48028,48029,48030,48031,48032,48033,48034,48035,48037,48038,48039,48041,48042,48043,48045,48046,48047,48048,48049,48050,48051,48053,48054,48056,48057,48058,48059,48060,48061,48062,48063,48065,48066,48067,48069,48070,48071,48073,48074,48075,48076,48077,48078,48079,48081,48082,48084,48085,48086,48087,48088,48089,48090,48091,48092,48093,48094,48095,48096,48097,48098,48099,48100,48101,48102,48103,48104,48105,48106,48107,48108,48109,48110,48111,48112,48113,48114,48115,48116,48117,48118,48119,48122,48123,48125,48126,48129,48131,48132,48133,48134,48135,48138,48142,48144,48146,48147,48153,48154,48160,48161,48162,48163,48166,48168,48170,48171,48172,48174,48175,48178,48179,48181,null,null,null,null,null,null,48182,48183,48185,48186,48187,48188,48189,48190,48191,48194,48198,48199,48200,48202,48203,48206,48207,48209,48210,48211,48212,48213,48214,48215,48216,48217,null,null,null,null,null,null,48218,48219,48220,48222,48223,48224,48225,48226,48227,48228,48229,48230,48231,48232,48233,48234,48235,48236,48237,48238,48239,48240,48241,48242,48243,48244,48245,48246,48247,48248,48249,48250,48251,48252,48253,48254,48255,48256,48257,48258,48259,48262,48263,48265,48266,48269,48271,48272,48273,48274,48275,48278,48280,48283,48284,48285,48286,48287,48290,48291,48293,48294,48297,48298,48299,48300,48301,48302,48303,48306,48310,48311,48312,48313,48314,48315,48318,48319,48321,48322,48323,48325,48326,48327,48328,48329,48330,48331,48332,48334,48338,48339,48340,48342,48343,48345,48346,48347,48349,48350,48351,48352,48353,48354,48355,48356,48357,48358,48359,48360,48361,48362,48363,48364,48365,48366,48367,48368,48369,48370,48371,48375,48377,48378,48379,48381,48382,48383,48384,48385,48386,48387,48390,48392,48394,48395,48396,48397,48398,48399,48401,48402,48403,48405,48406,48407,48408,48409,48410,48411,48412,48413,null,null,null,null,null,null,48414,48415,48416,48417,48418,48419,48421,48422,48423,48424,48425,48426,48427,48429,48430,48431,48432,48433,48434,48435,48436,48437,48438,48439,48440,48441,null,null,null,null,null,null,48442,48443,48444,48445,48446,48447,48449,48450,48451,48452,48453,48454,48455,48458,48459,48461,48462,48463,48465,48466,48467,48468,48469,48470,48471,48474,48475,48476,48477,48478,48479,48480,48481,48482,48483,48485,48486,48487,48489,48490,48491,48492,48493,48494,48495,48496,48497,48498,48499,48500,48501,48502,48503,48504,48505,48506,48507,48508,48509,48510,48511,48514,48515,48517,48518,48523,48524,48525,48526,48527,48530,48532,48534,48535,48536,48539,48541,48542,48543,48544,48545,48546,48547,48549,48550,48551,48552,48553,48554,48555,48556,48557,48558,48559,48561,48562,48563,48564,48565,48566,48567,48569,48570,48571,48572,48573,48574,48575,48576,48577,48578,48579,48580,48581,48582,48583,48584,48585,48586,48587,48588,48589,48590,48591,48592,48593,48594,48595,48598,48599,48601,48602,48603,48605,48606,48607,48608,48609,48610,48611,48612,48613,48614,48615,48616,48618,48619,48620,48621,48622,48623,48625,null,null,null,null,null,null,48626,48627,48629,48630,48631,48633,48634,48635,48636,48637,48638,48639,48641,48642,48644,48646,48647,48648,48649,48650,48651,48654,48655,48657,48658,48659,null,null,null,null,null,null,48661,48662,48663,48664,48665,48666,48667,48670,48672,48673,48674,48675,48676,48677,48678,48679,48680,48681,48682,48683,48684,48685,48686,48687,48688,48689,48690,48691,48692,48693,48694,48695,48696,48697,48698,48699,48700,48701,48702,48703,48704,48705,48706,48707,48710,48711,48713,48714,48715,48717,48719,48720,48721,48722,48723,48726,48728,48732,48733,48734,48735,48738,48739,48741,48742,48743,48745,48747,48748,48749,48750,48751,48754,48758,48759,48760,48761,48762,48766,48767,48769,48770,48771,48773,48774,48775,48776,48777,48778,48779,48782,48786,48787,48788,48789,48790,48791,48794,48795,48796,48797,48798,48799,48800,48801,48802,48803,48804,48805,48806,48807,48809,48810,48811,48812,48813,48814,48815,48816,48817,48818,48819,48820,48821,48822,48823,48824,48825,48826,48827,48828,48829,48830,48831,48832,48833,48834,48835,48836,48837,48838,48839,48840,48841,48842,48843,48844,48845,48846,48847,48850,48851,null,null,null,null,null,null,48853,48854,48857,48858,48859,48860,48861,48862,48863,48865,48866,48870,48871,48872,48873,48874,48875,48877,48878,48879,48880,48881,48882,48883,48884,48885,null,null,null,null,null,null,48886,48887,48888,48889,48890,48891,48892,48893,48894,48895,48896,48898,48899,48900,48901,48902,48903,48906,48907,48908,48909,48910,48911,48912,48913,48914,48915,48916,48917,48918,48919,48922,48926,48927,48928,48929,48930,48931,48932,48933,48934,48935,48936,48937,48938,48939,48940,48941,48942,48943,48944,48945,48946,48947,48948,48949,48950,48951,48952,48953,48954,48955,48956,48957,48958,48959,48962,48963,48965,48966,48967,48969,48970,48971,48972,48973,48974,48975,48978,48979,48980,48982,48983,48984,48985,48986,48987,48988,48989,48990,48991,48992,48993,48994,48995,48996,48997,48998,48999,49000,49001,49002,49003,49004,49005,49006,49007,49008,49009,49010,49011,49012,49013,49014,49015,49016,49017,49018,49019,49020,49021,49022,49023,49024,49025,49026,49027,49028,49029,49030,49031,49032,49033,49034,49035,49036,49037,49038,49039,49040,49041,49042,49043,49045,49046,49047,49048,49049,49050,49051,49052,49053,null,null,null,null,null,null,49054,49055,49056,49057,49058,49059,49060,49061,49062,49063,49064,49065,49066,49067,49068,49069,49070,49071,49073,49074,49075,49076,49077,49078,49079,49080,null,null,null,null,null,null,49081,49082,49083,49084,49085,49086,49087,49088,49089,49090,49091,49092,49094,49095,49096,49097,49098,49099,49102,49103,49105,49106,49107,49109,49110,49111,49112,49113,49114,49115,49117,49118,49120,49122,49123,49124,49125,49126,49127,49128,49129,49130,49131,49132,49133,49134,49135,49136,49137,49138,49139,49140,49141,49142,49143,49144,49145,49146,49147,49148,49149,49150,49151,49152,49153,49154,49155,49156,49157,49158,49159,49160,49161,49162,49163,49164,49165,49166,49167,49168,49169,49170,49171,49172,49173,49174,49175,49176,49177,49178,49179,49180,49181,49182,49183,49184,49185,49186,49187,49188,49189,49190,49191,49192,49193,49194,49195,49196,49197,49198,49199,49200,49201,49202,49203,49204,49205,49206,49207,49208,49209,49210,49211,49213,49214,49215,49216,49217,49218,49219,49220,49221,49222,49223,49224,49225,49226,49227,49228,49229,49230,49231,49232,49234,49235,49236,49237,49238,49239,49241,49242,49243,null,null,null,null,null,null,49245,49246,49247,49249,49250,49251,49252,49253,49254,49255,49258,49259,49260,49261,49262,49263,49264,49265,49266,49267,49268,49269,49270,49271,49272,49273,null,null,null,null,null,null,49274,49275,49276,49277,49278,49279,49280,49281,49282,49283,49284,49285,49286,49287,49288,49289,49290,49291,49292,49293,49294,49295,49298,49299,49301,49302,49303,49305,49306,49307,49308,49309,49310,49311,49314,49316,49318,49319,49320,49321,49322,49323,49326,49329,49330,49335,49336,49337,49338,49339,49342,49346,49347,49348,49350,49351,49354,49355,49357,49358,49359,49361,49362,49363,49364,49365,49366,49367,49370,49374,49375,49376,49377,49378,49379,49382,49383,49385,49386,49387,49389,49390,49391,49392,49393,49394,49395,49398,49400,49402,49403,49404,49405,49406,49407,49409,49410,49411,49413,49414,49415,49417,49418,49419,49420,49421,49422,49423,49425,49426,49427,49428,49430,49431,49432,49433,49434,49435,49441,49442,49445,49448,49449,49450,49451,49454,49458,49459,49460,49461,49463,49466,49467,49469,49470,49471,49473,49474,49475,49476,49477,49478,49479,49482,49486,49487,49488,49489,49490,49491,49494,49495,null,null,null,null,null,null,49497,49498,49499,49501,49502,49503,49504,49505,49506,49507,49510,49514,49515,49516,49517,49518,49519,49521,49522,49523,49525,49526,49527,49529,49530,49531,null,null,null,null,null,null,49532,49533,49534,49535,49536,49537,49538,49539,49540,49542,49543,49544,49545,49546,49547,49551,49553,49554,49555,49557,49559,49560,49561,49562,49563,49566,49568,49570,49571,49572,49574,49575,49578,49579,49581,49582,49583,49585,49586,49587,49588,49589,49590,49591,49592,49593,49594,49595,49596,49598,49599,49600,49601,49602,49603,49605,49606,49607,49609,49610,49611,49613,49614,49615,49616,49617,49618,49619,49621,49622,49625,49626,49627,49628,49629,49630,49631,49633,49634,49635,49637,49638,49639,49641,49642,49643,49644,49645,49646,49647,49650,49652,49653,49654,49655,49656,49657,49658,49659,49662,49663,49665,49666,49667,49669,49670,49671,49672,49673,49674,49675,49678,49680,49682,49683,49684,49685,49686,49687,49690,49691,49693,49694,49697,49698,49699,49700,49701,49702,49703,49706,49708,49710,49712,49715,49717,49718,49719,49720,49721,49722,49723,49724,49725,49726,49727,49728,49729,49730,49731,49732,49733,null,null,null,null,null,null,49734,49735,49737,49738,49739,49740,49741,49742,49743,49746,49747,49749,49750,49751,49753,49754,49755,49756,49757,49758,49759,49761,49762,49763,49764,49766,null,null,null,null,null,null,49767,49768,49769,49770,49771,49774,49775,49777,49778,49779,49781,49782,49783,49784,49785,49786,49787,49790,49792,49794,49795,49796,49797,49798,49799,49802,49803,49804,49805,49806,49807,49809,49810,49811,49812,49813,49814,49815,49817,49818,49820,49822,49823,49824,49825,49826,49827,49830,49831,49833,49834,49835,49838,49839,49840,49841,49842,49843,49846,49848,49850,49851,49852,49853,49854,49855,49856,49857,49858,49859,49860,49861,49862,49863,49864,49865,49866,49867,49868,49869,49870,49871,49872,49873,49874,49875,49876,49877,49878,49879,49880,49881,49882,49883,49886,49887,49889,49890,49893,49894,49895,49896,49897,49898,49902,49904,49906,49907,49908,49909,49911,49914,49917,49918,49919,49921,49922,49923,49924,49925,49926,49927,49930,49931,49934,49935,49936,49937,49938,49942,49943,49945,49946,49947,49949,49950,49951,49952,49953,49954,49955,49958,49959,49962,49963,49964,49965,49966,49967,49968,49969,49970,null,null,null,null,null,null,49971,49972,49973,49974,49975,49976,49977,49978,49979,49980,49981,49982,49983,49984,49985,49986,49987,49988,49990,49991,49992,49993,49994,49995,49996,49997,null,null,null,null,null,null,49998,49999,50000,50001,50002,50003,50004,50005,50006,50007,50008,50009,50010,50011,50012,50013,50014,50015,50016,50017,50018,50019,50020,50021,50022,50023,50026,50027,50029,50030,50031,50033,50035,50036,50037,50038,50039,50042,50043,50046,50047,50048,50049,50050,50051,50053,50054,50055,50057,50058,50059,50061,50062,50063,50064,50065,50066,50067,50068,50069,50070,50071,50072,50073,50074,50075,50076,50077,50078,50079,50080,50081,50082,50083,50084,50085,50086,50087,50088,50089,50090,50091,50092,50093,50094,50095,50096,50097,50098,50099,50100,50101,50102,50103,50104,50105,50106,50107,50108,50109,50110,50111,50113,50114,50115,50116,50117,50118,50119,50120,50121,50122,50123,50124,50125,50126,50127,50128,50129,50130,50131,50132,50133,50134,50135,50138,50139,50141,50142,50145,50147,50148,50149,50150,50151,50154,50155,50156,50158,50159,50160,50161,50162,50163,50166,50167,50169,50170,50171,50172,50173,50174,null,null,null,null,null,null,50175,50176,50177,50178,50179,50180,50181,50182,50183,50185,50186,50187,50188,50189,50190,50191,50193,50194,50195,50196,50197,50198,50199,50200,50201,50202,null,null,null,null,null,null,50203,50204,50205,50206,50207,50208,50209,50210,50211,50213,50214,50215,50216,50217,50218,50219,50221,50222,50223,50225,50226,50227,50229,50230,50231,50232,50233,50234,50235,50238,50239,50240,50241,50242,50243,50244,50245,50246,50247,50249,50250,50251,50252,50253,50254,50255,50256,50257,50258,50259,50260,50261,50262,50263,50264,50265,50266,50267,50268,50269,50270,50271,50272,50273,50274,50275,50278,50279,50281,50282,50283,50285,50286,50287,50288,50289,50290,50291,50294,50295,50296,50298,50299,50300,50301,50302,50303,50305,50306,50307,50308,50309,50310,50311,50312,50313,50314,50315,50316,50317,50318,50319,50320,50321,50322,50323,50325,50326,50327,50328,50329,50330,50331,50333,50334,50335,50336,50337,50338,50339,50340,50341,50342,50343,50344,50345,50346,50347,50348,50349,50350,50351,50352,50353,50354,50355,50356,50357,50358,50359,50361,50362,50363,50365,50366,50367,50368,50369,50370,50371,50372,50373,null,null,null,null,null,null,50374,50375,50376,50377,50378,50379,50380,50381,50382,50383,50384,50385,50386,50387,50388,50389,50390,50391,50392,50393,50394,50395,50396,50397,50398,50399,null,null,null,null,null,null,50400,50401,50402,50403,50404,50405,50406,50407,50408,50410,50411,50412,50413,50414,50415,50418,50419,50421,50422,50423,50425,50427,50428,50429,50430,50434,50435,50436,50437,50438,50439,50440,50441,50442,50443,50445,50446,50447,50449,50450,50451,50453,50454,50455,50456,50457,50458,50459,50461,50462,50463,50464,50465,50466,50467,50468,50469,50470,50471,50474,50475,50477,50478,50479,50481,50482,50483,50484,50485,50486,50487,50490,50492,50494,50495,50496,50497,50498,50499,50502,50503,50507,50511,50512,50513,50514,50518,50522,50523,50524,50527,50530,50531,50533,50534,50535,50537,50538,50539,50540,50541,50542,50543,50546,50550,50551,50552,50553,50554,50555,50558,50559,50561,50562,50563,50565,50566,50568,50569,50570,50571,50574,50576,50578,50579,50580,50582,50585,50586,50587,50589,50590,50591,50593,50594,50595,50596,50597,50598,50599,50600,50602,50603,50604,50605,50606,50607,50608,50609,50610,50611,50614,null,null,null,null,null,null,50615,50618,50623,50624,50625,50626,50627,50635,50637,50639,50642,50643,50645,50646,50647,50649,50650,50651,50652,50653,50654,50655,50658,50660,50662,50663,null,null,null,null,null,null,50664,50665,50666,50667,50671,50673,50674,50675,50677,50680,50681,50682,50683,50690,50691,50692,50697,50698,50699,50701,50702,50703,50705,50706,50707,50708,50709,50710,50711,50714,50717,50718,50719,50720,50721,50722,50723,50726,50727,50729,50730,50731,50735,50737,50738,50742,50744,50746,50748,50749,50750,50751,50754,50755,50757,50758,50759,50761,50762,50763,50764,50765,50766,50767,50770,50774,50775,50776,50777,50778,50779,50782,50783,50785,50786,50787,50788,50789,50790,50791,50792,50793,50794,50795,50797,50798,50800,50802,50803,50804,50805,50806,50807,50810,50811,50813,50814,50815,50817,50818,50819,50820,50821,50822,50823,50826,50828,50830,50831,50832,50833,50834,50835,50838,50839,50841,50842,50843,50845,50846,50847,50848,50849,50850,50851,50854,50856,50858,50859,50860,50861,50862,50863,50866,50867,50869,50870,50871,50875,50876,50877,50878,50879,50882,50884,50886,50887,50888,50889,50890,50891,50894,null,null,null,null,null,null,50895,50897,50898,50899,50901,50902,50903,50904,50905,50906,50907,50910,50911,50914,50915,50916,50917,50918,50919,50922,50923,50925,50926,50927,50929,50930,null,null,null,null,null,null,50931,50932,50933,50934,50935,50938,50939,50940,50942,50943,50944,50945,50946,50947,50950,50951,50953,50954,50955,50957,50958,50959,50960,50961,50962,50963,50966,50968,50970,50971,50972,50973,50974,50975,50978,50979,50981,50982,50983,50985,50986,50987,50988,50989,50990,50991,50994,50996,50998,51000,51001,51002,51003,51006,51007,51009,51010,51011,51013,51014,51015,51016,51017,51019,51022,51024,51033,51034,51035,51037,51038,51039,51041,51042,51043,51044,51045,51046,51047,51049,51050,51052,51053,51054,51055,51056,51057,51058,51059,51062,51063,51065,51066,51067,51071,51072,51073,51074,51078,51083,51084,51085,51087,51090,51091,51093,51097,51099,51100,51101,51102,51103,51106,51111,51112,51113,51114,51115,51118,51119,51121,51122,51123,51125,51126,51127,51128,51129,51130,51131,51134,51138,51139,51140,51141,51142,51143,51146,51147,51149,51151,51153,51154,51155,51156,51157,51158,51159,51161,51162,51163,51164,null,null,null,null,null,null,51166,51167,51168,51169,51170,51171,51173,51174,51175,51177,51178,51179,51181,51182,51183,51184,51185,51186,51187,51188,51189,51190,51191,51192,51193,51194,null,null,null,null,null,null,51195,51196,51197,51198,51199,51202,51203,51205,51206,51207,51209,51211,51212,51213,51214,51215,51218,51220,51223,51224,51225,51226,51227,51230,51231,51233,51234,51235,51237,51238,51239,51240,51241,51242,51243,51246,51248,51250,51251,51252,51253,51254,51255,51257,51258,51259,51261,51262,51263,51265,51266,51267,51268,51269,51270,51271,51274,51275,51278,51279,51280,51281,51282,51283,51285,51286,51287,51288,51289,51290,51291,51292,51293,51294,51295,51296,51297,51298,51299,51300,51301,51302,51303,51304,51305,51306,51307,51308,51309,51310,51311,51314,51315,51317,51318,51319,51321,51323,51324,51325,51326,51327,51330,51332,51336,51337,51338,51342,51343,51344,51345,51346,51347,51349,51350,51351,51352,51353,51354,51355,51356,51358,51360,51362,51363,51364,51365,51366,51367,51369,51370,51371,51372,51373,51374,51375,51376,51377,51378,51379,51380,51381,51382,51383,51384,51385,51386,51387,51390,51391,51392,51393,null,null,null,null,null,null,51394,51395,51397,51398,51399,51401,51402,51403,51405,51406,51407,51408,51409,51410,51411,51414,51416,51418,51419,51420,51421,51422,51423,51426,51427,51429,null,null,null,null,null,null,51430,51431,51432,51433,51434,51435,51436,51437,51438,51439,51440,51441,51442,51443,51444,51446,51447,51448,51449,51450,51451,51454,51455,51457,51458,51459,51463,51464,51465,51466,51467,51470,12288,12289,12290,183,8229,8230,168,12291,173,8213,8741,65340,8764,8216,8217,8220,8221,12308,12309,12296,12297,12298,12299,12300,12301,12302,12303,12304,12305,177,215,247,8800,8804,8805,8734,8756,176,8242,8243,8451,8491,65504,65505,65509,9794,9792,8736,8869,8978,8706,8711,8801,8786,167,8251,9734,9733,9675,9679,9678,9671,9670,9633,9632,9651,9650,9661,9660,8594,8592,8593,8595,8596,12307,8810,8811,8730,8765,8733,8757,8747,8748,8712,8715,8838,8839,8834,8835,8746,8745,8743,8744,65506,51472,51474,51475,51476,51477,51478,51479,51481,51482,51483,51484,51485,51486,51487,51488,51489,51490,51491,51492,51493,51494,51495,51496,51497,51498,51499,null,null,null,null,null,null,51501,51502,51503,51504,51505,51506,51507,51509,51510,51511,51512,51513,51514,51515,51516,51517,51518,51519,51520,51521,51522,51523,51524,51525,51526,51527,null,null,null,null,null,null,51528,51529,51530,51531,51532,51533,51534,51535,51538,51539,51541,51542,51543,51545,51546,51547,51548,51549,51550,51551,51554,51556,51557,51558,51559,51560,51561,51562,51563,51565,51566,51567,8658,8660,8704,8707,180,65374,711,728,733,730,729,184,731,161,191,720,8750,8721,8719,164,8457,8240,9665,9664,9655,9654,9828,9824,9825,9829,9831,9827,8857,9672,9635,9680,9681,9618,9636,9637,9640,9639,9638,9641,9832,9743,9742,9756,9758,182,8224,8225,8597,8599,8601,8598,8600,9837,9833,9834,9836,12927,12828,8470,13255,8482,13250,13272,8481,8364,174,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,51569,51570,51571,51573,51574,51575,51576,51577,51578,51579,51581,51582,51583,51584,51585,51586,51587,51588,51589,51590,51591,51594,51595,51597,51598,51599,null,null,null,null,null,null,51601,51602,51603,51604,51605,51606,51607,51610,51612,51614,51615,51616,51617,51618,51619,51620,51621,51622,51623,51624,51625,51626,51627,51628,51629,51630,null,null,null,null,null,null,51631,51632,51633,51634,51635,51636,51637,51638,51639,51640,51641,51642,51643,51644,51645,51646,51647,51650,51651,51653,51654,51657,51659,51660,51661,51662,51663,51666,51668,51671,51672,51675,65281,65282,65283,65284,65285,65286,65287,65288,65289,65290,65291,65292,65293,65294,65295,65296,65297,65298,65299,65300,65301,65302,65303,65304,65305,65306,65307,65308,65309,65310,65311,65312,65313,65314,65315,65316,65317,65318,65319,65320,65321,65322,65323,65324,65325,65326,65327,65328,65329,65330,65331,65332,65333,65334,65335,65336,65337,65338,65339,65510,65341,65342,65343,65344,65345,65346,65347,65348,65349,65350,65351,65352,65353,65354,65355,65356,65357,65358,65359,65360,65361,65362,65363,65364,65365,65366,65367,65368,65369,65370,65371,65372,65373,65507,51678,51679,51681,51683,51685,51686,51688,51689,51690,51691,51694,51698,51699,51700,51701,51702,51703,51706,51707,51709,51710,51711,51713,51714,51715,51716,null,null,null,null,null,null,51717,51718,51719,51722,51726,51727,51728,51729,51730,51731,51733,51734,51735,51737,51738,51739,51740,51741,51742,51743,51744,51745,51746,51747,51748,51749,null,null,null,null,null,null,51750,51751,51752,51754,51755,51756,51757,51758,51759,51760,51761,51762,51763,51764,51765,51766,51767,51768,51769,51770,51771,51772,51773,51774,51775,51776,51777,51778,51779,51780,51781,51782,12593,12594,12595,12596,12597,12598,12599,12600,12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616,12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632,12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,12647,12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663,12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679,12680,12681,12682,12683,12684,12685,12686,51783,51784,51785,51786,51787,51790,51791,51793,51794,51795,51797,51798,51799,51800,51801,51802,51803,51806,51810,51811,51812,51813,51814,51815,51817,51818,null,null,null,null,null,null,51819,51820,51821,51822,51823,51824,51825,51826,51827,51828,51829,51830,51831,51832,51833,51834,51835,51836,51838,51839,51840,51841,51842,51843,51845,51846,null,null,null,null,null,null,51847,51848,51849,51850,51851,51852,51853,51854,51855,51856,51857,51858,51859,51860,51861,51862,51863,51865,51866,51867,51868,51869,51870,51871,51872,51873,51874,51875,51876,51877,51878,51879,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,null,null,null,null,null,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,null,null,null,null,null,null,null,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,null,null,null,null,null,null,null,null,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,963,964,965,966,967,968,969,null,null,null,null,null,null,51880,51881,51882,51883,51884,51885,51886,51887,51888,51889,51890,51891,51892,51893,51894,51895,51896,51897,51898,51899,51902,51903,51905,51906,51907,51909,null,null,null,null,null,null,51910,51911,51912,51913,51914,51915,51918,51920,51922,51924,51925,51926,51927,51930,51931,51932,51933,51934,51935,51937,51938,51939,51940,51941,51942,51943,null,null,null,null,null,null,51944,51945,51946,51947,51949,51950,51951,51952,51953,51954,51955,51957,51958,51959,51960,51961,51962,51963,51964,51965,51966,51967,51968,51969,51970,51971,51972,51973,51974,51975,51977,51978,9472,9474,9484,9488,9496,9492,9500,9516,9508,9524,9532,9473,9475,9487,9491,9499,9495,9507,9523,9515,9531,9547,9504,9519,9512,9527,9535,9501,9520,9509,9528,9538,9490,9489,9498,9497,9494,9493,9486,9485,9502,9503,9505,9506,9510,9511,9513,9514,9517,9518,9521,9522,9525,9526,9529,9530,9533,9534,9536,9537,9539,9540,9541,9542,9543,9544,9545,9546,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,51979,51980,51981,51982,51983,51985,51986,51987,51989,51990,51991,51993,51994,51995,51996,51997,51998,51999,52002,52003,52004,52005,52006,52007,52008,52009,null,null,null,null,null,null,52010,52011,52012,52013,52014,52015,52016,52017,52018,52019,52020,52021,52022,52023,52024,52025,52026,52027,52028,52029,52030,52031,52032,52034,52035,52036,null,null,null,null,null,null,52037,52038,52039,52042,52043,52045,52046,52047,52049,52050,52051,52052,52053,52054,52055,52058,52059,52060,52062,52063,52064,52065,52066,52067,52069,52070,52071,52072,52073,52074,52075,52076,13205,13206,13207,8467,13208,13252,13219,13220,13221,13222,13209,13210,13211,13212,13213,13214,13215,13216,13217,13218,13258,13197,13198,13199,13263,13192,13193,13256,13223,13224,13232,13233,13234,13235,13236,13237,13238,13239,13240,13241,13184,13185,13186,13187,13188,13242,13243,13244,13245,13246,13247,13200,13201,13202,13203,13204,8486,13248,13249,13194,13195,13196,13270,13253,13229,13230,13231,13275,13225,13226,13227,13228,13277,13264,13267,13251,13257,13276,13254,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,52077,52078,52079,52080,52081,52082,52083,52084,52085,52086,52087,52090,52091,52092,52093,52094,52095,52096,52097,52098,52099,52100,52101,52102,52103,52104,null,null,null,null,null,null,52105,52106,52107,52108,52109,52110,52111,52112,52113,52114,52115,52116,52117,52118,52119,52120,52121,52122,52123,52125,52126,52127,52128,52129,52130,52131,null,null,null,null,null,null,52132,52133,52134,52135,52136,52137,52138,52139,52140,52141,52142,52143,52144,52145,52146,52147,52148,52149,52150,52151,52153,52154,52155,52156,52157,52158,52159,52160,52161,52162,52163,52164,198,208,170,294,null,306,null,319,321,216,338,186,222,358,330,null,12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911,12912,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,9424,9425,9426,9427,9428,9429,9430,9431,9432,9433,9434,9435,9436,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446,9447,9448,9449,9312,9313,9314,9315,9316,9317,9318,9319,9320,9321,9322,9323,9324,9325,9326,189,8531,8532,188,190,8539,8540,8541,8542,52165,52166,52167,52168,52169,52170,52171,52172,52173,52174,52175,52176,52177,52178,52179,52181,52182,52183,52184,52185,52186,52187,52188,52189,52190,52191,null,null,null,null,null,null,52192,52193,52194,52195,52197,52198,52200,52202,52203,52204,52205,52206,52207,52208,52209,52210,52211,52212,52213,52214,52215,52216,52217,52218,52219,52220,null,null,null,null,null,null,52221,52222,52223,52224,52225,52226,52227,52228,52229,52230,52231,52232,52233,52234,52235,52238,52239,52241,52242,52243,52245,52246,52247,52248,52249,52250,52251,52254,52255,52256,52259,52260,230,273,240,295,305,307,312,320,322,248,339,223,254,359,331,329,12800,12801,12802,12803,12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819,12820,12821,12822,12823,12824,12825,12826,12827,9372,9373,9374,9375,9376,9377,9378,9379,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389,9390,9391,9392,9393,9394,9395,9396,9397,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345,9346,185,178,179,8308,8319,8321,8322,8323,8324,52261,52262,52266,52267,52269,52271,52273,52274,52275,52276,52277,52278,52279,52282,52287,52288,52289,52290,52291,52294,52295,52297,52298,52299,52301,52302,null,null,null,null,null,null,52303,52304,52305,52306,52307,52310,52314,52315,52316,52317,52318,52319,52321,52322,52323,52325,52327,52329,52330,52331,52332,52333,52334,52335,52337,52338,null,null,null,null,null,null,52339,52340,52342,52343,52344,52345,52346,52347,52348,52349,52350,52351,52352,52353,52354,52355,52356,52357,52358,52359,52360,52361,52362,52363,52364,52365,52366,52367,52368,52369,52370,52371,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,null,null,null,null,null,null,null,null,null,null,null,52372,52373,52374,52375,52378,52379,52381,52382,52383,52385,52386,52387,52388,52389,52390,52391,52394,52398,52399,52400,52401,52402,52403,52406,52407,52409,null,null,null,null,null,null,52410,52411,52413,52414,52415,52416,52417,52418,52419,52422,52424,52426,52427,52428,52429,52430,52431,52433,52434,52435,52437,52438,52439,52440,52441,52442,null,null,null,null,null,null,52443,52444,52445,52446,52447,52448,52449,52450,52451,52453,52454,52455,52456,52457,52458,52459,52461,52462,52463,52465,52466,52467,52468,52469,52470,52471,52472,52473,52474,52475,52476,52477,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,null,null,null,null,null,null,null,null,52478,52479,52480,52482,52483,52484,52485,52486,52487,52490,52491,52493,52494,52495,52497,52498,52499,52500,52501,52502,52503,52506,52508,52510,52511,52512,null,null,null,null,null,null,52513,52514,52515,52517,52518,52519,52521,52522,52523,52525,52526,52527,52528,52529,52530,52531,52532,52533,52534,52535,52536,52538,52539,52540,52541,52542,null,null,null,null,null,null,52543,52544,52545,52546,52547,52548,52549,52550,52551,52552,52553,52554,52555,52556,52557,52558,52559,52560,52561,52562,52563,52564,52565,52566,52567,52568,52569,52570,52571,52573,52574,52575,1040,1041,1042,1043,1044,1045,1025,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,1072,1073,1074,1075,1076,1077,1105,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,null,null,null,null,null,null,null,null,null,null,null,null,null,52577,52578,52579,52581,52582,52583,52584,52585,52586,52587,52590,52592,52594,52595,52596,52597,52598,52599,52601,52602,52603,52604,52605,52606,52607,52608,null,null,null,null,null,null,52609,52610,52611,52612,52613,52614,52615,52617,52618,52619,52620,52621,52622,52623,52624,52625,52626,52627,52630,52631,52633,52634,52635,52637,52638,52639,null,null,null,null,null,null,52640,52641,52642,52643,52646,52648,52650,52651,52652,52653,52654,52655,52657,52658,52659,52660,52661,52662,52663,52664,52665,52666,52667,52668,52669,52670,52671,52672,52673,52674,52675,52677,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,52678,52679,52680,52681,52682,52683,52685,52686,52687,52689,52690,52691,52692,52693,52694,52695,52696,52697,52698,52699,52700,52701,52702,52703,52704,52705,null,null,null,null,null,null,52706,52707,52708,52709,52710,52711,52713,52714,52715,52717,52718,52719,52721,52722,52723,52724,52725,52726,52727,52730,52732,52734,52735,52736,52737,52738,null,null,null,null,null,null,52739,52741,52742,52743,52745,52746,52747,52749,52750,52751,52752,52753,52754,52755,52757,52758,52759,52760,52762,52763,52764,52765,52766,52767,52770,52771,52773,52774,52775,52777,52778,52779,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,52780,52781,52782,52783,52786,52788,52790,52791,52792,52793,52794,52795,52796,52797,52798,52799,52800,52801,52802,52803,52804,52805,52806,52807,52808,52809,null,null,null,null,null,null,52810,52811,52812,52813,52814,52815,52816,52817,52818,52819,52820,52821,52822,52823,52826,52827,52829,52830,52834,52835,52836,52837,52838,52839,52842,52844,null,null,null,null,null,null,52846,52847,52848,52849,52850,52851,52854,52855,52857,52858,52859,52861,52862,52863,52864,52865,52866,52867,52870,52872,52874,52875,52876,52877,52878,52879,52882,52883,52885,52886,52887,52889,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,52890,52891,52892,52893,52894,52895,52898,52902,52903,52904,52905,52906,52907,52910,52911,52912,52913,52914,52915,52916,52917,52918,52919,52920,52921,52922,null,null,null,null,null,null,52923,52924,52925,52926,52927,52928,52930,52931,52932,52933,52934,52935,52936,52937,52938,52939,52940,52941,52942,52943,52944,52945,52946,52947,52948,52949,null,null,null,null,null,null,52950,52951,52952,52953,52954,52955,52956,52957,52958,52959,52960,52961,52962,52963,52966,52967,52969,52970,52973,52974,52975,52976,52977,52978,52979,52982,52986,52987,52988,52989,52990,52991,44032,44033,44036,44039,44040,44041,44042,44048,44049,44050,44051,44052,44053,44054,44055,44057,44058,44059,44060,44061,44064,44068,44076,44077,44079,44080,44081,44088,44089,44092,44096,44107,44109,44116,44120,44124,44144,44145,44148,44151,44152,44154,44160,44161,44163,44164,44165,44166,44169,44170,44171,44172,44176,44180,44188,44189,44191,44192,44193,44200,44201,44202,44204,44207,44208,44216,44217,44219,44220,44221,44225,44228,44232,44236,44245,44247,44256,44257,44260,44263,44264,44266,44268,44271,44272,44273,44275,44277,44278,44284,44285,44288,44292,44294,52994,52995,52997,52998,52999,53001,53002,53003,53004,53005,53006,53007,53010,53012,53014,53015,53016,53017,53018,53019,53021,53022,53023,53025,53026,53027,null,null,null,null,null,null,53029,53030,53031,53032,53033,53034,53035,53038,53042,53043,53044,53045,53046,53047,53049,53050,53051,53052,53053,53054,53055,53056,53057,53058,53059,53060,null,null,null,null,null,null,53061,53062,53063,53064,53065,53066,53067,53068,53069,53070,53071,53072,53073,53074,53075,53078,53079,53081,53082,53083,53085,53086,53087,53088,53089,53090,53091,53094,53096,53098,53099,53100,44300,44301,44303,44305,44312,44316,44320,44329,44332,44333,44340,44341,44344,44348,44356,44357,44359,44361,44368,44372,44376,44385,44387,44396,44397,44400,44403,44404,44405,44406,44411,44412,44413,44415,44417,44418,44424,44425,44428,44432,44444,44445,44452,44471,44480,44481,44484,44488,44496,44497,44499,44508,44512,44516,44536,44537,44540,44543,44544,44545,44552,44553,44555,44557,44564,44592,44593,44596,44599,44600,44602,44608,44609,44611,44613,44614,44618,44620,44621,44622,44624,44628,44630,44636,44637,44639,44640,44641,44645,44648,44649,44652,44656,44664,53101,53102,53103,53106,53107,53109,53110,53111,53113,53114,53115,53116,53117,53118,53119,53121,53122,53123,53124,53126,53127,53128,53129,53130,53131,53133,null,null,null,null,null,null,53134,53135,53136,53137,53138,53139,53140,53141,53142,53143,53144,53145,53146,53147,53148,53149,53150,53151,53152,53154,53155,53156,53157,53158,53159,53161,null,null,null,null,null,null,53162,53163,53164,53165,53166,53167,53169,53170,53171,53172,53173,53174,53175,53176,53177,53178,53179,53180,53181,53182,53183,53184,53185,53186,53187,53189,53190,53191,53192,53193,53194,53195,44665,44667,44668,44669,44676,44677,44684,44732,44733,44734,44736,44740,44748,44749,44751,44752,44753,44760,44761,44764,44776,44779,44781,44788,44792,44796,44807,44808,44813,44816,44844,44845,44848,44850,44852,44860,44861,44863,44865,44866,44867,44872,44873,44880,44892,44893,44900,44901,44921,44928,44932,44936,44944,44945,44949,44956,44984,44985,44988,44992,44999,45000,45001,45003,45005,45006,45012,45020,45032,45033,45040,45041,45044,45048,45056,45057,45060,45068,45072,45076,45084,45085,45096,45124,45125,45128,45130,45132,45134,45139,45140,45141,45143,45145,53196,53197,53198,53199,53200,53201,53202,53203,53204,53205,53206,53207,53208,53209,53210,53211,53212,53213,53214,53215,53218,53219,53221,53222,53223,53225,null,null,null,null,null,null,53226,53227,53228,53229,53230,53231,53234,53236,53238,53239,53240,53241,53242,53243,53245,53246,53247,53249,53250,53251,53253,53254,53255,53256,53257,53258,null,null,null,null,null,null,53259,53260,53261,53262,53263,53264,53266,53267,53268,53269,53270,53271,53273,53274,53275,53276,53277,53278,53279,53280,53281,53282,53283,53284,53285,53286,53287,53288,53289,53290,53291,53292,45149,45180,45181,45184,45188,45196,45197,45199,45201,45208,45209,45210,45212,45215,45216,45217,45218,45224,45225,45227,45228,45229,45230,45231,45233,45235,45236,45237,45240,45244,45252,45253,45255,45256,45257,45264,45265,45268,45272,45280,45285,45320,45321,45323,45324,45328,45330,45331,45336,45337,45339,45340,45341,45347,45348,45349,45352,45356,45364,45365,45367,45368,45369,45376,45377,45380,45384,45392,45393,45396,45397,45400,45404,45408,45432,45433,45436,45440,45442,45448,45449,45451,45453,45458,45459,45460,45464,45468,45480,45516,45520,45524,45532,45533,53294,53295,53296,53297,53298,53299,53302,53303,53305,53306,53307,53309,53310,53311,53312,53313,53314,53315,53318,53320,53322,53323,53324,53325,53326,53327,null,null,null,null,null,null,53329,53330,53331,53333,53334,53335,53337,53338,53339,53340,53341,53342,53343,53345,53346,53347,53348,53349,53350,53351,53352,53353,53354,53355,53358,53359,null,null,null,null,null,null,53361,53362,53363,53365,53366,53367,53368,53369,53370,53371,53374,53375,53376,53378,53379,53380,53381,53382,53383,53384,53385,53386,53387,53388,53389,53390,53391,53392,53393,53394,53395,53396,45535,45544,45545,45548,45552,45561,45563,45565,45572,45573,45576,45579,45580,45588,45589,45591,45593,45600,45620,45628,45656,45660,45664,45672,45673,45684,45685,45692,45700,45701,45705,45712,45713,45716,45720,45721,45722,45728,45729,45731,45733,45734,45738,45740,45744,45748,45768,45769,45772,45776,45778,45784,45785,45787,45789,45794,45796,45797,45798,45800,45803,45804,45805,45806,45807,45811,45812,45813,45815,45816,45817,45818,45819,45823,45824,45825,45828,45832,45840,45841,45843,45844,45845,45852,45908,45909,45910,45912,45915,45916,45918,45919,45924,45925,53397,53398,53399,53400,53401,53402,53403,53404,53405,53406,53407,53408,53409,53410,53411,53414,53415,53417,53418,53419,53421,53422,53423,53424,53425,53426,null,null,null,null,null,null,53427,53430,53432,53434,53435,53436,53437,53438,53439,53442,53443,53445,53446,53447,53450,53451,53452,53453,53454,53455,53458,53462,53463,53464,53465,53466,null,null,null,null,null,null,53467,53470,53471,53473,53474,53475,53477,53478,53479,53480,53481,53482,53483,53486,53490,53491,53492,53493,53494,53495,53497,53498,53499,53500,53501,53502,53503,53504,53505,53506,53507,53508,45927,45929,45931,45934,45936,45937,45940,45944,45952,45953,45955,45956,45957,45964,45968,45972,45984,45985,45992,45996,46020,46021,46024,46027,46028,46030,46032,46036,46037,46039,46041,46043,46045,46048,46052,46056,46076,46096,46104,46108,46112,46120,46121,46123,46132,46160,46161,46164,46168,46176,46177,46179,46181,46188,46208,46216,46237,46244,46248,46252,46261,46263,46265,46272,46276,46280,46288,46293,46300,46301,46304,46307,46308,46310,46316,46317,46319,46321,46328,46356,46357,46360,46363,46364,46372,46373,46375,46376,46377,46378,46384,46385,46388,46392,53509,53510,53511,53512,53513,53514,53515,53516,53518,53519,53520,53521,53522,53523,53524,53525,53526,53527,53528,53529,53530,53531,53532,53533,53534,53535,null,null,null,null,null,null,53536,53537,53538,53539,53540,53541,53542,53543,53544,53545,53546,53547,53548,53549,53550,53551,53554,53555,53557,53558,53559,53561,53563,53564,53565,53566,null,null,null,null,null,null,53567,53570,53574,53575,53576,53577,53578,53579,53582,53583,53585,53586,53587,53589,53590,53591,53592,53593,53594,53595,53598,53600,53602,53603,53604,53605,53606,53607,53609,53610,53611,53613,46400,46401,46403,46404,46405,46411,46412,46413,46416,46420,46428,46429,46431,46432,46433,46496,46497,46500,46504,46506,46507,46512,46513,46515,46516,46517,46523,46524,46525,46528,46532,46540,46541,46543,46544,46545,46552,46572,46608,46609,46612,46616,46629,46636,46644,46664,46692,46696,46748,46749,46752,46756,46763,46764,46769,46804,46832,46836,46840,46848,46849,46853,46888,46889,46892,46895,46896,46904,46905,46907,46916,46920,46924,46932,46933,46944,46948,46952,46960,46961,46963,46965,46972,46973,46976,46980,46988,46989,46991,46992,46993,46994,46998,46999,53614,53615,53616,53617,53618,53619,53620,53621,53622,53623,53624,53625,53626,53627,53629,53630,53631,53632,53633,53634,53635,53637,53638,53639,53641,53642,null,null,null,null,null,null,53643,53644,53645,53646,53647,53648,53649,53650,53651,53652,53653,53654,53655,53656,53657,53658,53659,53660,53661,53662,53663,53666,53667,53669,53670,53671,null,null,null,null,null,null,53673,53674,53675,53676,53677,53678,53679,53682,53684,53686,53687,53688,53689,53691,53693,53694,53695,53697,53698,53699,53700,53701,53702,53703,53704,53705,53706,53707,53708,53709,53710,53711,47000,47001,47004,47008,47016,47017,47019,47020,47021,47028,47029,47032,47047,47049,47084,47085,47088,47092,47100,47101,47103,47104,47105,47111,47112,47113,47116,47120,47128,47129,47131,47133,47140,47141,47144,47148,47156,47157,47159,47160,47161,47168,47172,47185,47187,47196,47197,47200,47204,47212,47213,47215,47217,47224,47228,47245,47272,47280,47284,47288,47296,47297,47299,47301,47308,47312,47316,47325,47327,47329,47336,47337,47340,47344,47352,47353,47355,47357,47364,47384,47392,47420,47421,47424,47428,47436,47439,47441,47448,47449,47452,47456,47464,47465,53712,53713,53714,53715,53716,53717,53718,53719,53721,53722,53723,53724,53725,53726,53727,53728,53729,53730,53731,53732,53733,53734,53735,53736,53737,53738,null,null,null,null,null,null,53739,53740,53741,53742,53743,53744,53745,53746,53747,53749,53750,53751,53753,53754,53755,53756,53757,53758,53759,53760,53761,53762,53763,53764,53765,53766,null,null,null,null,null,null,53768,53770,53771,53772,53773,53774,53775,53777,53778,53779,53780,53781,53782,53783,53784,53785,53786,53787,53788,53789,53790,53791,53792,53793,53794,53795,53796,53797,53798,53799,53800,53801,47467,47469,47476,47477,47480,47484,47492,47493,47495,47497,47498,47501,47502,47532,47533,47536,47540,47548,47549,47551,47553,47560,47561,47564,47566,47567,47568,47569,47570,47576,47577,47579,47581,47582,47585,47587,47588,47589,47592,47596,47604,47605,47607,47608,47609,47610,47616,47617,47624,47637,47672,47673,47676,47680,47682,47688,47689,47691,47693,47694,47699,47700,47701,47704,47708,47716,47717,47719,47720,47721,47728,47729,47732,47736,47747,47748,47749,47751,47756,47784,47785,47787,47788,47792,47794,47800,47801,47803,47805,47812,47816,47832,47833,47868,53802,53803,53806,53807,53809,53810,53811,53813,53814,53815,53816,53817,53818,53819,53822,53824,53826,53827,53828,53829,53830,53831,53833,53834,53835,53836,null,null,null,null,null,null,53837,53838,53839,53840,53841,53842,53843,53844,53845,53846,53847,53848,53849,53850,53851,53853,53854,53855,53856,53857,53858,53859,53861,53862,53863,53864,null,null,null,null,null,null,53865,53866,53867,53868,53869,53870,53871,53872,53873,53874,53875,53876,53877,53878,53879,53880,53881,53882,53883,53884,53885,53886,53887,53890,53891,53893,53894,53895,53897,53898,53899,53900,47872,47876,47885,47887,47889,47896,47900,47904,47913,47915,47924,47925,47926,47928,47931,47932,47933,47934,47940,47941,47943,47945,47949,47951,47952,47956,47960,47969,47971,47980,48008,48012,48016,48036,48040,48044,48052,48055,48064,48068,48072,48080,48083,48120,48121,48124,48127,48128,48130,48136,48137,48139,48140,48141,48143,48145,48148,48149,48150,48151,48152,48155,48156,48157,48158,48159,48164,48165,48167,48169,48173,48176,48177,48180,48184,48192,48193,48195,48196,48197,48201,48204,48205,48208,48221,48260,48261,48264,48267,48268,48270,48276,48277,48279,53901,53902,53903,53906,53907,53908,53910,53911,53912,53913,53914,53915,53917,53918,53919,53921,53922,53923,53925,53926,53927,53928,53929,53930,53931,53933,null,null,null,null,null,null,53934,53935,53936,53938,53939,53940,53941,53942,53943,53946,53947,53949,53950,53953,53955,53956,53957,53958,53959,53962,53964,53965,53966,53967,53968,53969,null,null,null,null,null,null,53970,53971,53973,53974,53975,53977,53978,53979,53981,53982,53983,53984,53985,53986,53987,53990,53991,53992,53993,53994,53995,53996,53997,53998,53999,54002,54003,54005,54006,54007,54009,54010,48281,48282,48288,48289,48292,48295,48296,48304,48305,48307,48308,48309,48316,48317,48320,48324,48333,48335,48336,48337,48341,48344,48348,48372,48373,48374,48376,48380,48388,48389,48391,48393,48400,48404,48420,48428,48448,48456,48457,48460,48464,48472,48473,48484,48488,48512,48513,48516,48519,48520,48521,48522,48528,48529,48531,48533,48537,48538,48540,48548,48560,48568,48596,48597,48600,48604,48617,48624,48628,48632,48640,48643,48645,48652,48653,48656,48660,48668,48669,48671,48708,48709,48712,48716,48718,48724,48725,48727,48729,48730,48731,48736,48737,48740,54011,54012,54013,54014,54015,54018,54020,54022,54023,54024,54025,54026,54027,54031,54033,54034,54035,54037,54039,54040,54041,54042,54043,54046,54050,54051,null,null,null,null,null,null,54052,54054,54055,54058,54059,54061,54062,54063,54065,54066,54067,54068,54069,54070,54071,54074,54078,54079,54080,54081,54082,54083,54086,54087,54088,54089,null,null,null,null,null,null,54090,54091,54092,54093,54094,54095,54096,54097,54098,54099,54100,54101,54102,54103,54104,54105,54106,54107,54108,54109,54110,54111,54112,54113,54114,54115,54116,54117,54118,54119,54120,54121,48744,48746,48752,48753,48755,48756,48757,48763,48764,48765,48768,48772,48780,48781,48783,48784,48785,48792,48793,48808,48848,48849,48852,48855,48856,48864,48867,48868,48869,48876,48897,48904,48905,48920,48921,48923,48924,48925,48960,48961,48964,48968,48976,48977,48981,49044,49072,49093,49100,49101,49104,49108,49116,49119,49121,49212,49233,49240,49244,49248,49256,49257,49296,49297,49300,49304,49312,49313,49315,49317,49324,49325,49327,49328,49331,49332,49333,49334,49340,49341,49343,49344,49345,49349,49352,49353,49356,49360,49368,49369,49371,49372,49373,49380,54122,54123,54124,54125,54126,54127,54128,54129,54130,54131,54132,54133,54134,54135,54136,54137,54138,54139,54142,54143,54145,54146,54147,54149,54150,54151,null,null,null,null,null,null,54152,54153,54154,54155,54158,54162,54163,54164,54165,54166,54167,54170,54171,54173,54174,54175,54177,54178,54179,54180,54181,54182,54183,54186,54188,54190,null,null,null,null,null,null,54191,54192,54193,54194,54195,54197,54198,54199,54201,54202,54203,54205,54206,54207,54208,54209,54210,54211,54214,54215,54218,54219,54220,54221,54222,54223,54225,54226,54227,54228,54229,54230,49381,49384,49388,49396,49397,49399,49401,49408,49412,49416,49424,49429,49436,49437,49438,49439,49440,49443,49444,49446,49447,49452,49453,49455,49456,49457,49462,49464,49465,49468,49472,49480,49481,49483,49484,49485,49492,49493,49496,49500,49508,49509,49511,49512,49513,49520,49524,49528,49541,49548,49549,49550,49552,49556,49558,49564,49565,49567,49569,49573,49576,49577,49580,49584,49597,49604,49608,49612,49620,49623,49624,49632,49636,49640,49648,49649,49651,49660,49661,49664,49668,49676,49677,49679,49681,49688,49689,49692,49695,49696,49704,49705,49707,49709,54231,54233,54234,54235,54236,54237,54238,54239,54240,54242,54244,54245,54246,54247,54248,54249,54250,54251,54254,54255,54257,54258,54259,54261,54262,54263,null,null,null,null,null,null,54264,54265,54266,54267,54270,54272,54274,54275,54276,54277,54278,54279,54281,54282,54283,54284,54285,54286,54287,54288,54289,54290,54291,54292,54293,54294,null,null,null,null,null,null,54295,54296,54297,54298,54299,54300,54302,54303,54304,54305,54306,54307,54308,54309,54310,54311,54312,54313,54314,54315,54316,54317,54318,54319,54320,54321,54322,54323,54324,54325,54326,54327,49711,49713,49714,49716,49736,49744,49745,49748,49752,49760,49765,49772,49773,49776,49780,49788,49789,49791,49793,49800,49801,49808,49816,49819,49821,49828,49829,49832,49836,49837,49844,49845,49847,49849,49884,49885,49888,49891,49892,49899,49900,49901,49903,49905,49910,49912,49913,49915,49916,49920,49928,49929,49932,49933,49939,49940,49941,49944,49948,49956,49957,49960,49961,49989,50024,50025,50028,50032,50034,50040,50041,50044,50045,50052,50056,50060,50112,50136,50137,50140,50143,50144,50146,50152,50153,50157,50164,50165,50168,50184,50192,50212,50220,50224,54328,54329,54330,54331,54332,54333,54334,54335,54337,54338,54339,54341,54342,54343,54344,54345,54346,54347,54348,54349,54350,54351,54352,54353,54354,54355,null,null,null,null,null,null,54356,54357,54358,54359,54360,54361,54362,54363,54365,54366,54367,54369,54370,54371,54373,54374,54375,54376,54377,54378,54379,54380,54382,54384,54385,54386,null,null,null,null,null,null,54387,54388,54389,54390,54391,54394,54395,54397,54398,54401,54403,54404,54405,54406,54407,54410,54412,54414,54415,54416,54417,54418,54419,54421,54422,54423,54424,54425,54426,54427,54428,54429,50228,50236,50237,50248,50276,50277,50280,50284,50292,50293,50297,50304,50324,50332,50360,50364,50409,50416,50417,50420,50424,50426,50431,50432,50433,50444,50448,50452,50460,50472,50473,50476,50480,50488,50489,50491,50493,50500,50501,50504,50505,50506,50508,50509,50510,50515,50516,50517,50519,50520,50521,50525,50526,50528,50529,50532,50536,50544,50545,50547,50548,50549,50556,50557,50560,50564,50567,50572,50573,50575,50577,50581,50583,50584,50588,50592,50601,50612,50613,50616,50617,50619,50620,50621,50622,50628,50629,50630,50631,50632,50633,50634,50636,50638,54430,54431,54432,54433,54434,54435,54436,54437,54438,54439,54440,54442,54443,54444,54445,54446,54447,54448,54449,54450,54451,54452,54453,54454,54455,54456,null,null,null,null,null,null,54457,54458,54459,54460,54461,54462,54463,54464,54465,54466,54467,54468,54469,54470,54471,54472,54473,54474,54475,54477,54478,54479,54481,54482,54483,54485,null,null,null,null,null,null,54486,54487,54488,54489,54490,54491,54493,54494,54496,54497,54498,54499,54500,54501,54502,54503,54505,54506,54507,54509,54510,54511,54513,54514,54515,54516,54517,54518,54519,54521,54522,54524,50640,50641,50644,50648,50656,50657,50659,50661,50668,50669,50670,50672,50676,50678,50679,50684,50685,50686,50687,50688,50689,50693,50694,50695,50696,50700,50704,50712,50713,50715,50716,50724,50725,50728,50732,50733,50734,50736,50739,50740,50741,50743,50745,50747,50752,50753,50756,50760,50768,50769,50771,50772,50773,50780,50781,50784,50796,50799,50801,50808,50809,50812,50816,50824,50825,50827,50829,50836,50837,50840,50844,50852,50853,50855,50857,50864,50865,50868,50872,50873,50874,50880,50881,50883,50885,50892,50893,50896,50900,50908,50909,50912,50913,50920,54526,54527,54528,54529,54530,54531,54533,54534,54535,54537,54538,54539,54541,54542,54543,54544,54545,54546,54547,54550,54552,54553,54554,54555,54556,54557,null,null,null,null,null,null,54558,54559,54560,54561,54562,54563,54564,54565,54566,54567,54568,54569,54570,54571,54572,54573,54574,54575,54576,54577,54578,54579,54580,54581,54582,54583,null,null,null,null,null,null,54584,54585,54586,54587,54590,54591,54593,54594,54595,54597,54598,54599,54600,54601,54602,54603,54606,54608,54610,54611,54612,54613,54614,54615,54618,54619,54621,54622,54623,54625,54626,54627,50921,50924,50928,50936,50937,50941,50948,50949,50952,50956,50964,50965,50967,50969,50976,50977,50980,50984,50992,50993,50995,50997,50999,51004,51005,51008,51012,51018,51020,51021,51023,51025,51026,51027,51028,51029,51030,51031,51032,51036,51040,51048,51051,51060,51061,51064,51068,51069,51070,51075,51076,51077,51079,51080,51081,51082,51086,51088,51089,51092,51094,51095,51096,51098,51104,51105,51107,51108,51109,51110,51116,51117,51120,51124,51132,51133,51135,51136,51137,51144,51145,51148,51150,51152,51160,51165,51172,51176,51180,51200,51201,51204,51208,51210,54628,54630,54631,54634,54636,54638,54639,54640,54641,54642,54643,54646,54647,54649,54650,54651,54653,54654,54655,54656,54657,54658,54659,54662,54666,54667,null,null,null,null,null,null,54668,54669,54670,54671,54673,54674,54675,54676,54677,54678,54679,54680,54681,54682,54683,54684,54685,54686,54687,54688,54689,54690,54691,54692,54694,54695,null,null,null,null,null,null,54696,54697,54698,54699,54700,54701,54702,54703,54704,54705,54706,54707,54708,54709,54710,54711,54712,54713,54714,54715,54716,54717,54718,54719,54720,54721,54722,54723,54724,54725,54726,54727,51216,51217,51219,51221,51222,51228,51229,51232,51236,51244,51245,51247,51249,51256,51260,51264,51272,51273,51276,51277,51284,51312,51313,51316,51320,51322,51328,51329,51331,51333,51334,51335,51339,51340,51341,51348,51357,51359,51361,51368,51388,51389,51396,51400,51404,51412,51413,51415,51417,51424,51425,51428,51445,51452,51453,51456,51460,51461,51462,51468,51469,51471,51473,51480,51500,51508,51536,51537,51540,51544,51552,51553,51555,51564,51568,51572,51580,51592,51593,51596,51600,51608,51609,51611,51613,51648,51649,51652,51655,51656,51658,51664,51665,51667,54730,54731,54733,54734,54735,54737,54739,54740,54741,54742,54743,54746,54748,54750,54751,54752,54753,54754,54755,54758,54759,54761,54762,54763,54765,54766,null,null,null,null,null,null,54767,54768,54769,54770,54771,54774,54776,54778,54779,54780,54781,54782,54783,54786,54787,54789,54790,54791,54793,54794,54795,54796,54797,54798,54799,54802,null,null,null,null,null,null,54806,54807,54808,54809,54810,54811,54813,54814,54815,54817,54818,54819,54821,54822,54823,54824,54825,54826,54827,54828,54830,54831,54832,54833,54834,54835,54836,54837,54838,54839,54842,54843,51669,51670,51673,51674,51676,51677,51680,51682,51684,51687,51692,51693,51695,51696,51697,51704,51705,51708,51712,51720,51721,51723,51724,51725,51732,51736,51753,51788,51789,51792,51796,51804,51805,51807,51808,51809,51816,51837,51844,51864,51900,51901,51904,51908,51916,51917,51919,51921,51923,51928,51929,51936,51948,51956,51976,51984,51988,51992,52000,52001,52033,52040,52041,52044,52048,52056,52057,52061,52068,52088,52089,52124,52152,52180,52196,52199,52201,52236,52237,52240,52244,52252,52253,52257,52258,52263,52264,52265,52268,52270,52272,52280,52281,52283,54845,54846,54847,54849,54850,54851,54852,54854,54855,54858,54860,54862,54863,54864,54866,54867,54870,54871,54873,54874,54875,54877,54878,54879,54880,54881,null,null,null,null,null,null,54882,54883,54884,54885,54886,54888,54890,54891,54892,54893,54894,54895,54898,54899,54901,54902,54903,54904,54905,54906,54907,54908,54909,54910,54911,54912,null,null,null,null,null,null,54913,54914,54916,54918,54919,54920,54921,54922,54923,54926,54927,54929,54930,54931,54933,54934,54935,54936,54937,54938,54939,54940,54942,54944,54946,54947,54948,54949,54950,54951,54953,54954,52284,52285,52286,52292,52293,52296,52300,52308,52309,52311,52312,52313,52320,52324,52326,52328,52336,52341,52376,52377,52380,52384,52392,52393,52395,52396,52397,52404,52405,52408,52412,52420,52421,52423,52425,52432,52436,52452,52460,52464,52481,52488,52489,52492,52496,52504,52505,52507,52509,52516,52520,52524,52537,52572,52576,52580,52588,52589,52591,52593,52600,52616,52628,52629,52632,52636,52644,52645,52647,52649,52656,52676,52684,52688,52712,52716,52720,52728,52729,52731,52733,52740,52744,52748,52756,52761,52768,52769,52772,52776,52784,52785,52787,52789,54955,54957,54958,54959,54961,54962,54963,54964,54965,54966,54967,54968,54970,54972,54973,54974,54975,54976,54977,54978,54979,54982,54983,54985,54986,54987,null,null,null,null,null,null,54989,54990,54991,54992,54994,54995,54997,54998,55000,55002,55003,55004,55005,55006,55007,55009,55010,55011,55013,55014,55015,55017,55018,55019,55020,55021,null,null,null,null,null,null,55022,55023,55025,55026,55027,55028,55030,55031,55032,55033,55034,55035,55038,55039,55041,55042,55043,55045,55046,55047,55048,55049,55050,55051,55052,55053,55054,55055,55056,55058,55059,55060,52824,52825,52828,52831,52832,52833,52840,52841,52843,52845,52852,52853,52856,52860,52868,52869,52871,52873,52880,52881,52884,52888,52896,52897,52899,52900,52901,52908,52909,52929,52964,52965,52968,52971,52972,52980,52981,52983,52984,52985,52992,52993,52996,53000,53008,53009,53011,53013,53020,53024,53028,53036,53037,53039,53040,53041,53048,53076,53077,53080,53084,53092,53093,53095,53097,53104,53105,53108,53112,53120,53125,53132,53153,53160,53168,53188,53216,53217,53220,53224,53232,53233,53235,53237,53244,53248,53252,53265,53272,53293,53300,53301,53304,53308,55061,55062,55063,55066,55067,55069,55070,55071,55073,55074,55075,55076,55077,55078,55079,55082,55084,55086,55087,55088,55089,55090,55091,55094,55095,55097,null,null,null,null,null,null,55098,55099,55101,55102,55103,55104,55105,55106,55107,55109,55110,55112,55114,55115,55116,55117,55118,55119,55122,55123,55125,55130,55131,55132,55133,55134,null,null,null,null,null,null,55135,55138,55140,55142,55143,55144,55146,55147,55149,55150,55151,55153,55154,55155,55157,55158,55159,55160,55161,55162,55163,55166,55167,55168,55170,55171,55172,55173,55174,55175,55178,55179,53316,53317,53319,53321,53328,53332,53336,53344,53356,53357,53360,53364,53372,53373,53377,53412,53413,53416,53420,53428,53429,53431,53433,53440,53441,53444,53448,53449,53456,53457,53459,53460,53461,53468,53469,53472,53476,53484,53485,53487,53488,53489,53496,53517,53552,53553,53556,53560,53562,53568,53569,53571,53572,53573,53580,53581,53584,53588,53596,53597,53599,53601,53608,53612,53628,53636,53640,53664,53665,53668,53672,53680,53681,53683,53685,53690,53692,53696,53720,53748,53752,53767,53769,53776,53804,53805,53808,53812,53820,53821,53823,53825,53832,53852,55181,55182,55183,55185,55186,55187,55188,55189,55190,55191,55194,55196,55198,55199,55200,55201,55202,55203,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,53860,53888,53889,53892,53896,53904,53905,53909,53916,53920,53924,53932,53937,53944,53945,53948,53951,53952,53954,53960,53961,53963,53972,53976,53980,53988,53989,54000,54001,54004,54008,54016,54017,54019,54021,54028,54029,54030,54032,54036,54038,54044,54045,54047,54048,54049,54053,54056,54057,54060,54064,54072,54073,54075,54076,54077,54084,54085,54140,54141,54144,54148,54156,54157,54159,54160,54161,54168,54169,54172,54176,54184,54185,54187,54189,54196,54200,54204,54212,54213,54216,54217,54224,54232,54241,54243,54252,54253,54256,54260,54268,54269,54271,54273,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,54280,54301,54336,54340,54364,54368,54372,54381,54383,54392,54393,54396,54399,54400,54402,54408,54409,54411,54413,54420,54441,54476,54480,54484,54492,54495,54504,54508,54512,54520,54523,54525,54532,54536,54540,54548,54549,54551,54588,54589,54592,54596,54604,54605,54607,54609,54616,54617,54620,54624,54629,54632,54633,54635,54637,54644,54645,54648,54652,54660,54661,54663,54664,54665,54672,54693,54728,54729,54732,54736,54738,54744,54745,54747,54749,54756,54757,54760,54764,54772,54773,54775,54777,54784,54785,54788,54792,54800,54801,54803,54804,54805,54812,54816,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,54820,54829,54840,54841,54844,54848,54853,54856,54857,54859,54861,54865,54868,54869,54872,54876,54887,54889,54896,54897,54900,54915,54917,54924,54925,54928,54932,54941,54943,54945,54952,54956,54960,54969,54971,54980,54981,54984,54988,54993,54996,54999,55001,55008,55012,55016,55024,55029,55036,55037,55040,55044,55057,55064,55065,55068,55072,55080,55081,55083,55085,55092,55093,55096,55100,55108,55111,55113,55120,55121,55124,55126,55127,55128,55129,55136,55137,55139,55141,55145,55148,55152,55156,55164,55165,55169,55176,55177,55180,55184,55192,55193,55195,55197,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,20285,20339,20551,20729,21152,21487,21621,21733,22025,23233,23478,26247,26550,26551,26607,27468,29634,30146,31292,33499,33540,34903,34952,35382,36040,36303,36603,36838,39381,21051,21364,21508,24682,24932,27580,29647,33050,35258,35282,38307,20355,21002,22718,22904,23014,24178,24185,25031,25536,26438,26604,26751,28567,30286,30475,30965,31240,31487,31777,32925,33390,33393,35563,38291,20075,21917,26359,28212,30883,31469,33883,35088,34638,38824,21208,22350,22570,23884,24863,25022,25121,25954,26577,27204,28187,29976,30131,30435,30640,32058,37039,37969,37970,40853,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,21283,23724,30002,32987,37440,38296,21083,22536,23004,23713,23831,24247,24378,24394,24951,27743,30074,30086,31968,32115,32177,32652,33108,33313,34193,35137,35611,37628,38477,40007,20171,20215,20491,20977,22607,24887,24894,24936,25913,27114,28433,30117,30342,30422,31623,33445,33995,63744,37799,38283,21888,23458,22353,63745,31923,32697,37301,20520,21435,23621,24040,25298,25454,25818,25831,28192,28844,31067,36317,36382,63746,36989,37445,37624,20094,20214,20581,24062,24314,24838,26967,33137,34388,36423,37749,39467,20062,20625,26480,26688,20745,21133,21138,27298,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,30652,37392,40660,21163,24623,36850,20552,25001,25581,25802,26684,27268,28608,33160,35233,38548,22533,29309,29356,29956,32121,32365,32937,35211,35700,36963,40273,25225,27770,28500,32080,32570,35363,20860,24906,31645,35609,37463,37772,20140,20435,20510,20670,20742,21185,21197,21375,22384,22659,24218,24465,24950,25004,25806,25964,26223,26299,26356,26775,28039,28805,28913,29855,29861,29898,30169,30828,30956,31455,31478,32069,32147,32789,32831,33051,33686,35686,36629,36885,37857,38915,38968,39514,39912,20418,21843,22586,22865,23395,23622,24760,25106,26690,26800,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,26856,28330,30028,30328,30926,31293,31995,32363,32380,35336,35489,35903,38542,40388,21476,21481,21578,21617,22266,22993,23396,23611,24235,25335,25911,25925,25970,26272,26543,27073,27837,30204,30352,30590,31295,32660,32771,32929,33167,33510,33533,33776,34241,34865,34996,35493,63747,36764,37678,38599,39015,39640,40723,21741,26011,26354,26767,31296,35895,40288,22256,22372,23825,26118,26801,26829,28414,29736,34974,39908,27752,63748,39592,20379,20844,20849,21151,23380,24037,24656,24685,25329,25511,25915,29657,31354,34467,36002,38799,20018,23521,25096,26524,29916,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,31185,33747,35463,35506,36328,36942,37707,38982,24275,27112,34303,37101,63749,20896,23448,23532,24931,26874,27454,28748,29743,29912,31649,32592,33733,35264,36011,38364,39208,21038,24669,25324,36866,20362,20809,21281,22745,24291,26336,27960,28826,29378,29654,31568,33009,37979,21350,25499,32619,20054,20608,22602,22750,24618,24871,25296,27088,39745,23439,32024,32945,36703,20132,20689,21676,21932,23308,23968,24039,25898,25934,26657,27211,29409,30350,30703,32094,32761,33184,34126,34527,36611,36686,37066,39171,39509,39851,19992,20037,20061,20167,20465,20855,21246,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,21312,21475,21477,21646,22036,22389,22434,23495,23943,24272,25084,25304,25937,26552,26601,27083,27472,27590,27628,27714,28317,28792,29399,29590,29699,30655,30697,31350,32127,32777,33276,33285,33290,33503,34914,35635,36092,36544,36881,37041,37476,37558,39378,39493,40169,40407,40860,22283,23616,33738,38816,38827,40628,21531,31384,32676,35033,36557,37089,22528,23624,25496,31391,23470,24339,31353,31406,33422,36524,20518,21048,21240,21367,22280,25331,25458,27402,28099,30519,21413,29527,34152,36470,38357,26426,27331,28528,35437,36556,39243,63750,26231,27512,36020,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,39740,63751,21483,22317,22862,25542,27131,29674,30789,31418,31429,31998,33909,35215,36211,36917,38312,21243,22343,30023,31584,33740,37406,63752,27224,20811,21067,21127,25119,26840,26997,38553,20677,21156,21220,25027,26020,26681,27135,29822,31563,33465,33771,35250,35641,36817,39241,63753,20170,22935,25810,26129,27278,29748,31105,31165,33449,34942,34943,35167,63754,37670,20235,21450,24613,25201,27762,32026,32102,20120,20834,30684,32943,20225,20238,20854,20864,21980,22120,22331,22522,22524,22804,22855,22931,23492,23696,23822,24049,24190,24524,25216,26071,26083,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,26398,26399,26462,26827,26820,27231,27450,27683,27773,27778,28103,29592,29734,29738,29826,29859,30072,30079,30849,30959,31041,31047,31048,31098,31637,32000,32186,32648,32774,32813,32908,35352,35663,35912,36215,37665,37668,39138,39249,39438,39439,39525,40594,32202,20342,21513,25326,26708,37329,21931,20794,63755,63756,23068,25062,63757,25295,25343,63758,63759,63760,63761,63762,63763,37027,63764,63765,63766,63767,63768,35582,63769,63770,63771,63772,26262,63773,29014,63774,63775,38627,63776,25423,25466,21335,63777,26511,26976,28275,63778,30007,63779,63780,63781,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,32013,63782,63783,34930,22218,23064,63784,63785,63786,63787,63788,20035,63789,20839,22856,26608,32784,63790,22899,24180,25754,31178,24565,24684,25288,25467,23527,23511,21162,63791,22900,24361,24594,63792,63793,63794,29785,63795,63796,63797,63798,63799,63800,39377,63801,63802,63803,63804,63805,63806,63807,63808,63809,63810,63811,28611,63812,63813,33215,36786,24817,63814,63815,33126,63816,63817,23615,63818,63819,63820,63821,63822,63823,63824,63825,23273,35365,26491,32016,63826,63827,63828,63829,63830,63831,33021,63832,63833,23612,27877,21311,28346,22810,33590,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,20025,20150,20294,21934,22296,22727,24406,26039,26086,27264,27573,28237,30701,31471,31774,32222,34507,34962,37170,37723,25787,28606,29562,30136,36948,21846,22349,25018,25812,26311,28129,28251,28525,28601,30192,32835,33213,34113,35203,35527,35674,37663,27795,30035,31572,36367,36957,21776,22530,22616,24162,25095,25758,26848,30070,31958,34739,40680,20195,22408,22382,22823,23565,23729,24118,24453,25140,25825,29619,33274,34955,36024,38538,40667,23429,24503,24755,20498,20992,21040,22294,22581,22615,23566,23648,23798,23947,24230,24466,24764,25361,25481,25623,26691,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,26873,27330,28120,28193,28372,28644,29182,30428,30585,31153,31291,33796,35241,36077,36339,36424,36867,36884,36947,37117,37709,38518,38876,27602,28678,29272,29346,29544,30563,31167,31716,32411,35712,22697,24775,25958,26109,26302,27788,28958,29129,35930,38931,20077,31361,20189,20908,20941,21205,21516,24999,26481,26704,26847,27934,28540,30140,30643,31461,33012,33891,37509,20828,26007,26460,26515,30168,31431,33651,63834,35910,36887,38957,23663,33216,33434,36929,36975,37389,24471,23965,27225,29128,30331,31561,34276,35588,37159,39472,21895,25078,63835,30313,32645,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,34367,34746,35064,37007,63836,27931,28889,29662,32097,33853,63837,37226,39409,63838,20098,21365,27396,27410,28734,29211,34349,40478,21068,36771,23888,25829,25900,27414,28651,31811,32412,34253,35172,35261,25289,33240,34847,24266,26391,28010,29436,29701,29807,34690,37086,20358,23821,24480,33802,20919,25504,30053,20142,20486,20841,20937,26753,27153,31918,31921,31975,33391,35538,36635,37327,20406,20791,21237,21570,24300,24942,25150,26053,27354,28670,31018,34268,34851,38317,39522,39530,40599,40654,21147,26310,27511,28701,31019,36706,38722,24976,25088,25891,28451,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,29001,29833,32244,32879,34030,36646,36899,37706,20925,21015,21155,27916,28872,35010,24265,25986,27566,28610,31806,29557,20196,20278,22265,63839,23738,23994,24604,29618,31533,32666,32718,32838,36894,37428,38646,38728,38936,40801,20363,28583,31150,37300,38583,21214,63840,25736,25796,27347,28510,28696,29200,30439,32769,34310,34396,36335,36613,38706,39791,40442,40565,30860,31103,32160,33737,37636,40575,40595,35542,22751,24324,26407,28711,29903,31840,32894,20769,28712,29282,30922,36034,36058,36084,38647,20102,20698,23534,24278,26009,29134,30274,30637,32842,34044,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,36988,39719,40845,22744,23105,23650,27155,28122,28431,30267,32047,32311,34078,35128,37860,38475,21129,26066,26611,27060,27969,28316,28687,29705,29792,30041,30244,30827,35628,39006,20845,25134,38520,20374,20523,23833,28138,32184,36650,24459,24900,26647,63841,38534,21202,32907,20956,20940,26974,31260,32190,33777,38517,20442,21033,21400,21519,21774,23653,24743,26446,26792,28012,29313,29432,29702,29827,63842,30178,31852,32633,32696,33673,35023,35041,37324,37328,38626,39881,21533,28542,29136,29848,34298,36522,38563,40023,40607,26519,28107,29747,33256,38678,30764,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,31435,31520,31890,25705,29802,30194,30908,30952,39340,39764,40635,23518,24149,28448,33180,33707,37000,19975,21325,23081,24018,24398,24930,25405,26217,26364,28415,28459,28771,30622,33836,34067,34875,36627,39237,39995,21788,25273,26411,27819,33545,35178,38778,20129,22916,24536,24537,26395,32178,32596,33426,33579,33725,36638,37017,22475,22969,23186,23504,26151,26522,26757,27599,29028,32629,36023,36067,36993,39749,33032,35978,38476,39488,40613,23391,27667,29467,30450,30431,33804,20906,35219,20813,20885,21193,26825,27796,30468,30496,32191,32236,38754,40629,28357,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,34065,20901,21517,21629,26126,26269,26919,28319,30399,30609,33559,33986,34719,37225,37528,40180,34946,20398,20882,21215,22982,24125,24917,25720,25721,26286,26576,27169,27597,27611,29279,29281,29761,30520,30683,32791,33468,33541,35584,35624,35980,26408,27792,29287,30446,30566,31302,40361,27519,27794,22818,26406,33945,21359,22675,22937,24287,25551,26164,26483,28218,29483,31447,33495,37672,21209,24043,25006,25035,25098,25287,25771,26080,26969,27494,27595,28961,29687,30045,32326,33310,33538,34154,35491,36031,38695,40289,22696,40664,20497,21006,21563,21839,25991,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,27766,32010,32011,32862,34442,38272,38639,21247,27797,29289,21619,23194,23614,23883,24396,24494,26410,26806,26979,28220,28228,30473,31859,32654,34183,35598,36855,38753,40692,23735,24758,24845,25003,25935,26107,26108,27665,27887,29599,29641,32225,38292,23494,34588,35600,21085,21338,25293,25615,25778,26420,27192,27850,29632,29854,31636,31893,32283,33162,33334,34180,36843,38649,39361,20276,21322,21453,21467,25292,25644,25856,26001,27075,27886,28504,29677,30036,30242,30436,30460,30928,30971,31020,32070,33324,34784,36820,38930,39151,21187,25300,25765,28196,28497,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,30332,36299,37297,37474,39662,39747,20515,20621,22346,22952,23592,24135,24439,25151,25918,26041,26049,26121,26507,27036,28354,30917,32033,32938,33152,33323,33459,33953,34444,35370,35607,37030,38450,40848,20493,20467,63843,22521,24472,25308,25490,26479,28227,28953,30403,32972,32986,35060,35061,35097,36064,36649,37197,38506,20271,20336,24091,26575,26658,30333,30334,39748,24161,27146,29033,29140,30058,63844,32321,34115,34281,39132,20240,31567,32624,38309,20961,24070,26805,27710,27726,27867,29359,31684,33539,27861,29754,20731,21128,22721,25816,27287,29863,30294,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,30887,34327,38370,38713,63845,21342,24321,35722,36776,36783,37002,21029,30629,40009,40712,19993,20482,20853,23643,24183,26142,26170,26564,26821,28851,29953,30149,31177,31453,36647,39200,39432,20445,22561,22577,23542,26222,27493,27921,28282,28541,29668,29995,33769,35036,35091,35676,36628,20239,20693,21264,21340,23443,24489,26381,31119,33145,33583,34068,35079,35206,36665,36667,39333,39954,26412,20086,20472,22857,23553,23791,23792,25447,26834,28925,29090,29739,32299,34028,34562,36898,37586,40179,19981,20184,20463,20613,21078,21103,21542,21648,22496,22827,23142,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,23386,23413,23500,24220,63846,25206,25975,26023,28014,28325,29238,31526,31807,32566,33104,33105,33178,33344,33433,33705,35331,36000,36070,36091,36212,36282,37096,37340,38428,38468,39385,40167,21271,20998,21545,22132,22707,22868,22894,24575,24996,25198,26128,27774,28954,30406,31881,31966,32027,33452,36033,38640,63847,20315,24343,24447,25282,23849,26379,26842,30844,32323,40300,19989,20633,21269,21290,21329,22915,23138,24199,24754,24970,25161,25209,26000,26503,27047,27604,27606,27607,27608,27832,63848,29749,30202,30738,30865,31189,31192,31875,32203,32737,32933,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,33086,33218,33778,34586,35048,35513,35692,36027,37145,38750,39131,40763,22188,23338,24428,25996,27315,27567,27996,28657,28693,29277,29613,36007,36051,38971,24977,27703,32856,39425,20045,20107,20123,20181,20282,20284,20351,20447,20735,21490,21496,21766,21987,22235,22763,22882,23057,23531,23546,23556,24051,24107,24473,24605,25448,26012,26031,26614,26619,26797,27515,27801,27863,28195,28681,29509,30722,31038,31040,31072,31169,31721,32023,32114,32902,33293,33678,34001,34503,35039,35408,35422,35613,36060,36198,36781,37034,39164,39391,40605,21066,63849,26388,63850,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,20632,21034,23665,25955,27733,29642,29987,30109,31639,33948,37240,38704,20087,25746,27578,29022,34217,19977,63851,26441,26862,28183,33439,34072,34923,25591,28545,37394,39087,19978,20663,20687,20767,21830,21930,22039,23360,23577,23776,24120,24202,24224,24258,24819,26705,27233,28248,29245,29248,29376,30456,31077,31665,32724,35059,35316,35443,35937,36062,38684,22622,29885,36093,21959,63852,31329,32034,33394,29298,29983,29989,63853,31513,22661,22779,23996,24207,24246,24464,24661,25234,25471,25933,26257,26329,26360,26646,26866,29312,29790,31598,32110,32214,32626,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,32997,33298,34223,35199,35475,36893,37604,40653,40736,22805,22893,24109,24796,26132,26227,26512,27728,28101,28511,30707,30889,33990,37323,37675,20185,20682,20808,21892,23307,23459,25159,25982,26059,28210,29053,29697,29764,29831,29887,30316,31146,32218,32341,32680,33146,33203,33337,34330,34796,35445,36323,36984,37521,37925,39245,39854,21352,23633,26964,27844,27945,28203,33292,34203,35131,35373,35498,38634,40807,21089,26297,27570,32406,34814,36109,38275,38493,25885,28041,29166,63854,22478,22995,23468,24615,24826,25104,26143,26207,29481,29689,30427,30465,31596,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,32854,32882,33125,35488,37266,19990,21218,27506,27927,31237,31545,32048,63855,36016,21484,22063,22609,23477,23567,23569,24034,25152,25475,25620,26157,26803,27836,28040,28335,28703,28836,29138,29990,30095,30094,30233,31505,31712,31787,32032,32057,34092,34157,34311,35380,36877,36961,37045,37559,38902,39479,20439,23660,26463,28049,31903,32396,35606,36118,36895,23403,24061,25613,33984,36956,39137,29575,23435,24730,26494,28126,35359,35494,36865,38924,21047,63856,28753,30862,37782,34928,37335,20462,21463,22013,22234,22402,22781,23234,23432,23723,23744,24101,24833,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,25101,25163,25480,25628,25910,25976,27193,27530,27700,27929,28465,29159,29417,29560,29703,29874,30246,30561,31168,31319,31466,31929,32143,32172,32353,32670,33065,33585,33936,34010,34282,34966,35504,35728,36664,36930,36995,37228,37526,37561,38539,38567,38568,38614,38656,38920,39318,39635,39706,21460,22654,22809,23408,23487,28113,28506,29087,29729,29881,32901,33789,24033,24455,24490,24642,26092,26642,26991,27219,27529,27957,28147,29667,30462,30636,31565,32020,33059,33308,33600,34036,34147,35426,35524,37255,37662,38918,39348,25100,34899,36848,37477,23815,23847,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,23913,29791,33181,34664,28629,25342,32722,35126,35186,19998,20056,20711,21213,21319,25215,26119,32361,34821,38494,20365,21273,22070,22987,23204,23608,23630,23629,24066,24337,24643,26045,26159,26178,26558,26612,29468,30690,31034,32709,33940,33997,35222,35430,35433,35553,35925,35962,22516,23508,24335,24687,25325,26893,27542,28252,29060,31698,34645,35672,36606,39135,39166,20280,20353,20449,21627,23072,23480,24892,26032,26216,29180,30003,31070,32051,33102,33251,33688,34218,34254,34563,35338,36523,36763,63857,36805,22833,23460,23526,24713,23529,23563,24515,27777,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,63858,28145,28683,29978,33455,35574,20160,21313,63859,38617,27663,20126,20420,20818,21854,23077,23784,25105,29273,33469,33706,34558,34905,35357,38463,38597,39187,40201,40285,22538,23731,23997,24132,24801,24853,25569,27138,28197,37122,37716,38990,39952,40823,23433,23736,25353,26191,26696,30524,38593,38797,38996,39839,26017,35585,36555,38332,21813,23721,24022,24245,26263,30284,33780,38343,22739,25276,29390,40232,20208,22830,24591,26171,27523,31207,40230,21395,21696,22467,23830,24859,26326,28079,30861,33406,38552,38724,21380,25212,25494,28082,32266,33099,38989,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,27387,32588,40367,40474,20063,20539,20918,22812,24825,25590,26928,29242,32822,63860,37326,24369,63861,63862,32004,33509,33903,33979,34277,36493,63863,20335,63864,63865,22756,23363,24665,25562,25880,25965,26264,63866,26954,27171,27915,28673,29036,30162,30221,31155,31344,63867,32650,63868,35140,63869,35731,37312,38525,63870,39178,22276,24481,26044,28417,30208,31142,35486,39341,39770,40812,20740,25014,25233,27277,33222,20547,22576,24422,28937,35328,35578,23420,34326,20474,20796,22196,22852,25513,28153,23978,26989,20870,20104,20313,63871,63872,63873,22914,63874,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,63875,27487,27741,63876,29877,30998,63877,33287,33349,33593,36671,36701,63878,39192,63879,63880,63881,20134,63882,22495,24441,26131,63883,63884,30123,32377,35695,63885,36870,39515,22181,22567,23032,23071,23476,63886,24310,63887,63888,25424,25403,63889,26941,27783,27839,28046,28051,28149,28436,63890,28895,28982,29017,63891,29123,29141,63892,30799,30831,63893,31605,32227,63894,32303,63895,34893,36575,63896,63897,63898,37467,63899,40182,63900,63901,63902,24709,28037,63903,29105,63904,63905,38321,21421,63906,63907,63908,26579,63909,28814,28976,29744,33398,33490,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,63910,38331,39653,40573,26308,63911,29121,33865,63912,63913,22603,63914,63915,23992,24433,63916,26144,26254,27001,27054,27704,27891,28214,28481,28634,28699,28719,29008,29151,29552,63917,29787,63918,29908,30408,31310,32403,63919,63920,33521,35424,36814,63921,37704,63922,38681,63923,63924,20034,20522,63925,21000,21473,26355,27757,28618,29450,30591,31330,33454,34269,34306,63926,35028,35427,35709,35947,63927,37555,63928,38675,38928,20116,20237,20425,20658,21320,21566,21555,21978,22626,22714,22887,23067,23524,24735,63929,25034,25942,26111,26212,26791,27738,28595,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,28879,29100,29522,31613,34568,35492,39986,40711,23627,27779,29508,29577,37434,28331,29797,30239,31337,32277,34314,20800,22725,25793,29934,29973,30320,32705,37013,38605,39252,28198,29926,31401,31402,33253,34521,34680,35355,23113,23436,23451,26785,26880,28003,29609,29715,29740,30871,32233,32747,33048,33109,33694,35916,38446,38929,26352,24448,26106,26505,27754,29579,20525,23043,27498,30702,22806,23916,24013,29477,30031,63930,63931,20709,20985,22575,22829,22934,23002,23525,63932,63933,23970,25303,25622,25747,25854,63934,26332,63935,27208,63936,29183,29796,63937,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,31368,31407,32327,32350,32768,33136,63938,34799,35201,35616,36953,63939,36992,39250,24958,27442,28020,32287,35109,36785,20433,20653,20887,21191,22471,22665,23481,24248,24898,27029,28044,28263,28342,29076,29794,29992,29996,32883,33592,33993,36362,37780,37854,63940,20110,20305,20598,20778,21448,21451,21491,23431,23507,23588,24858,24962,26100,29275,29591,29760,30402,31056,31121,31161,32006,32701,33419,34261,34398,36802,36935,37109,37354,38533,38632,38633,21206,24423,26093,26161,26671,29020,31286,37057,38922,20113,63941,27218,27550,28560,29065,32792,33464,34131,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,36939,38549,38642,38907,34074,39729,20112,29066,38596,20803,21407,21729,22291,22290,22435,23195,23236,23491,24616,24895,25588,27781,27961,28274,28304,29232,29503,29783,33489,34945,36677,36960,63942,38498,39000,40219,26376,36234,37470,20301,20553,20702,21361,22285,22996,23041,23561,24944,26256,28205,29234,29771,32239,32963,33806,33894,34111,34655,34907,35096,35586,36949,38859,39759,20083,20369,20754,20842,63943,21807,21929,23418,23461,24188,24189,24254,24736,24799,24840,24841,25540,25912,26377,63944,26580,26586,63945,26977,26978,27833,27943,63946,28216,63947,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,28641,29494,29495,63948,29788,30001,63949,30290,63950,63951,32173,33278,33848,35029,35480,35547,35565,36400,36418,36938,36926,36986,37193,37321,37742,63952,63953,22537,63954,27603,32905,32946,63955,63956,20801,22891,23609,63957,63958,28516,29607,32996,36103,63959,37399,38287,63960,63961,63962,63963,32895,25102,28700,32104,34701,63964,22432,24681,24903,27575,35518,37504,38577,20057,21535,28139,34093,38512,38899,39150,25558,27875,37009,20957,25033,33210,40441,20381,20506,20736,23452,24847,25087,25836,26885,27589,30097,30691,32681,33380,34191,34811,34915,35516,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,35696,37291,20108,20197,20234,63965,63966,22839,23016,63967,24050,24347,24411,24609,63968,63969,63970,63971,29246,29669,63972,30064,30157,63973,31227,63974,32780,32819,32900,33505,33617,63975,63976,36029,36019,36999,63977,63978,39156,39180,63979,63980,28727,30410,32714,32716,32764,35610,20154,20161,20995,21360,63981,21693,22240,23035,23493,24341,24525,28270,63982,63983,32106,33589,63984,34451,35469,63985,38765,38775,63986,63987,19968,20314,20350,22777,26085,28322,36920,37808,39353,20219,22764,22922,23001,24641,63988,63989,31252,63990,33615,36035,20837,21316,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,63991,63992,63993,20173,21097,23381,33471,20180,21050,21672,22985,23039,23376,23383,23388,24675,24904,28363,28825,29038,29574,29943,30133,30913,32043,32773,33258,33576,34071,34249,35566,36039,38604,20316,21242,22204,26027,26152,28796,28856,29237,32189,33421,37196,38592,40306,23409,26855,27544,28538,30430,23697,26283,28507,31668,31786,34870,38620,19976,20183,21280,22580,22715,22767,22892,23559,24115,24196,24373,25484,26290,26454,27167,27299,27404,28479,29254,63994,29520,29835,31456,31911,33144,33247,33255,33674,33900,34083,34196,34255,35037,36115,37292,38263,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,38556,20877,21705,22312,23472,25165,26448,26685,26771,28221,28371,28797,32289,35009,36001,36617,40779,40782,29229,31631,35533,37658,20295,20302,20786,21632,22992,24213,25269,26485,26990,27159,27822,28186,29401,29482,30141,31672,32053,33511,33785,33879,34295,35419,36015,36487,36889,37048,38606,40799,21219,21514,23265,23490,25688,25973,28404,29380,63995,30340,31309,31515,31821,32318,32735,33659,35627,36042,36196,36321,36447,36842,36857,36969,37841,20291,20346,20659,20840,20856,21069,21098,22625,22652,22880,23560,23637,24283,24731,25136,26643,27583,27656,28593,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,29006,29728,30000,30008,30033,30322,31564,31627,31661,31686,32399,35438,36670,36681,37439,37523,37666,37931,38651,39002,39019,39198,20999,25130,25240,27993,30308,31434,31680,32118,21344,23742,24215,28472,28857,31896,38673,39822,40670,25509,25722,34678,19969,20117,20141,20572,20597,21576,22979,23450,24128,24237,24311,24449,24773,25402,25919,25972,26060,26230,26232,26622,26984,27273,27491,27712,28096,28136,28191,28254,28702,28833,29582,29693,30010,30555,30855,31118,31243,31357,31934,32142,33351,35330,35562,35998,37165,37194,37336,37478,37580,37664,38662,38742,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,38748,38914,40718,21046,21137,21884,22564,24093,24351,24716,25552,26799,28639,31085,31532,33229,34234,35069,35576,36420,37261,38500,38555,38717,38988,40778,20430,20806,20939,21161,22066,24340,24427,25514,25805,26089,26177,26362,26361,26397,26781,26839,27133,28437,28526,29031,29157,29226,29866,30522,31062,31066,31199,31264,31381,31895,31967,32068,32368,32903,34299,34468,35412,35519,36249,36481,36896,36973,37347,38459,38613,40165,26063,31751,36275,37827,23384,23562,21330,25305,29469,20519,23447,24478,24752,24939,26837,28121,29742,31278,32066,32156,32305,33131,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,36394,36405,37758,37912,20304,22352,24038,24231,25387,32618,20027,20303,20367,20570,23005,32964,21610,21608,22014,22863,23449,24030,24282,26205,26417,26609,26666,27880,27954,28234,28557,28855,29664,30087,31820,32002,32044,32162,33311,34523,35387,35461,36208,36490,36659,36913,37198,37202,37956,39376,31481,31909,20426,20737,20934,22472,23535,23803,26201,27197,27994,28310,28652,28940,30063,31459,34850,36897,36981,38603,39423,33537,20013,20210,34886,37325,21373,27355,26987,27713,33914,22686,24974,26366,25327,28893,29969,30151,32338,33976,35657,36104,20043,21482,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,21675,22320,22336,24535,25345,25351,25711,25903,26088,26234,26525,26547,27490,27744,27802,28460,30693,30757,31049,31063,32025,32930,33026,33267,33437,33463,34584,35468,63996,36100,36286,36978,30452,31257,31287,32340,32887,21767,21972,22645,25391,25634,26185,26187,26733,27035,27524,27941,28337,29645,29800,29857,30043,30137,30433,30494,30603,31206,32265,32285,33275,34095,34967,35386,36049,36587,36784,36914,37805,38499,38515,38663,20356,21489,23018,23241,24089,26702,29894,30142,31209,31378,33187,34541,36074,36300,36845,26015,26389,63997,22519,28503,32221,36655,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,37878,38598,24501,25074,28548,19988,20376,20511,21449,21983,23919,24046,27425,27492,30923,31642,63998,36425,36554,36974,25417,25662,30528,31364,37679,38015,40810,25776,28591,29158,29864,29914,31428,31762,32386,31922,32408,35738,36106,38013,39184,39244,21049,23519,25830,26413,32046,20717,21443,22649,24920,24921,25082,26028,31449,35730,35734,20489,20513,21109,21809,23100,24288,24432,24884,25950,26124,26166,26274,27085,28356,28466,29462,30241,31379,33081,33369,33750,33980,20661,22512,23488,23528,24425,25505,30758,32181,33756,34081,37319,37365,20874,26613,31574,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,36012,20932,22971,24765,34389,20508,63999,21076,23610,24957,25114,25299,25842,26021,28364,30240,33034,36448,38495,38587,20191,21315,21912,22825,24029,25797,27849,28154,29588,31359,33307,34214,36068,36368,36983,37351,38369,38433,38854,20984,21746,21894,24505,25764,28552,32180,36639,36685,37941,20681,23574,27838,28155,29979,30651,31805,31844,35449,35522,22558,22974,24086,25463,29266,30090,30571,35548,36028,36626,24307,26228,28152,32893,33729,35531,38737,39894,64000,21059,26367,28053,28399,32224,35558,36910,36958,39636,21021,21119,21736,24980,25220,25307,26786,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,26898,26970,27189,28818,28966,30813,30977,30990,31186,31245,32918,33400,33493,33609,34121,35970,36229,37218,37259,37294,20419,22225,29165,30679,34560,35320,23544,24534,26449,37032,21474,22618,23541,24740,24961,25696,32317,32880,34085,37507,25774,20652,23828,26368,22684,25277,25512,26894,27000,27166,28267,30394,31179,33467,33833,35535,36264,36861,37138,37195,37276,37648,37656,37786,38619,39478,39949,19985,30044,31069,31482,31569,31689,32302,33988,36441,36468,36600,36880,26149,26943,29763,20986,26414,40668,20805,24544,27798,34802,34909,34935,24756,33205,33795,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,36101,21462,21561,22068,23094,23601,28810,32736,32858,33030,33261,36259,37257,39519,40434,20596,20164,21408,24827,28204,23652,20360,20516,21988,23769,24159,24677,26772,27835,28100,29118,30164,30196,30305,31258,31305,32199,32251,32622,33268,34473,36636,38601,39347,40786,21063,21189,39149,35242,19971,26578,28422,20405,23522,26517,27784,28024,29723,30759,37341,37756,34756,31204,31281,24555,20182,21668,21822,22702,22949,24816,25171,25302,26422,26965,33333,38464,39345,39389,20524,21331,21828,22396,64001,25176,64002,25826,26219,26589,28609,28655,29730,29752,35351,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,37944,21585,22022,22374,24392,24986,27470,28760,28845,32187,35477,22890,33067,25506,30472,32829,36010,22612,25645,27067,23445,24081,28271,64003,34153,20812,21488,22826,24608,24907,27526,27760,27888,31518,32974,33492,36294,37040,39089,64004,25799,28580,25745,25860,20814,21520,22303,35342,24927,26742,64005,30171,31570,32113,36890,22534,27084,33151,35114,36864,38969,20600,22871,22956,25237,36879,39722,24925,29305,38358,22369,23110,24052,25226,25773,25850,26487,27874,27966,29228,29750,30772,32631,33453,36315,38935,21028,22338,26495,29256,29923,36009,36774,37393,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,38442,20843,21485,25420,20329,21764,24726,25943,27803,28031,29260,29437,31255,35207,35997,24429,28558,28921,33192,24846,20415,20559,25153,29255,31687,32232,32745,36941,38829,39449,36022,22378,24179,26544,33805,35413,21536,23318,24163,24290,24330,25987,32954,34109,38281,38491,20296,21253,21261,21263,21638,21754,22275,24067,24598,25243,25265,25429,64006,27873,28006,30129,30770,32990,33071,33502,33889,33970,34957,35090,36875,37610,39165,39825,24133,26292,26333,28689,29190,64007,20469,21117,24426,24915,26451,27161,28418,29922,31080,34920,35961,39111,39108,39491,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,21697,31263,26963,35575,35914,39080,39342,24444,25259,30130,30382,34987,36991,38466,21305,24380,24517,27852,29644,30050,30091,31558,33534,39325,20047,36924,19979,20309,21414,22799,24264,26160,27827,29781,33655,34662,36032,36944,38686,39957,22737,23416,34384,35604,40372,23506,24680,24717,26097,27735,28450,28579,28698,32597,32752,38289,38290,38480,38867,21106,36676,20989,21547,21688,21859,21898,27323,28085,32216,33382,37532,38519,40569,21512,21704,30418,34532,38308,38356,38492,20130,20233,23022,23270,24055,24658,25239,26477,26689,27782,28207,32568,32923,33322,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,64008,64009,38917,20133,20565,21683,22419,22874,23401,23475,25032,26999,28023,28707,34809,35299,35442,35559,36994,39405,39608,21182,26680,20502,24184,26447,33607,34892,20139,21521,22190,29670,37141,38911,39177,39255,39321,22099,22687,34395,35377,25010,27382,29563,36562,27463,38570,39511,22869,29184,36203,38761,20436,23796,24358,25080,26203,27883,28843,29572,29625,29694,30505,30541,32067,32098,32291,33335,34898,64010,36066,37449,39023,23377,31348,34880,38913,23244,20448,21332,22846,23805,25406,28025,29433,33029,33031,33698,37583,38960,20136,20804,21009,22411,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,24418,27842,28366,28677,28752,28847,29074,29673,29801,33610,34722,34913,36872,37026,37795,39336,20846,24407,24800,24935,26291,34137,36426,37295,38795,20046,20114,21628,22741,22778,22909,23733,24359,25142,25160,26122,26215,27627,28009,28111,28246,28408,28564,28640,28649,28765,29392,29733,29786,29920,30355,31068,31946,32286,32993,33446,33899,33983,34382,34399,34676,35703,35946,37804,38912,39013,24785,25110,37239,23130,26127,28151,28222,29759,39746,24573,24794,31503,21700,24344,27742,27859,27946,28888,32005,34425,35340,40251,21270,21644,23301,27194,28779,30069,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,31117,31166,33457,33775,35441,35649,36008,38772,64011,25844,25899,30906,30907,31339,20024,21914,22864,23462,24187,24739,25563,27489,26213,26707,28185,29029,29872,32008,36996,39529,39973,27963,28369,29502,35905,38346,20976,24140,24488,24653,24822,24880,24908,26179,26180,27045,27841,28255,28361,28514,29004,29852,30343,31681,31783,33618,34647,36945,38541,40643,21295,22238,24315,24458,24674,24724,25079,26214,26371,27292,28142,28590,28784,29546,32362,33214,33588,34516,35496,36036,21123,29554,23446,27243,37892,21742,22150,23389,25928,25989,26313,26783,28045,28102,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,29243,32948,37237,39501,20399,20505,21402,21518,21564,21897,21957,24127,24460,26429,29030,29661,36869,21211,21235,22628,22734,28932,29071,29179,34224,35347,26248,34216,21927,26244,29002,33841,21321,21913,27585,24409,24509,25582,26249,28999,35569,36637,40638,20241,25658,28875,30054,34407,24676,35662,40440,20807,20982,21256,27958,33016,40657,26133,27427,28824,30165,21507,23673,32007,35350,27424,27453,27462,21560,24688,27965,32725,33288,20694,20958,21916,22123,22221,23020,23305,24076,24985,24984,25137,26206,26342,29081,29113,29114,29351,31143,31232,32690,35440,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null], + "gb18030":[19970,19972,19973,19974,19983,19986,19991,19999,20000,20001,20003,20006,20009,20014,20015,20017,20019,20021,20023,20028,20032,20033,20034,20036,20038,20042,20049,20053,20055,20058,20059,20066,20067,20068,20069,20071,20072,20074,20075,20076,20077,20078,20079,20082,20084,20085,20086,20087,20088,20089,20090,20091,20092,20093,20095,20096,20097,20098,20099,20100,20101,20103,20106,20112,20118,20119,20121,20124,20125,20126,20131,20138,20143,20144,20145,20148,20150,20151,20152,20153,20156,20157,20158,20168,20172,20175,20176,20178,20186,20187,20188,20192,20194,20198,20199,20201,20205,20206,20207,20209,20212,20216,20217,20218,20220,20222,20224,20226,20227,20228,20229,20230,20231,20232,20235,20236,20242,20243,20244,20245,20246,20252,20253,20257,20259,20264,20265,20268,20269,20270,20273,20275,20277,20279,20281,20283,20286,20287,20288,20289,20290,20292,20293,20295,20296,20297,20298,20299,20300,20306,20308,20310,20321,20322,20326,20328,20330,20331,20333,20334,20337,20338,20341,20343,20344,20345,20346,20349,20352,20353,20354,20357,20358,20359,20362,20364,20366,20368,20370,20371,20373,20374,20376,20377,20378,20380,20382,20383,20385,20386,20388,20395,20397,20400,20401,20402,20403,20404,20406,20407,20408,20409,20410,20411,20412,20413,20414,20416,20417,20418,20422,20423,20424,20425,20427,20428,20429,20434,20435,20436,20437,20438,20441,20443,20448,20450,20452,20453,20455,20459,20460,20464,20466,20468,20469,20470,20471,20473,20475,20476,20477,20479,20480,20481,20482,20483,20484,20485,20486,20487,20488,20489,20490,20491,20494,20496,20497,20499,20501,20502,20503,20507,20509,20510,20512,20514,20515,20516,20519,20523,20527,20528,20529,20530,20531,20532,20533,20534,20535,20536,20537,20539,20541,20543,20544,20545,20546,20548,20549,20550,20553,20554,20555,20557,20560,20561,20562,20563,20564,20566,20567,20568,20569,20571,20573,20574,20575,20576,20577,20578,20579,20580,20582,20583,20584,20585,20586,20587,20589,20590,20591,20592,20593,20594,20595,20596,20597,20600,20601,20602,20604,20605,20609,20610,20611,20612,20614,20615,20617,20618,20619,20620,20622,20623,20624,20625,20626,20627,20628,20629,20630,20631,20632,20633,20634,20635,20636,20637,20638,20639,20640,20641,20642,20644,20646,20650,20651,20653,20654,20655,20656,20657,20659,20660,20661,20662,20663,20664,20665,20668,20669,20670,20671,20672,20673,20674,20675,20676,20677,20678,20679,20680,20681,20682,20683,20684,20685,20686,20688,20689,20690,20691,20692,20693,20695,20696,20697,20699,20700,20701,20702,20703,20704,20705,20706,20707,20708,20709,20712,20713,20714,20715,20719,20720,20721,20722,20724,20726,20727,20728,20729,20730,20732,20733,20734,20735,20736,20737,20738,20739,20740,20741,20744,20745,20746,20748,20749,20750,20751,20752,20753,20755,20756,20757,20758,20759,20760,20761,20762,20763,20764,20765,20766,20767,20768,20770,20771,20772,20773,20774,20775,20776,20777,20778,20779,20780,20781,20782,20783,20784,20785,20786,20787,20788,20789,20790,20791,20792,20793,20794,20795,20796,20797,20798,20802,20807,20810,20812,20814,20815,20816,20818,20819,20823,20824,20825,20827,20829,20830,20831,20832,20833,20835,20836,20838,20839,20841,20842,20847,20850,20858,20862,20863,20867,20868,20870,20871,20874,20875,20878,20879,20880,20881,20883,20884,20888,20890,20893,20894,20895,20897,20899,20902,20903,20904,20905,20906,20909,20910,20916,20920,20921,20922,20926,20927,20929,20930,20931,20933,20936,20938,20941,20942,20944,20946,20947,20948,20949,20950,20951,20952,20953,20954,20956,20958,20959,20962,20963,20965,20966,20967,20968,20969,20970,20972,20974,20977,20978,20980,20983,20990,20996,20997,21001,21003,21004,21007,21008,21011,21012,21013,21020,21022,21023,21025,21026,21027,21029,21030,21031,21034,21036,21039,21041,21042,21044,21045,21052,21054,21060,21061,21062,21063,21064,21065,21067,21070,21071,21074,21075,21077,21079,21080,21081,21082,21083,21085,21087,21088,21090,21091,21092,21094,21096,21099,21100,21101,21102,21104,21105,21107,21108,21109,21110,21111,21112,21113,21114,21115,21116,21118,21120,21123,21124,21125,21126,21127,21129,21130,21131,21132,21133,21134,21135,21137,21138,21140,21141,21142,21143,21144,21145,21146,21148,21156,21157,21158,21159,21166,21167,21168,21172,21173,21174,21175,21176,21177,21178,21179,21180,21181,21184,21185,21186,21188,21189,21190,21192,21194,21196,21197,21198,21199,21201,21203,21204,21205,21207,21209,21210,21211,21212,21213,21214,21216,21217,21218,21219,21221,21222,21223,21224,21225,21226,21227,21228,21229,21230,21231,21233,21234,21235,21236,21237,21238,21239,21240,21243,21244,21245,21249,21250,21251,21252,21255,21257,21258,21259,21260,21262,21265,21266,21267,21268,21272,21275,21276,21278,21279,21282,21284,21285,21287,21288,21289,21291,21292,21293,21295,21296,21297,21298,21299,21300,21301,21302,21303,21304,21308,21309,21312,21314,21316,21318,21323,21324,21325,21328,21332,21336,21337,21339,21341,21349,21352,21354,21356,21357,21362,21366,21369,21371,21372,21373,21374,21376,21377,21379,21383,21384,21386,21390,21391,21392,21393,21394,21395,21396,21398,21399,21401,21403,21404,21406,21408,21409,21412,21415,21418,21419,21420,21421,21423,21424,21425,21426,21427,21428,21429,21431,21432,21433,21434,21436,21437,21438,21440,21443,21444,21445,21446,21447,21454,21455,21456,21458,21459,21461,21466,21468,21469,21470,21473,21474,21479,21492,21498,21502,21503,21504,21506,21509,21511,21515,21524,21528,21529,21530,21532,21538,21540,21541,21546,21552,21555,21558,21559,21562,21565,21567,21569,21570,21572,21573,21575,21577,21580,21581,21582,21583,21585,21594,21597,21598,21599,21600,21601,21603,21605,21607,21609,21610,21611,21612,21613,21614,21615,21616,21620,21625,21626,21630,21631,21633,21635,21637,21639,21640,21641,21642,21645,21649,21651,21655,21656,21660,21662,21663,21664,21665,21666,21669,21678,21680,21682,21685,21686,21687,21689,21690,21692,21694,21699,21701,21706,21707,21718,21720,21723,21728,21729,21730,21731,21732,21739,21740,21743,21744,21745,21748,21749,21750,21751,21752,21753,21755,21758,21760,21762,21763,21764,21765,21768,21770,21771,21772,21773,21774,21778,21779,21781,21782,21783,21784,21785,21786,21788,21789,21790,21791,21793,21797,21798,21800,21801,21803,21805,21810,21812,21813,21814,21816,21817,21818,21819,21821,21824,21826,21829,21831,21832,21835,21836,21837,21838,21839,21841,21842,21843,21844,21847,21848,21849,21850,21851,21853,21854,21855,21856,21858,21859,21864,21865,21867,21871,21872,21873,21874,21875,21876,21881,21882,21885,21887,21893,21894,21900,21901,21902,21904,21906,21907,21909,21910,21911,21914,21915,21918,21920,21921,21922,21923,21924,21925,21926,21928,21929,21930,21931,21932,21933,21934,21935,21936,21938,21940,21942,21944,21946,21948,21951,21952,21953,21954,21955,21958,21959,21960,21962,21963,21966,21967,21968,21973,21975,21976,21977,21978,21979,21982,21984,21986,21991,21993,21997,21998,22000,22001,22004,22006,22008,22009,22010,22011,22012,22015,22018,22019,22020,22021,22022,22023,22026,22027,22029,22032,22033,22034,22035,22036,22037,22038,22039,22041,22042,22044,22045,22048,22049,22050,22053,22054,22056,22057,22058,22059,22062,22063,22064,22067,22069,22071,22072,22074,22076,22077,22078,22080,22081,22082,22083,22084,22085,22086,22087,22088,22089,22090,22091,22095,22096,22097,22098,22099,22101,22102,22106,22107,22109,22110,22111,22112,22113,22115,22117,22118,22119,22125,22126,22127,22128,22130,22131,22132,22133,22135,22136,22137,22138,22141,22142,22143,22144,22145,22146,22147,22148,22151,22152,22153,22154,22155,22156,22157,22160,22161,22162,22164,22165,22166,22167,22168,22169,22170,22171,22172,22173,22174,22175,22176,22177,22178,22180,22181,22182,22183,22184,22185,22186,22187,22188,22189,22190,22192,22193,22194,22195,22196,22197,22198,22200,22201,22202,22203,22205,22206,22207,22208,22209,22210,22211,22212,22213,22214,22215,22216,22217,22219,22220,22221,22222,22223,22224,22225,22226,22227,22229,22230,22232,22233,22236,22243,22245,22246,22247,22248,22249,22250,22252,22254,22255,22258,22259,22262,22263,22264,22267,22268,22272,22273,22274,22277,22279,22283,22284,22285,22286,22287,22288,22289,22290,22291,22292,22293,22294,22295,22296,22297,22298,22299,22301,22302,22304,22305,22306,22308,22309,22310,22311,22315,22321,22322,22324,22325,22326,22327,22328,22332,22333,22335,22337,22339,22340,22341,22342,22344,22345,22347,22354,22355,22356,22357,22358,22360,22361,22370,22371,22373,22375,22380,22382,22384,22385,22386,22388,22389,22392,22393,22394,22397,22398,22399,22400,22401,22407,22408,22409,22410,22413,22414,22415,22416,22417,22420,22421,22422,22423,22424,22425,22426,22428,22429,22430,22431,22437,22440,22442,22444,22447,22448,22449,22451,22453,22454,22455,22457,22458,22459,22460,22461,22462,22463,22464,22465,22468,22469,22470,22471,22472,22473,22474,22476,22477,22480,22481,22483,22486,22487,22491,22492,22494,22497,22498,22499,22501,22502,22503,22504,22505,22506,22507,22508,22510,22512,22513,22514,22515,22517,22518,22519,22523,22524,22526,22527,22529,22531,22532,22533,22536,22537,22538,22540,22542,22543,22544,22546,22547,22548,22550,22551,22552,22554,22555,22556,22557,22559,22562,22563,22565,22566,22567,22568,22569,22571,22572,22573,22574,22575,22577,22578,22579,22580,22582,22583,22584,22585,22586,22587,22588,22589,22590,22591,22592,22593,22594,22595,22597,22598,22599,22600,22601,22602,22603,22606,22607,22608,22610,22611,22613,22614,22615,22617,22618,22619,22620,22621,22623,22624,22625,22626,22627,22628,22630,22631,22632,22633,22634,22637,22638,22639,22640,22641,22642,22643,22644,22645,22646,22647,22648,22649,22650,22651,22652,22653,22655,22658,22660,22662,22663,22664,22666,22667,22668,22669,22670,22671,22672,22673,22676,22677,22678,22679,22680,22683,22684,22685,22688,22689,22690,22691,22692,22693,22694,22695,22698,22699,22700,22701,22702,22703,22704,22705,22706,22707,22708,22709,22710,22711,22712,22713,22714,22715,22717,22718,22719,22720,22722,22723,22724,22726,22727,22728,22729,22730,22731,22732,22733,22734,22735,22736,22738,22739,22740,22742,22743,22744,22745,22746,22747,22748,22749,22750,22751,22752,22753,22754,22755,22757,22758,22759,22760,22761,22762,22765,22767,22769,22770,22772,22773,22775,22776,22778,22779,22780,22781,22782,22783,22784,22785,22787,22789,22790,22792,22793,22794,22795,22796,22798,22800,22801,22802,22803,22807,22808,22811,22813,22814,22816,22817,22818,22819,22822,22824,22828,22832,22834,22835,22837,22838,22843,22845,22846,22847,22848,22851,22853,22854,22858,22860,22861,22864,22866,22867,22873,22875,22876,22877,22878,22879,22881,22883,22884,22886,22887,22888,22889,22890,22891,22892,22893,22894,22895,22896,22897,22898,22901,22903,22906,22907,22908,22910,22911,22912,22917,22921,22923,22924,22926,22927,22928,22929,22932,22933,22936,22938,22939,22940,22941,22943,22944,22945,22946,22950,22951,22956,22957,22960,22961,22963,22964,22965,22966,22967,22968,22970,22972,22973,22975,22976,22977,22978,22979,22980,22981,22983,22984,22985,22988,22989,22990,22991,22997,22998,23001,23003,23006,23007,23008,23009,23010,23012,23014,23015,23017,23018,23019,23021,23022,23023,23024,23025,23026,23027,23028,23029,23030,23031,23032,23034,23036,23037,23038,23040,23042,23050,23051,23053,23054,23055,23056,23058,23060,23061,23062,23063,23065,23066,23067,23069,23070,23073,23074,23076,23078,23079,23080,23082,23083,23084,23085,23086,23087,23088,23091,23093,23095,23096,23097,23098,23099,23101,23102,23103,23105,23106,23107,23108,23109,23111,23112,23115,23116,23117,23118,23119,23120,23121,23122,23123,23124,23126,23127,23128,23129,23131,23132,23133,23134,23135,23136,23137,23139,23140,23141,23142,23144,23145,23147,23148,23149,23150,23151,23152,23153,23154,23155,23160,23161,23163,23164,23165,23166,23168,23169,23170,23171,23172,23173,23174,23175,23176,23177,23178,23179,23180,23181,23182,23183,23184,23185,23187,23188,23189,23190,23191,23192,23193,23196,23197,23198,23199,23200,23201,23202,23203,23204,23205,23206,23207,23208,23209,23211,23212,23213,23214,23215,23216,23217,23220,23222,23223,23225,23226,23227,23228,23229,23231,23232,23235,23236,23237,23238,23239,23240,23242,23243,23245,23246,23247,23248,23249,23251,23253,23255,23257,23258,23259,23261,23262,23263,23266,23268,23269,23271,23272,23274,23276,23277,23278,23279,23280,23282,23283,23284,23285,23286,23287,23288,23289,23290,23291,23292,23293,23294,23295,23296,23297,23298,23299,23300,23301,23302,23303,23304,23306,23307,23308,23309,23310,23311,23312,23313,23314,23315,23316,23317,23320,23321,23322,23323,23324,23325,23326,23327,23328,23329,23330,23331,23332,23333,23334,23335,23336,23337,23338,23339,23340,23341,23342,23343,23344,23345,23347,23349,23350,23352,23353,23354,23355,23356,23357,23358,23359,23361,23362,23363,23364,23365,23366,23367,23368,23369,23370,23371,23372,23373,23374,23375,23378,23382,23390,23392,23393,23399,23400,23403,23405,23406,23407,23410,23412,23414,23415,23416,23417,23419,23420,23422,23423,23426,23430,23434,23437,23438,23440,23441,23442,23444,23446,23455,23463,23464,23465,23468,23469,23470,23471,23473,23474,23479,23482,23483,23484,23488,23489,23491,23496,23497,23498,23499,23501,23502,23503,23505,23508,23509,23510,23511,23512,23513,23514,23515,23516,23520,23522,23523,23526,23527,23529,23530,23531,23532,23533,23535,23537,23538,23539,23540,23541,23542,23543,23549,23550,23552,23554,23555,23557,23559,23560,23563,23564,23565,23566,23568,23570,23571,23575,23577,23579,23582,23583,23584,23585,23587,23590,23592,23593,23594,23595,23597,23598,23599,23600,23602,23603,23605,23606,23607,23619,23620,23622,23623,23628,23629,23634,23635,23636,23638,23639,23640,23642,23643,23644,23645,23647,23650,23652,23655,23656,23657,23658,23659,23660,23661,23664,23666,23667,23668,23669,23670,23671,23672,23675,23676,23677,23678,23680,23683,23684,23685,23686,23687,23689,23690,23691,23694,23695,23698,23699,23701,23709,23710,23711,23712,23713,23716,23717,23718,23719,23720,23722,23726,23727,23728,23730,23732,23734,23737,23738,23739,23740,23742,23744,23746,23747,23749,23750,23751,23752,23753,23754,23756,23757,23758,23759,23760,23761,23763,23764,23765,23766,23767,23768,23770,23771,23772,23773,23774,23775,23776,23778,23779,23783,23785,23787,23788,23790,23791,23793,23794,23795,23796,23797,23798,23799,23800,23801,23802,23804,23805,23806,23807,23808,23809,23812,23813,23816,23817,23818,23819,23820,23821,23823,23824,23825,23826,23827,23829,23831,23832,23833,23834,23836,23837,23839,23840,23841,23842,23843,23845,23848,23850,23851,23852,23855,23856,23857,23858,23859,23861,23862,23863,23864,23865,23866,23867,23868,23871,23872,23873,23874,23875,23876,23877,23878,23880,23881,23885,23886,23887,23888,23889,23890,23891,23892,23893,23894,23895,23897,23898,23900,23902,23903,23904,23905,23906,23907,23908,23909,23910,23911,23912,23914,23917,23918,23920,23921,23922,23923,23925,23926,23927,23928,23929,23930,23931,23932,23933,23934,23935,23936,23937,23939,23940,23941,23942,23943,23944,23945,23946,23947,23948,23949,23950,23951,23952,23953,23954,23955,23956,23957,23958,23959,23960,23962,23963,23964,23966,23967,23968,23969,23970,23971,23972,23973,23974,23975,23976,23977,23978,23979,23980,23981,23982,23983,23984,23985,23986,23987,23988,23989,23990,23992,23993,23994,23995,23996,23997,23998,23999,24000,24001,24002,24003,24004,24006,24007,24008,24009,24010,24011,24012,24014,24015,24016,24017,24018,24019,24020,24021,24022,24023,24024,24025,24026,24028,24031,24032,24035,24036,24042,24044,24045,24048,24053,24054,24056,24057,24058,24059,24060,24063,24064,24068,24071,24073,24074,24075,24077,24078,24082,24083,24087,24094,24095,24096,24097,24098,24099,24100,24101,24104,24105,24106,24107,24108,24111,24112,24114,24115,24116,24117,24118,24121,24122,24126,24127,24128,24129,24131,24134,24135,24136,24137,24138,24139,24141,24142,24143,24144,24145,24146,24147,24150,24151,24152,24153,24154,24156,24157,24159,24160,24163,24164,24165,24166,24167,24168,24169,24170,24171,24172,24173,24174,24175,24176,24177,24181,24183,24185,24190,24193,24194,24195,24197,24200,24201,24204,24205,24206,24210,24216,24219,24221,24225,24226,24227,24228,24232,24233,24234,24235,24236,24238,24239,24240,24241,24242,24244,24250,24251,24252,24253,24255,24256,24257,24258,24259,24260,24261,24262,24263,24264,24267,24268,24269,24270,24271,24272,24276,24277,24279,24280,24281,24282,24284,24285,24286,24287,24288,24289,24290,24291,24292,24293,24294,24295,24297,24299,24300,24301,24302,24303,24304,24305,24306,24307,24309,24312,24313,24315,24316,24317,24325,24326,24327,24329,24332,24333,24334,24336,24338,24340,24342,24345,24346,24348,24349,24350,24353,24354,24355,24356,24360,24363,24364,24366,24368,24370,24371,24372,24373,24374,24375,24376,24379,24381,24382,24383,24385,24386,24387,24388,24389,24390,24391,24392,24393,24394,24395,24396,24397,24398,24399,24401,24404,24409,24410,24411,24412,24414,24415,24416,24419,24421,24423,24424,24427,24430,24431,24434,24436,24437,24438,24440,24442,24445,24446,24447,24451,24454,24461,24462,24463,24465,24467,24468,24470,24474,24475,24477,24478,24479,24480,24482,24483,24484,24485,24486,24487,24489,24491,24492,24495,24496,24497,24498,24499,24500,24502,24504,24505,24506,24507,24510,24511,24512,24513,24514,24519,24520,24522,24523,24526,24531,24532,24533,24538,24539,24540,24542,24543,24546,24547,24549,24550,24552,24553,24556,24559,24560,24562,24563,24564,24566,24567,24569,24570,24572,24583,24584,24585,24587,24588,24592,24593,24595,24599,24600,24602,24606,24607,24610,24611,24612,24620,24621,24622,24624,24625,24626,24627,24628,24630,24631,24632,24633,24634,24637,24638,24640,24644,24645,24646,24647,24648,24649,24650,24652,24654,24655,24657,24659,24660,24662,24663,24664,24667,24668,24670,24671,24672,24673,24677,24678,24686,24689,24690,24692,24693,24695,24702,24704,24705,24706,24709,24710,24711,24712,24714,24715,24718,24719,24720,24721,24723,24725,24727,24728,24729,24732,24734,24737,24738,24740,24741,24743,24745,24746,24750,24752,24755,24757,24758,24759,24761,24762,24765,24766,24767,24768,24769,24770,24771,24772,24775,24776,24777,24780,24781,24782,24783,24784,24786,24787,24788,24790,24791,24793,24795,24798,24801,24802,24803,24804,24805,24810,24817,24818,24821,24823,24824,24827,24828,24829,24830,24831,24834,24835,24836,24837,24839,24842,24843,24844,24848,24849,24850,24851,24852,24854,24855,24856,24857,24859,24860,24861,24862,24865,24866,24869,24872,24873,24874,24876,24877,24878,24879,24880,24881,24882,24883,24884,24885,24886,24887,24888,24889,24890,24891,24892,24893,24894,24896,24897,24898,24899,24900,24901,24902,24903,24905,24907,24909,24911,24912,24914,24915,24916,24918,24919,24920,24921,24922,24923,24924,24926,24927,24928,24929,24931,24932,24933,24934,24937,24938,24939,24940,24941,24942,24943,24945,24946,24947,24948,24950,24952,24953,24954,24955,24956,24957,24958,24959,24960,24961,24962,24963,24964,24965,24966,24967,24968,24969,24970,24972,24973,24975,24976,24977,24978,24979,24981,24982,24983,24984,24985,24986,24987,24988,24990,24991,24992,24993,24994,24995,24996,24997,24998,25002,25003,25005,25006,25007,25008,25009,25010,25011,25012,25013,25014,25016,25017,25018,25019,25020,25021,25023,25024,25025,25027,25028,25029,25030,25031,25033,25036,25037,25038,25039,25040,25043,25045,25046,25047,25048,25049,25050,25051,25052,25053,25054,25055,25056,25057,25058,25059,25060,25061,25063,25064,25065,25066,25067,25068,25069,25070,25071,25072,25073,25074,25075,25076,25078,25079,25080,25081,25082,25083,25084,25085,25086,25088,25089,25090,25091,25092,25093,25095,25097,25107,25108,25113,25116,25117,25118,25120,25123,25126,25127,25128,25129,25131,25133,25135,25136,25137,25138,25141,25142,25144,25145,25146,25147,25148,25154,25156,25157,25158,25162,25167,25168,25173,25174,25175,25177,25178,25180,25181,25182,25183,25184,25185,25186,25188,25189,25192,25201,25202,25204,25205,25207,25208,25210,25211,25213,25217,25218,25219,25221,25222,25223,25224,25227,25228,25229,25230,25231,25232,25236,25241,25244,25245,25246,25251,25254,25255,25257,25258,25261,25262,25263,25264,25266,25267,25268,25270,25271,25272,25274,25278,25280,25281,25283,25291,25295,25297,25301,25309,25310,25312,25313,25316,25322,25323,25328,25330,25333,25336,25337,25338,25339,25344,25347,25348,25349,25350,25354,25355,25356,25357,25359,25360,25362,25363,25364,25365,25367,25368,25369,25372,25382,25383,25385,25388,25389,25390,25392,25393,25395,25396,25397,25398,25399,25400,25403,25404,25406,25407,25408,25409,25412,25415,25416,25418,25425,25426,25427,25428,25430,25431,25432,25433,25434,25435,25436,25437,25440,25444,25445,25446,25448,25450,25451,25452,25455,25456,25458,25459,25460,25461,25464,25465,25468,25469,25470,25471,25473,25475,25476,25477,25478,25483,25485,25489,25491,25492,25493,25495,25497,25498,25499,25500,25501,25502,25503,25505,25508,25510,25515,25519,25521,25522,25525,25526,25529,25531,25533,25535,25536,25537,25538,25539,25541,25543,25544,25546,25547,25548,25553,25555,25556,25557,25559,25560,25561,25562,25563,25564,25565,25567,25570,25572,25573,25574,25575,25576,25579,25580,25582,25583,25584,25585,25587,25589,25591,25593,25594,25595,25596,25598,25603,25604,25606,25607,25608,25609,25610,25613,25614,25617,25618,25621,25622,25623,25624,25625,25626,25629,25631,25634,25635,25636,25637,25639,25640,25641,25643,25646,25647,25648,25649,25650,25651,25653,25654,25655,25656,25657,25659,25660,25662,25664,25666,25667,25673,25675,25676,25677,25678,25679,25680,25681,25683,25685,25686,25687,25689,25690,25691,25692,25693,25695,25696,25697,25698,25699,25700,25701,25702,25704,25706,25707,25708,25710,25711,25712,25713,25714,25715,25716,25717,25718,25719,25723,25724,25725,25726,25727,25728,25729,25731,25734,25736,25737,25738,25739,25740,25741,25742,25743,25744,25747,25748,25751,25752,25754,25755,25756,25757,25759,25760,25761,25762,25763,25765,25766,25767,25768,25770,25771,25775,25777,25778,25779,25780,25782,25785,25787,25789,25790,25791,25793,25795,25796,25798,25799,25800,25801,25802,25803,25804,25807,25809,25811,25812,25813,25814,25817,25818,25819,25820,25821,25823,25824,25825,25827,25829,25831,25832,25833,25834,25835,25836,25837,25838,25839,25840,25841,25842,25843,25844,25845,25846,25847,25848,25849,25850,25851,25852,25853,25854,25855,25857,25858,25859,25860,25861,25862,25863,25864,25866,25867,25868,25869,25870,25871,25872,25873,25875,25876,25877,25878,25879,25881,25882,25883,25884,25885,25886,25887,25888,25889,25890,25891,25892,25894,25895,25896,25897,25898,25900,25901,25904,25905,25906,25907,25911,25914,25916,25917,25920,25921,25922,25923,25924,25926,25927,25930,25931,25933,25934,25936,25938,25939,25940,25943,25944,25946,25948,25951,25952,25953,25956,25957,25959,25960,25961,25962,25965,25966,25967,25969,25971,25973,25974,25976,25977,25978,25979,25980,25981,25982,25983,25984,25985,25986,25987,25988,25989,25990,25992,25993,25994,25997,25998,25999,26002,26004,26005,26006,26008,26010,26013,26014,26016,26018,26019,26022,26024,26026,26028,26030,26033,26034,26035,26036,26037,26038,26039,26040,26042,26043,26046,26047,26048,26050,26055,26056,26057,26058,26061,26064,26065,26067,26068,26069,26072,26073,26074,26075,26076,26077,26078,26079,26081,26083,26084,26090,26091,26098,26099,26100,26101,26104,26105,26107,26108,26109,26110,26111,26113,26116,26117,26119,26120,26121,26123,26125,26128,26129,26130,26134,26135,26136,26138,26139,26140,26142,26145,26146,26147,26148,26150,26153,26154,26155,26156,26158,26160,26162,26163,26167,26168,26169,26170,26171,26173,26175,26176,26178,26180,26181,26182,26183,26184,26185,26186,26189,26190,26192,26193,26200,26201,26203,26204,26205,26206,26208,26210,26211,26213,26215,26217,26218,26219,26220,26221,26225,26226,26227,26229,26232,26233,26235,26236,26237,26239,26240,26241,26243,26245,26246,26248,26249,26250,26251,26253,26254,26255,26256,26258,26259,26260,26261,26264,26265,26266,26267,26268,26270,26271,26272,26273,26274,26275,26276,26277,26278,26281,26282,26283,26284,26285,26287,26288,26289,26290,26291,26293,26294,26295,26296,26298,26299,26300,26301,26303,26304,26305,26306,26307,26308,26309,26310,26311,26312,26313,26314,26315,26316,26317,26318,26319,26320,26321,26322,26323,26324,26325,26326,26327,26328,26330,26334,26335,26336,26337,26338,26339,26340,26341,26343,26344,26346,26347,26348,26349,26350,26351,26353,26357,26358,26360,26362,26363,26365,26369,26370,26371,26372,26373,26374,26375,26380,26382,26383,26385,26386,26387,26390,26392,26393,26394,26396,26398,26400,26401,26402,26403,26404,26405,26407,26409,26414,26416,26418,26419,26422,26423,26424,26425,26427,26428,26430,26431,26433,26436,26437,26439,26442,26443,26445,26450,26452,26453,26455,26456,26457,26458,26459,26461,26466,26467,26468,26470,26471,26475,26476,26478,26481,26484,26486,26488,26489,26490,26491,26493,26496,26498,26499,26501,26502,26504,26506,26508,26509,26510,26511,26513,26514,26515,26516,26518,26521,26523,26527,26528,26529,26532,26534,26537,26540,26542,26545,26546,26548,26553,26554,26555,26556,26557,26558,26559,26560,26562,26565,26566,26567,26568,26569,26570,26571,26572,26573,26574,26581,26582,26583,26587,26591,26593,26595,26596,26598,26599,26600,26602,26603,26605,26606,26610,26613,26614,26615,26616,26617,26618,26619,26620,26622,26625,26626,26627,26628,26630,26637,26640,26642,26644,26645,26648,26649,26650,26651,26652,26654,26655,26656,26658,26659,26660,26661,26662,26663,26664,26667,26668,26669,26670,26671,26672,26673,26676,26677,26678,26682,26683,26687,26695,26699,26701,26703,26706,26710,26711,26712,26713,26714,26715,26716,26717,26718,26719,26730,26732,26733,26734,26735,26736,26737,26738,26739,26741,26744,26745,26746,26747,26748,26749,26750,26751,26752,26754,26756,26759,26760,26761,26762,26763,26764,26765,26766,26768,26769,26770,26772,26773,26774,26776,26777,26778,26779,26780,26781,26782,26783,26784,26785,26787,26788,26789,26793,26794,26795,26796,26798,26801,26802,26804,26806,26807,26808,26809,26810,26811,26812,26813,26814,26815,26817,26819,26820,26821,26822,26823,26824,26826,26828,26830,26831,26832,26833,26835,26836,26838,26839,26841,26843,26844,26845,26846,26847,26849,26850,26852,26853,26854,26855,26856,26857,26858,26859,26860,26861,26863,26866,26867,26868,26870,26871,26872,26875,26877,26878,26879,26880,26882,26883,26884,26886,26887,26888,26889,26890,26892,26895,26897,26899,26900,26901,26902,26903,26904,26905,26906,26907,26908,26909,26910,26913,26914,26915,26917,26918,26919,26920,26921,26922,26923,26924,26926,26927,26929,26930,26931,26933,26934,26935,26936,26938,26939,26940,26942,26944,26945,26947,26948,26949,26950,26951,26952,26953,26954,26955,26956,26957,26958,26959,26960,26961,26962,26963,26965,26966,26968,26969,26971,26972,26975,26977,26978,26980,26981,26983,26984,26985,26986,26988,26989,26991,26992,26994,26995,26996,26997,26998,27002,27003,27005,27006,27007,27009,27011,27013,27018,27019,27020,27022,27023,27024,27025,27026,27027,27030,27031,27033,27034,27037,27038,27039,27040,27041,27042,27043,27044,27045,27046,27049,27050,27052,27054,27055,27056,27058,27059,27061,27062,27064,27065,27066,27068,27069,27070,27071,27072,27074,27075,27076,27077,27078,27079,27080,27081,27083,27085,27087,27089,27090,27091,27093,27094,27095,27096,27097,27098,27100,27101,27102,27105,27106,27107,27108,27109,27110,27111,27112,27113,27114,27115,27116,27118,27119,27120,27121,27123,27124,27125,27126,27127,27128,27129,27130,27131,27132,27134,27136,27137,27138,27139,27140,27141,27142,27143,27144,27145,27147,27148,27149,27150,27151,27152,27153,27154,27155,27156,27157,27158,27161,27162,27163,27164,27165,27166,27168,27170,27171,27172,27173,27174,27175,27177,27179,27180,27181,27182,27184,27186,27187,27188,27190,27191,27192,27193,27194,27195,27196,27199,27200,27201,27202,27203,27205,27206,27208,27209,27210,27211,27212,27213,27214,27215,27217,27218,27219,27220,27221,27222,27223,27226,27228,27229,27230,27231,27232,27234,27235,27236,27238,27239,27240,27241,27242,27243,27244,27245,27246,27247,27248,27250,27251,27252,27253,27254,27255,27256,27258,27259,27261,27262,27263,27265,27266,27267,27269,27270,27271,27272,27273,27274,27275,27276,27277,27279,27282,27283,27284,27285,27286,27288,27289,27290,27291,27292,27293,27294,27295,27297,27298,27299,27300,27301,27302,27303,27304,27306,27309,27310,27311,27312,27313,27314,27315,27316,27317,27318,27319,27320,27321,27322,27323,27324,27325,27326,27327,27328,27329,27330,27331,27332,27333,27334,27335,27336,27337,27338,27339,27340,27341,27342,27343,27344,27345,27346,27347,27348,27349,27350,27351,27352,27353,27354,27355,27356,27357,27358,27359,27360,27361,27362,27363,27364,27365,27366,27367,27368,27369,27370,27371,27372,27373,27374,27375,27376,27377,27378,27379,27380,27381,27382,27383,27384,27385,27386,27387,27388,27389,27390,27391,27392,27393,27394,27395,27396,27397,27398,27399,27400,27401,27402,27403,27404,27405,27406,27407,27408,27409,27410,27411,27412,27413,27414,27415,27416,27417,27418,27419,27420,27421,27422,27423,27429,27430,27432,27433,27434,27435,27436,27437,27438,27439,27440,27441,27443,27444,27445,27446,27448,27451,27452,27453,27455,27456,27457,27458,27460,27461,27464,27466,27467,27469,27470,27471,27472,27473,27474,27475,27476,27477,27478,27479,27480,27482,27483,27484,27485,27486,27487,27488,27489,27496,27497,27499,27500,27501,27502,27503,27504,27505,27506,27507,27508,27509,27510,27511,27512,27514,27517,27518,27519,27520,27525,27528,27532,27534,27535,27536,27537,27540,27541,27543,27544,27545,27548,27549,27550,27551,27552,27554,27555,27556,27557,27558,27559,27560,27561,27563,27564,27565,27566,27567,27568,27569,27570,27574,27576,27577,27578,27579,27580,27581,27582,27584,27587,27588,27590,27591,27592,27593,27594,27596,27598,27600,27601,27608,27610,27612,27613,27614,27615,27616,27618,27619,27620,27621,27622,27623,27624,27625,27628,27629,27630,27632,27633,27634,27636,27638,27639,27640,27642,27643,27644,27646,27647,27648,27649,27650,27651,27652,27656,27657,27658,27659,27660,27662,27666,27671,27676,27677,27678,27680,27683,27685,27691,27692,27693,27697,27699,27702,27703,27705,27706,27707,27708,27710,27711,27715,27716,27717,27720,27723,27724,27725,27726,27727,27729,27730,27731,27734,27736,27737,27738,27746,27747,27749,27750,27751,27755,27756,27757,27758,27759,27761,27763,27765,27767,27768,27770,27771,27772,27775,27776,27780,27783,27786,27787,27789,27790,27793,27794,27797,27798,27799,27800,27802,27804,27805,27806,27808,27810,27816,27820,27823,27824,27828,27829,27830,27831,27834,27840,27841,27842,27843,27846,27847,27848,27851,27853,27854,27855,27857,27858,27864,27865,27866,27868,27869,27871,27876,27878,27879,27881,27884,27885,27890,27892,27897,27903,27904,27906,27907,27909,27910,27912,27913,27914,27917,27919,27920,27921,27923,27924,27925,27926,27928,27932,27933,27935,27936,27937,27938,27939,27940,27942,27944,27945,27948,27949,27951,27952,27956,27958,27959,27960,27962,27967,27968,27970,27972,27977,27980,27984,27989,27990,27991,27992,27995,27997,27999,28001,28002,28004,28005,28007,28008,28011,28012,28013,28016,28017,28018,28019,28021,28022,28025,28026,28027,28029,28030,28031,28032,28033,28035,28036,28038,28039,28042,28043,28045,28047,28048,28050,28054,28055,28056,28057,28058,28060,28066,28069,28076,28077,28080,28081,28083,28084,28086,28087,28089,28090,28091,28092,28093,28094,28097,28098,28099,28104,28105,28106,28109,28110,28111,28112,28114,28115,28116,28117,28119,28122,28123,28124,28127,28130,28131,28133,28135,28136,28137,28138,28141,28143,28144,28146,28148,28149,28150,28152,28154,28157,28158,28159,28160,28161,28162,28163,28164,28166,28167,28168,28169,28171,28175,28178,28179,28181,28184,28185,28187,28188,28190,28191,28194,28198,28199,28200,28202,28204,28206,28208,28209,28211,28213,28214,28215,28217,28219,28220,28221,28222,28223,28224,28225,28226,28229,28230,28231,28232,28233,28234,28235,28236,28239,28240,28241,28242,28245,28247,28249,28250,28252,28253,28254,28256,28257,28258,28259,28260,28261,28262,28263,28264,28265,28266,28268,28269,28271,28272,28273,28274,28275,28276,28277,28278,28279,28280,28281,28282,28283,28284,28285,28288,28289,28290,28292,28295,28296,28298,28299,28300,28301,28302,28305,28306,28307,28308,28309,28310,28311,28313,28314,28315,28317,28318,28320,28321,28323,28324,28326,28328,28329,28331,28332,28333,28334,28336,28339,28341,28344,28345,28348,28350,28351,28352,28355,28356,28357,28358,28360,28361,28362,28364,28365,28366,28368,28370,28374,28376,28377,28379,28380,28381,28387,28391,28394,28395,28396,28397,28398,28399,28400,28401,28402,28403,28405,28406,28407,28408,28410,28411,28412,28413,28414,28415,28416,28417,28419,28420,28421,28423,28424,28426,28427,28428,28429,28430,28432,28433,28434,28438,28439,28440,28441,28442,28443,28444,28445,28446,28447,28449,28450,28451,28453,28454,28455,28456,28460,28462,28464,28466,28468,28469,28471,28472,28473,28474,28475,28476,28477,28479,28480,28481,28482,28483,28484,28485,28488,28489,28490,28492,28494,28495,28496,28497,28498,28499,28500,28501,28502,28503,28505,28506,28507,28509,28511,28512,28513,28515,28516,28517,28519,28520,28521,28522,28523,28524,28527,28528,28529,28531,28533,28534,28535,28537,28539,28541,28542,28543,28544,28545,28546,28547,28549,28550,28551,28554,28555,28559,28560,28561,28562,28563,28564,28565,28566,28567,28568,28569,28570,28571,28573,28574,28575,28576,28578,28579,28580,28581,28582,28584,28585,28586,28587,28588,28589,28590,28591,28592,28593,28594,28596,28597,28599,28600,28602,28603,28604,28605,28606,28607,28609,28611,28612,28613,28614,28615,28616,28618,28619,28620,28621,28622,28623,28624,28627,28628,28629,28630,28631,28632,28633,28634,28635,28636,28637,28639,28642,28643,28644,28645,28646,28647,28648,28649,28650,28651,28652,28653,28656,28657,28658,28659,28660,28661,28662,28663,28664,28665,28666,28667,28668,28669,28670,28671,28672,28673,28674,28675,28676,28677,28678,28679,28680,28681,28682,28683,28684,28685,28686,28687,28688,28690,28691,28692,28693,28694,28695,28696,28697,28700,28701,28702,28703,28704,28705,28706,28708,28709,28710,28711,28712,28713,28714,28715,28716,28717,28718,28719,28720,28721,28722,28723,28724,28726,28727,28728,28730,28731,28732,28733,28734,28735,28736,28737,28738,28739,28740,28741,28742,28743,28744,28745,28746,28747,28749,28750,28752,28753,28754,28755,28756,28757,28758,28759,28760,28761,28762,28763,28764,28765,28767,28768,28769,28770,28771,28772,28773,28774,28775,28776,28777,28778,28782,28785,28786,28787,28788,28791,28793,28794,28795,28797,28801,28802,28803,28804,28806,28807,28808,28811,28812,28813,28815,28816,28817,28819,28823,28824,28826,28827,28830,28831,28832,28833,28834,28835,28836,28837,28838,28839,28840,28841,28842,28848,28850,28852,28853,28854,28858,28862,28863,28868,28869,28870,28871,28873,28875,28876,28877,28878,28879,28880,28881,28882,28883,28884,28885,28886,28887,28890,28892,28893,28894,28896,28897,28898,28899,28901,28906,28910,28912,28913,28914,28915,28916,28917,28918,28920,28922,28923,28924,28926,28927,28928,28929,28930,28931,28932,28933,28934,28935,28936,28939,28940,28941,28942,28943,28945,28946,28948,28951,28955,28956,28957,28958,28959,28960,28961,28962,28963,28964,28965,28967,28968,28969,28970,28971,28972,28973,28974,28978,28979,28980,28981,28983,28984,28985,28986,28987,28988,28989,28990,28991,28992,28993,28994,28995,28996,28998,28999,29000,29001,29003,29005,29007,29008,29009,29010,29011,29012,29013,29014,29015,29016,29017,29018,29019,29021,29023,29024,29025,29026,29027,29029,29033,29034,29035,29036,29037,29039,29040,29041,29044,29045,29046,29047,29049,29051,29052,29054,29055,29056,29057,29058,29059,29061,29062,29063,29064,29065,29067,29068,29069,29070,29072,29073,29074,29075,29077,29078,29079,29082,29083,29084,29085,29086,29089,29090,29091,29092,29093,29094,29095,29097,29098,29099,29101,29102,29103,29104,29105,29106,29108,29110,29111,29112,29114,29115,29116,29117,29118,29119,29120,29121,29122,29124,29125,29126,29127,29128,29129,29130,29131,29132,29133,29135,29136,29137,29138,29139,29142,29143,29144,29145,29146,29147,29148,29149,29150,29151,29153,29154,29155,29156,29158,29160,29161,29162,29163,29164,29165,29167,29168,29169,29170,29171,29172,29173,29174,29175,29176,29178,29179,29180,29181,29182,29183,29184,29185,29186,29187,29188,29189,29191,29192,29193,29194,29195,29196,29197,29198,29199,29200,29201,29202,29203,29204,29205,29206,29207,29208,29209,29210,29211,29212,29214,29215,29216,29217,29218,29219,29220,29221,29222,29223,29225,29227,29229,29230,29231,29234,29235,29236,29242,29244,29246,29248,29249,29250,29251,29252,29253,29254,29257,29258,29259,29262,29263,29264,29265,29267,29268,29269,29271,29272,29274,29276,29278,29280,29283,29284,29285,29288,29290,29291,29292,29293,29296,29297,29299,29300,29302,29303,29304,29307,29308,29309,29314,29315,29317,29318,29319,29320,29321,29324,29326,29328,29329,29331,29332,29333,29334,29335,29336,29337,29338,29339,29340,29341,29342,29344,29345,29346,29347,29348,29349,29350,29351,29352,29353,29354,29355,29358,29361,29362,29363,29365,29370,29371,29372,29373,29374,29375,29376,29381,29382,29383,29385,29386,29387,29388,29391,29393,29395,29396,29397,29398,29400,29402,29403,58566,58567,58568,58569,58570,58571,58572,58573,58574,58575,58576,58577,58578,58579,58580,58581,58582,58583,58584,58585,58586,58587,58588,58589,58590,58591,58592,58593,58594,58595,58596,58597,58598,58599,58600,58601,58602,58603,58604,58605,58606,58607,58608,58609,58610,58611,58612,58613,58614,58615,58616,58617,58618,58619,58620,58621,58622,58623,58624,58625,58626,58627,58628,58629,58630,58631,58632,58633,58634,58635,58636,58637,58638,58639,58640,58641,58642,58643,58644,58645,58646,58647,58648,58649,58650,58651,58652,58653,58654,58655,58656,58657,58658,58659,58660,58661,12288,12289,12290,183,713,711,168,12291,12293,8212,65374,8214,8230,8216,8217,8220,8221,12308,12309,12296,12297,12298,12299,12300,12301,12302,12303,12310,12311,12304,12305,177,215,247,8758,8743,8744,8721,8719,8746,8745,8712,8759,8730,8869,8741,8736,8978,8857,8747,8750,8801,8780,8776,8765,8733,8800,8814,8815,8804,8805,8734,8757,8756,9794,9792,176,8242,8243,8451,65284,164,65504,65505,8240,167,8470,9734,9733,9675,9679,9678,9671,9670,9633,9632,9651,9650,8251,8594,8592,8593,8595,12307,58662,58663,58664,58665,58666,58667,58668,58669,58670,58671,58672,58673,58674,58675,58676,58677,58678,58679,58680,58681,58682,58683,58684,58685,58686,58687,58688,58689,58690,58691,58692,58693,58694,58695,58696,58697,58698,58699,58700,58701,58702,58703,58704,58705,58706,58707,58708,58709,58710,58711,58712,58713,58714,58715,58716,58717,58718,58719,58720,58721,58722,58723,58724,58725,58726,58727,58728,58729,58730,58731,58732,58733,58734,58735,58736,58737,58738,58739,58740,58741,58742,58743,58744,58745,58746,58747,58748,58749,58750,58751,58752,58753,58754,58755,58756,58757,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,59238,59239,59240,59241,59242,59243,9352,9353,9354,9355,9356,9357,9358,9359,9360,9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345,9346,9347,9348,9349,9350,9351,9312,9313,9314,9315,9316,9317,9318,9319,9320,9321,8364,59245,12832,12833,12834,12835,12836,12837,12838,12839,12840,12841,59246,59247,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,59248,59249,58758,58759,58760,58761,58762,58763,58764,58765,58766,58767,58768,58769,58770,58771,58772,58773,58774,58775,58776,58777,58778,58779,58780,58781,58782,58783,58784,58785,58786,58787,58788,58789,58790,58791,58792,58793,58794,58795,58796,58797,58798,58799,58800,58801,58802,58803,58804,58805,58806,58807,58808,58809,58810,58811,58812,58813,58814,58815,58816,58817,58818,58819,58820,58821,58822,58823,58824,58825,58826,58827,58828,58829,58830,58831,58832,58833,58834,58835,58836,58837,58838,58839,58840,58841,58842,58843,58844,58845,58846,58847,58848,58849,58850,58851,58852,12288,65281,65282,65283,65509,65285,65286,65287,65288,65289,65290,65291,65292,65293,65294,65295,65296,65297,65298,65299,65300,65301,65302,65303,65304,65305,65306,65307,65308,65309,65310,65311,65312,65313,65314,65315,65316,65317,65318,65319,65320,65321,65322,65323,65324,65325,65326,65327,65328,65329,65330,65331,65332,65333,65334,65335,65336,65337,65338,65339,65340,65341,65342,65343,65344,65345,65346,65347,65348,65349,65350,65351,65352,65353,65354,65355,65356,65357,65358,65359,65360,65361,65362,65363,65364,65365,65366,65367,65368,65369,65370,65371,65372,65373,65507,58854,58855,58856,58857,58858,58859,58860,58861,58862,58863,58864,58865,58866,58867,58868,58869,58870,58871,58872,58873,58874,58875,58876,58877,58878,58879,58880,58881,58882,58883,58884,58885,58886,58887,58888,58889,58890,58891,58892,58893,58894,58895,58896,58897,58898,58899,58900,58901,58902,58903,58904,58905,58906,58907,58908,58909,58910,58911,58912,58913,58914,58915,58916,58917,58918,58919,58920,58921,58922,58923,58924,58925,58926,58927,58928,58929,58930,58931,58932,58933,58934,58935,58936,58937,58938,58939,58940,58941,58942,58943,58944,58945,58946,58947,58948,58949,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,59250,59251,59252,59253,59254,59255,59256,59257,59258,59259,59260,58950,58951,58952,58953,58954,58955,58956,58957,58958,58959,58960,58961,58962,58963,58964,58965,58966,58967,58968,58969,58970,58971,58972,58973,58974,58975,58976,58977,58978,58979,58980,58981,58982,58983,58984,58985,58986,58987,58988,58989,58990,58991,58992,58993,58994,58995,58996,58997,58998,58999,59000,59001,59002,59003,59004,59005,59006,59007,59008,59009,59010,59011,59012,59013,59014,59015,59016,59017,59018,59019,59020,59021,59022,59023,59024,59025,59026,59027,59028,59029,59030,59031,59032,59033,59034,59035,59036,59037,59038,59039,59040,59041,59042,59043,59044,59045,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,59261,59262,59263,59264,59265,59266,59267,59268,59046,59047,59048,59049,59050,59051,59052,59053,59054,59055,59056,59057,59058,59059,59060,59061,59062,59063,59064,59065,59066,59067,59068,59069,59070,59071,59072,59073,59074,59075,59076,59077,59078,59079,59080,59081,59082,59083,59084,59085,59086,59087,59088,59089,59090,59091,59092,59093,59094,59095,59096,59097,59098,59099,59100,59101,59102,59103,59104,59105,59106,59107,59108,59109,59110,59111,59112,59113,59114,59115,59116,59117,59118,59119,59120,59121,59122,59123,59124,59125,59126,59127,59128,59129,59130,59131,59132,59133,59134,59135,59136,59137,59138,59139,59140,59141,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,59269,59270,59271,59272,59273,59274,59275,59276,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,963,964,965,966,967,968,969,59277,59278,59279,59280,59281,59282,59283,65077,65078,65081,65082,65087,65088,65085,65086,65089,65090,65091,65092,59284,59285,65083,65084,65079,65080,65073,59286,65075,65076,59287,59288,59289,59290,59291,59292,59293,59294,59295,59142,59143,59144,59145,59146,59147,59148,59149,59150,59151,59152,59153,59154,59155,59156,59157,59158,59159,59160,59161,59162,59163,59164,59165,59166,59167,59168,59169,59170,59171,59172,59173,59174,59175,59176,59177,59178,59179,59180,59181,59182,59183,59184,59185,59186,59187,59188,59189,59190,59191,59192,59193,59194,59195,59196,59197,59198,59199,59200,59201,59202,59203,59204,59205,59206,59207,59208,59209,59210,59211,59212,59213,59214,59215,59216,59217,59218,59219,59220,59221,59222,59223,59224,59225,59226,59227,59228,59229,59230,59231,59232,59233,59234,59235,59236,59237,1040,1041,1042,1043,1044,1045,1025,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,59296,59297,59298,59299,59300,59301,59302,59303,59304,59305,59306,59307,59308,59309,59310,1072,1073,1074,1075,1076,1077,1105,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,59311,59312,59313,59314,59315,59316,59317,59318,59319,59320,59321,59322,59323,714,715,729,8211,8213,8229,8245,8453,8457,8598,8599,8600,8601,8725,8735,8739,8786,8806,8807,8895,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584,9585,9586,9587,9601,9602,9603,9604,9605,9606,9607,9608,9609,9610,9611,9612,9613,9614,9615,9619,9620,9621,9660,9661,9698,9699,9700,9701,9737,8853,12306,12317,12318,59324,59325,59326,59327,59328,59329,59330,59331,59332,59333,59334,257,225,462,224,275,233,283,232,299,237,464,236,333,243,466,242,363,250,468,249,470,472,474,476,252,234,593,7743,324,328,505,609,59337,59338,59339,59340,12549,12550,12551,12552,12553,12554,12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570,12571,12572,12573,12574,12575,12576,12577,12578,12579,12580,12581,12582,12583,12584,12585,59341,59342,59343,59344,59345,59346,59347,59348,59349,59350,59351,59352,59353,59354,59355,59356,59357,59358,59359,59360,59361,12321,12322,12323,12324,12325,12326,12327,12328,12329,12963,13198,13199,13212,13213,13214,13217,13252,13262,13265,13266,13269,65072,65506,65508,59362,8481,12849,59363,8208,59364,59365,59366,12540,12443,12444,12541,12542,12294,12445,12446,65097,65098,65099,65100,65101,65102,65103,65104,65105,65106,65108,65109,65110,65111,65113,65114,65115,65116,65117,65118,65119,65120,65121,65122,65123,65124,65125,65126,65128,65129,65130,65131,12350,12272,12273,12274,12275,12276,12277,12278,12279,12280,12281,12282,12283,12295,59380,59381,59382,59383,59384,59385,59386,59387,59388,59389,59390,59391,59392,9472,9473,9474,9475,9476,9477,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,9489,9490,9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506,9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,9521,9522,9523,9524,9525,9526,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536,9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,59393,59394,59395,59396,59397,59398,59399,59400,59401,59402,59403,59404,59405,59406,59407,29404,29405,29407,29410,29411,29412,29413,29414,29415,29418,29419,29429,29430,29433,29437,29438,29439,29440,29442,29444,29445,29446,29447,29448,29449,29451,29452,29453,29455,29456,29457,29458,29460,29464,29465,29466,29471,29472,29475,29476,29478,29479,29480,29485,29487,29488,29490,29491,29493,29494,29498,29499,29500,29501,29504,29505,29506,29507,29508,29509,29510,29511,29512,29513,29514,29515,29516,29518,29519,29521,29523,29524,29525,29526,29528,29529,29530,29531,29532,29533,29534,29535,29537,29538,29539,29540,29541,29542,29543,29544,29545,29546,29547,29550,29552,29553,57344,57345,57346,57347,57348,57349,57350,57351,57352,57353,57354,57355,57356,57357,57358,57359,57360,57361,57362,57363,57364,57365,57366,57367,57368,57369,57370,57371,57372,57373,57374,57375,57376,57377,57378,57379,57380,57381,57382,57383,57384,57385,57386,57387,57388,57389,57390,57391,57392,57393,57394,57395,57396,57397,57398,57399,57400,57401,57402,57403,57404,57405,57406,57407,57408,57409,57410,57411,57412,57413,57414,57415,57416,57417,57418,57419,57420,57421,57422,57423,57424,57425,57426,57427,57428,57429,57430,57431,57432,57433,57434,57435,57436,57437,29554,29555,29556,29557,29558,29559,29560,29561,29562,29563,29564,29565,29567,29568,29569,29570,29571,29573,29574,29576,29578,29580,29581,29583,29584,29586,29587,29588,29589,29591,29592,29593,29594,29596,29597,29598,29600,29601,29603,29604,29605,29606,29607,29608,29610,29612,29613,29617,29620,29621,29622,29624,29625,29628,29629,29630,29631,29633,29635,29636,29637,29638,29639,29643,29644,29646,29650,29651,29652,29653,29654,29655,29656,29658,29659,29660,29661,29663,29665,29666,29667,29668,29670,29672,29674,29675,29676,29678,29679,29680,29681,29683,29684,29685,29686,29687,57438,57439,57440,57441,57442,57443,57444,57445,57446,57447,57448,57449,57450,57451,57452,57453,57454,57455,57456,57457,57458,57459,57460,57461,57462,57463,57464,57465,57466,57467,57468,57469,57470,57471,57472,57473,57474,57475,57476,57477,57478,57479,57480,57481,57482,57483,57484,57485,57486,57487,57488,57489,57490,57491,57492,57493,57494,57495,57496,57497,57498,57499,57500,57501,57502,57503,57504,57505,57506,57507,57508,57509,57510,57511,57512,57513,57514,57515,57516,57517,57518,57519,57520,57521,57522,57523,57524,57525,57526,57527,57528,57529,57530,57531,29688,29689,29690,29691,29692,29693,29694,29695,29696,29697,29698,29700,29703,29704,29707,29708,29709,29710,29713,29714,29715,29716,29717,29718,29719,29720,29721,29724,29725,29726,29727,29728,29729,29731,29732,29735,29737,29739,29741,29743,29745,29746,29751,29752,29753,29754,29755,29757,29758,29759,29760,29762,29763,29764,29765,29766,29767,29768,29769,29770,29771,29772,29773,29774,29775,29776,29777,29778,29779,29780,29782,29784,29789,29792,29793,29794,29795,29796,29797,29798,29799,29800,29801,29802,29803,29804,29806,29807,29809,29810,29811,29812,29813,29816,29817,29818,57532,57533,57534,57535,57536,57537,57538,57539,57540,57541,57542,57543,57544,57545,57546,57547,57548,57549,57550,57551,57552,57553,57554,57555,57556,57557,57558,57559,57560,57561,57562,57563,57564,57565,57566,57567,57568,57569,57570,57571,57572,57573,57574,57575,57576,57577,57578,57579,57580,57581,57582,57583,57584,57585,57586,57587,57588,57589,57590,57591,57592,57593,57594,57595,57596,57597,57598,57599,57600,57601,57602,57603,57604,57605,57606,57607,57608,57609,57610,57611,57612,57613,57614,57615,57616,57617,57618,57619,57620,57621,57622,57623,57624,57625,29819,29820,29821,29823,29826,29828,29829,29830,29832,29833,29834,29836,29837,29839,29841,29842,29843,29844,29845,29846,29847,29848,29849,29850,29851,29853,29855,29856,29857,29858,29859,29860,29861,29862,29866,29867,29868,29869,29870,29871,29872,29873,29874,29875,29876,29877,29878,29879,29880,29881,29883,29884,29885,29886,29887,29888,29889,29890,29891,29892,29893,29894,29895,29896,29897,29898,29899,29900,29901,29902,29903,29904,29905,29907,29908,29909,29910,29911,29912,29913,29914,29915,29917,29919,29921,29925,29927,29928,29929,29930,29931,29932,29933,29936,29937,29938,57626,57627,57628,57629,57630,57631,57632,57633,57634,57635,57636,57637,57638,57639,57640,57641,57642,57643,57644,57645,57646,57647,57648,57649,57650,57651,57652,57653,57654,57655,57656,57657,57658,57659,57660,57661,57662,57663,57664,57665,57666,57667,57668,57669,57670,57671,57672,57673,57674,57675,57676,57677,57678,57679,57680,57681,57682,57683,57684,57685,57686,57687,57688,57689,57690,57691,57692,57693,57694,57695,57696,57697,57698,57699,57700,57701,57702,57703,57704,57705,57706,57707,57708,57709,57710,57711,57712,57713,57714,57715,57716,57717,57718,57719,29939,29941,29944,29945,29946,29947,29948,29949,29950,29952,29953,29954,29955,29957,29958,29959,29960,29961,29962,29963,29964,29966,29968,29970,29972,29973,29974,29975,29979,29981,29982,29984,29985,29986,29987,29988,29990,29991,29994,29998,30004,30006,30009,30012,30013,30015,30017,30018,30019,30020,30022,30023,30025,30026,30029,30032,30033,30034,30035,30037,30038,30039,30040,30045,30046,30047,30048,30049,30050,30051,30052,30055,30056,30057,30059,30060,30061,30062,30063,30064,30065,30067,30069,30070,30071,30074,30075,30076,30077,30078,30080,30081,30082,30084,30085,30087,57720,57721,57722,57723,57724,57725,57726,57727,57728,57729,57730,57731,57732,57733,57734,57735,57736,57737,57738,57739,57740,57741,57742,57743,57744,57745,57746,57747,57748,57749,57750,57751,57752,57753,57754,57755,57756,57757,57758,57759,57760,57761,57762,57763,57764,57765,57766,57767,57768,57769,57770,57771,57772,57773,57774,57775,57776,57777,57778,57779,57780,57781,57782,57783,57784,57785,57786,57787,57788,57789,57790,57791,57792,57793,57794,57795,57796,57797,57798,57799,57800,57801,57802,57803,57804,57805,57806,57807,57808,57809,57810,57811,57812,57813,30088,30089,30090,30092,30093,30094,30096,30099,30101,30104,30107,30108,30110,30114,30118,30119,30120,30121,30122,30125,30134,30135,30138,30139,30143,30144,30145,30150,30155,30156,30158,30159,30160,30161,30163,30167,30169,30170,30172,30173,30175,30176,30177,30181,30185,30188,30189,30190,30191,30194,30195,30197,30198,30199,30200,30202,30203,30205,30206,30210,30212,30214,30215,30216,30217,30219,30221,30222,30223,30225,30226,30227,30228,30230,30234,30236,30237,30238,30241,30243,30247,30248,30252,30254,30255,30257,30258,30262,30263,30265,30266,30267,30269,30273,30274,30276,57814,57815,57816,57817,57818,57819,57820,57821,57822,57823,57824,57825,57826,57827,57828,57829,57830,57831,57832,57833,57834,57835,57836,57837,57838,57839,57840,57841,57842,57843,57844,57845,57846,57847,57848,57849,57850,57851,57852,57853,57854,57855,57856,57857,57858,57859,57860,57861,57862,57863,57864,57865,57866,57867,57868,57869,57870,57871,57872,57873,57874,57875,57876,57877,57878,57879,57880,57881,57882,57883,57884,57885,57886,57887,57888,57889,57890,57891,57892,57893,57894,57895,57896,57897,57898,57899,57900,57901,57902,57903,57904,57905,57906,57907,30277,30278,30279,30280,30281,30282,30283,30286,30287,30288,30289,30290,30291,30293,30295,30296,30297,30298,30299,30301,30303,30304,30305,30306,30308,30309,30310,30311,30312,30313,30314,30316,30317,30318,30320,30321,30322,30323,30324,30325,30326,30327,30329,30330,30332,30335,30336,30337,30339,30341,30345,30346,30348,30349,30351,30352,30354,30356,30357,30359,30360,30362,30363,30364,30365,30366,30367,30368,30369,30370,30371,30373,30374,30375,30376,30377,30378,30379,30380,30381,30383,30384,30387,30389,30390,30391,30392,30393,30394,30395,30396,30397,30398,30400,30401,30403,21834,38463,22467,25384,21710,21769,21696,30353,30284,34108,30702,33406,30861,29233,38552,38797,27688,23433,20474,25353,26263,23736,33018,26696,32942,26114,30414,20985,25942,29100,32753,34948,20658,22885,25034,28595,33453,25420,25170,21485,21543,31494,20843,30116,24052,25300,36299,38774,25226,32793,22365,38712,32610,29240,30333,26575,30334,25670,20336,36133,25308,31255,26001,29677,25644,25203,33324,39041,26495,29256,25198,25292,20276,29923,21322,21150,32458,37030,24110,26758,27036,33152,32465,26834,30917,34444,38225,20621,35876,33502,32990,21253,35090,21093,30404,30407,30409,30411,30412,30419,30421,30425,30426,30428,30429,30430,30432,30433,30434,30435,30436,30438,30439,30440,30441,30442,30443,30444,30445,30448,30451,30453,30454,30455,30458,30459,30461,30463,30464,30466,30467,30469,30470,30474,30476,30478,30479,30480,30481,30482,30483,30484,30485,30486,30487,30488,30491,30492,30493,30494,30497,30499,30500,30501,30503,30506,30507,30508,30510,30512,30513,30514,30515,30516,30521,30523,30525,30526,30527,30530,30532,30533,30534,30536,30537,30538,30539,30540,30541,30542,30543,30546,30547,30548,30549,30550,30551,30552,30553,30556,34180,38649,20445,22561,39281,23453,25265,25253,26292,35961,40077,29190,26479,30865,24754,21329,21271,36744,32972,36125,38049,20493,29384,22791,24811,28953,34987,22868,33519,26412,31528,23849,32503,29997,27893,36454,36856,36924,40763,27604,37145,31508,24444,30887,34006,34109,27605,27609,27606,24065,24199,30201,38381,25949,24330,24517,36767,22721,33218,36991,38491,38829,36793,32534,36140,25153,20415,21464,21342,36776,36777,36779,36941,26631,24426,33176,34920,40150,24971,21035,30250,24428,25996,28626,28392,23486,25672,20853,20912,26564,19993,31177,39292,28851,30557,30558,30559,30560,30564,30567,30569,30570,30573,30574,30575,30576,30577,30578,30579,30580,30581,30582,30583,30584,30586,30587,30588,30593,30594,30595,30598,30599,30600,30601,30602,30603,30607,30608,30611,30612,30613,30614,30615,30616,30617,30618,30619,30620,30621,30622,30625,30627,30628,30630,30632,30635,30637,30638,30639,30641,30642,30644,30646,30647,30648,30649,30650,30652,30654,30656,30657,30658,30659,30660,30661,30662,30663,30664,30665,30666,30667,30668,30670,30671,30672,30673,30674,30675,30676,30677,30678,30680,30681,30682,30685,30686,30687,30688,30689,30692,30149,24182,29627,33760,25773,25320,38069,27874,21338,21187,25615,38082,31636,20271,24091,33334,33046,33162,28196,27850,39539,25429,21340,21754,34917,22496,19981,24067,27493,31807,37096,24598,25830,29468,35009,26448,25165,36130,30572,36393,37319,24425,33756,34081,39184,21442,34453,27531,24813,24808,28799,33485,33329,20179,27815,34255,25805,31961,27133,26361,33609,21397,31574,20391,20876,27979,23618,36461,25554,21449,33580,33590,26597,30900,25661,23519,23700,24046,35815,25286,26612,35962,25600,25530,34633,39307,35863,32544,38130,20135,38416,39076,26124,29462,30694,30696,30698,30703,30704,30705,30706,30708,30709,30711,30713,30714,30715,30716,30723,30724,30725,30726,30727,30728,30730,30731,30734,30735,30736,30739,30741,30745,30747,30750,30752,30753,30754,30756,30760,30762,30763,30766,30767,30769,30770,30771,30773,30774,30781,30783,30785,30786,30787,30788,30790,30792,30793,30794,30795,30797,30799,30801,30803,30804,30808,30809,30810,30811,30812,30814,30815,30816,30817,30818,30819,30820,30821,30822,30823,30824,30825,30831,30832,30833,30834,30835,30836,30837,30838,30840,30841,30842,30843,30845,30846,30847,30848,30849,30850,30851,22330,23581,24120,38271,20607,32928,21378,25950,30021,21809,20513,36229,25220,38046,26397,22066,28526,24034,21557,28818,36710,25199,25764,25507,24443,28552,37108,33251,36784,23576,26216,24561,27785,38472,36225,34924,25745,31216,22478,27225,25104,21576,20056,31243,24809,28548,35802,25215,36894,39563,31204,21507,30196,25345,21273,27744,36831,24347,39536,32827,40831,20360,23610,36196,32709,26021,28861,20805,20914,34411,23815,23456,25277,37228,30068,36364,31264,24833,31609,20167,32504,30597,19985,33261,21021,20986,27249,21416,36487,38148,38607,28353,38500,26970,30852,30853,30854,30856,30858,30859,30863,30864,30866,30868,30869,30870,30873,30877,30878,30880,30882,30884,30886,30888,30889,30890,30891,30892,30893,30894,30895,30901,30902,30903,30904,30906,30907,30908,30909,30911,30912,30914,30915,30916,30918,30919,30920,30924,30925,30926,30927,30929,30930,30931,30934,30935,30936,30938,30939,30940,30941,30942,30943,30944,30945,30946,30947,30948,30949,30950,30951,30953,30954,30955,30957,30958,30959,30960,30961,30963,30965,30966,30968,30969,30971,30972,30973,30974,30975,30976,30978,30979,30980,30982,30983,30984,30985,30986,30987,30988,30784,20648,30679,25616,35302,22788,25571,24029,31359,26941,20256,33337,21912,20018,30126,31383,24162,24202,38383,21019,21561,28810,25462,38180,22402,26149,26943,37255,21767,28147,32431,34850,25139,32496,30133,33576,30913,38604,36766,24904,29943,35789,27492,21050,36176,27425,32874,33905,22257,21254,20174,19995,20945,31895,37259,31751,20419,36479,31713,31388,25703,23828,20652,33030,30209,31929,28140,32736,26449,23384,23544,30923,25774,25619,25514,25387,38169,25645,36798,31572,30249,25171,22823,21574,27513,20643,25140,24102,27526,20195,36151,34955,24453,36910,30989,30990,30991,30992,30993,30994,30996,30997,30998,30999,31000,31001,31002,31003,31004,31005,31007,31008,31009,31010,31011,31013,31014,31015,31016,31017,31018,31019,31020,31021,31022,31023,31024,31025,31026,31027,31029,31030,31031,31032,31033,31037,31039,31042,31043,31044,31045,31047,31050,31051,31052,31053,31054,31055,31056,31057,31058,31060,31061,31064,31065,31073,31075,31076,31078,31081,31082,31083,31084,31086,31088,31089,31090,31091,31092,31093,31094,31097,31099,31100,31101,31102,31103,31106,31107,31110,31111,31112,31113,31115,31116,31117,31118,31120,31121,31122,24608,32829,25285,20025,21333,37112,25528,32966,26086,27694,20294,24814,28129,35806,24377,34507,24403,25377,20826,33633,26723,20992,25443,36424,20498,23707,31095,23548,21040,31291,24764,36947,30423,24503,24471,30340,36460,28783,30331,31561,30634,20979,37011,22564,20302,28404,36842,25932,31515,29380,28068,32735,23265,25269,24213,22320,33922,31532,24093,24351,36882,32532,39072,25474,28359,30872,28857,20856,38747,22443,30005,20291,30008,24215,24806,22880,28096,27583,30857,21500,38613,20939,20993,25481,21514,38035,35843,36300,29241,30879,34678,36845,35853,21472,31123,31124,31125,31126,31127,31128,31129,31131,31132,31133,31134,31135,31136,31137,31138,31139,31140,31141,31142,31144,31145,31146,31147,31148,31149,31150,31151,31152,31153,31154,31156,31157,31158,31159,31160,31164,31167,31170,31172,31173,31175,31176,31178,31180,31182,31183,31184,31187,31188,31190,31191,31193,31194,31195,31196,31197,31198,31200,31201,31202,31205,31208,31210,31212,31214,31217,31218,31219,31220,31221,31222,31223,31225,31226,31228,31230,31231,31233,31236,31237,31239,31240,31241,31242,31244,31247,31248,31249,31250,31251,31253,31254,31256,31257,31259,31260,19969,30447,21486,38025,39030,40718,38189,23450,35746,20002,19996,20908,33891,25026,21160,26635,20375,24683,20923,27934,20828,25238,26007,38497,35910,36887,30168,37117,30563,27602,29322,29420,35835,22581,30585,36172,26460,38208,32922,24230,28193,22930,31471,30701,38203,27573,26029,32526,22534,20817,38431,23545,22697,21544,36466,25958,39039,22244,38045,30462,36929,25479,21702,22810,22842,22427,36530,26421,36346,33333,21057,24816,22549,34558,23784,40517,20420,39069,35769,23077,24694,21380,25212,36943,37122,39295,24681,32780,20799,32819,23572,39285,27953,20108,31261,31263,31265,31266,31268,31269,31270,31271,31272,31273,31274,31275,31276,31277,31278,31279,31280,31281,31282,31284,31285,31286,31288,31290,31294,31296,31297,31298,31299,31300,31301,31303,31304,31305,31306,31307,31308,31309,31310,31311,31312,31314,31315,31316,31317,31318,31320,31321,31322,31323,31324,31325,31326,31327,31328,31329,31330,31331,31332,31333,31334,31335,31336,31337,31338,31339,31340,31341,31342,31343,31345,31346,31347,31349,31355,31356,31357,31358,31362,31365,31367,31369,31370,31371,31372,31374,31375,31376,31379,31380,31385,31386,31387,31390,31393,31394,36144,21457,32602,31567,20240,20047,38400,27861,29648,34281,24070,30058,32763,27146,30718,38034,32321,20961,28902,21453,36820,33539,36137,29359,39277,27867,22346,33459,26041,32938,25151,38450,22952,20223,35775,32442,25918,33778,38750,21857,39134,32933,21290,35837,21536,32954,24223,27832,36153,33452,37210,21545,27675,20998,32439,22367,28954,27774,31881,22859,20221,24575,24868,31914,20016,23553,26539,34562,23792,38155,39118,30127,28925,36898,20911,32541,35773,22857,20964,20315,21542,22827,25975,32932,23413,25206,25282,36752,24133,27679,31526,20239,20440,26381,31395,31396,31399,31401,31402,31403,31406,31407,31408,31409,31410,31412,31413,31414,31415,31416,31417,31418,31419,31420,31421,31422,31424,31425,31426,31427,31428,31429,31430,31431,31432,31433,31434,31436,31437,31438,31439,31440,31441,31442,31443,31444,31445,31447,31448,31450,31451,31452,31453,31457,31458,31460,31463,31464,31465,31466,31467,31468,31470,31472,31473,31474,31475,31476,31477,31478,31479,31480,31483,31484,31486,31488,31489,31490,31493,31495,31497,31500,31501,31502,31504,31506,31507,31510,31511,31512,31514,31516,31517,31519,31521,31522,31523,31527,31529,31533,28014,28074,31119,34993,24343,29995,25242,36741,20463,37340,26023,33071,33105,24220,33104,36212,21103,35206,36171,22797,20613,20184,38428,29238,33145,36127,23500,35747,38468,22919,32538,21648,22134,22030,35813,25913,27010,38041,30422,28297,24178,29976,26438,26577,31487,32925,36214,24863,31174,25954,36195,20872,21018,38050,32568,32923,32434,23703,28207,26464,31705,30347,39640,33167,32660,31957,25630,38224,31295,21578,21733,27468,25601,25096,40509,33011,30105,21106,38761,33883,26684,34532,38401,38548,38124,20010,21508,32473,26681,36319,32789,26356,24218,32697,31535,31536,31538,31540,31541,31542,31543,31545,31547,31549,31551,31552,31553,31554,31555,31556,31558,31560,31562,31565,31566,31571,31573,31575,31577,31580,31582,31583,31585,31587,31588,31589,31590,31591,31592,31593,31594,31595,31596,31597,31599,31600,31603,31604,31606,31608,31610,31612,31613,31615,31617,31618,31619,31620,31622,31623,31624,31625,31626,31627,31628,31630,31631,31633,31634,31635,31638,31640,31641,31642,31643,31646,31647,31648,31651,31652,31653,31662,31663,31664,31666,31667,31669,31670,31671,31673,31674,31675,31676,31677,31678,31679,31680,31682,31683,31684,22466,32831,26775,24037,25915,21151,24685,40858,20379,36524,20844,23467,24339,24041,27742,25329,36129,20849,38057,21246,27807,33503,29399,22434,26500,36141,22815,36764,33735,21653,31629,20272,27837,23396,22993,40723,21476,34506,39592,35895,32929,25925,39038,22266,38599,21038,29916,21072,23521,25346,35074,20054,25296,24618,26874,20851,23448,20896,35266,31649,39302,32592,24815,28748,36143,20809,24191,36891,29808,35268,22317,30789,24402,40863,38394,36712,39740,35809,30328,26690,26588,36330,36149,21053,36746,28378,26829,38149,37101,22269,26524,35065,36807,21704,31685,31688,31689,31690,31691,31693,31694,31695,31696,31698,31700,31701,31702,31703,31704,31707,31708,31710,31711,31712,31714,31715,31716,31719,31720,31721,31723,31724,31725,31727,31728,31730,31731,31732,31733,31734,31736,31737,31738,31739,31741,31743,31744,31745,31746,31747,31748,31749,31750,31752,31753,31754,31757,31758,31760,31761,31762,31763,31764,31765,31767,31768,31769,31770,31771,31772,31773,31774,31776,31777,31778,31779,31780,31781,31784,31785,31787,31788,31789,31790,31791,31792,31793,31794,31795,31796,31797,31798,31799,31801,31802,31803,31804,31805,31806,31810,39608,23401,28023,27686,20133,23475,39559,37219,25000,37039,38889,21547,28085,23506,20989,21898,32597,32752,25788,25421,26097,25022,24717,28938,27735,27721,22831,26477,33322,22741,22158,35946,27627,37085,22909,32791,21495,28009,21621,21917,33655,33743,26680,31166,21644,20309,21512,30418,35977,38402,27827,28088,36203,35088,40548,36154,22079,40657,30165,24456,29408,24680,21756,20136,27178,34913,24658,36720,21700,28888,34425,40511,27946,23439,24344,32418,21897,20399,29492,21564,21402,20505,21518,21628,20046,24573,29786,22774,33899,32993,34676,29392,31946,28246,31811,31812,31813,31814,31815,31816,31817,31818,31819,31820,31822,31823,31824,31825,31826,31827,31828,31829,31830,31831,31832,31833,31834,31835,31836,31837,31838,31839,31840,31841,31842,31843,31844,31845,31846,31847,31848,31849,31850,31851,31852,31853,31854,31855,31856,31857,31858,31861,31862,31863,31864,31865,31866,31870,31871,31872,31873,31874,31875,31876,31877,31878,31879,31880,31882,31883,31884,31885,31886,31887,31888,31891,31892,31894,31897,31898,31899,31904,31905,31907,31910,31911,31912,31913,31915,31916,31917,31919,31920,31924,31925,31926,31927,31928,31930,31931,24359,34382,21804,25252,20114,27818,25143,33457,21719,21326,29502,28369,30011,21010,21270,35805,27088,24458,24576,28142,22351,27426,29615,26707,36824,32531,25442,24739,21796,30186,35938,28949,28067,23462,24187,33618,24908,40644,30970,34647,31783,30343,20976,24822,29004,26179,24140,24653,35854,28784,25381,36745,24509,24674,34516,22238,27585,24724,24935,21321,24800,26214,36159,31229,20250,28905,27719,35763,35826,32472,33636,26127,23130,39746,27985,28151,35905,27963,20249,28779,33719,25110,24785,38669,36135,31096,20987,22334,22522,26426,30072,31293,31215,31637,31935,31936,31938,31939,31940,31942,31945,31947,31950,31951,31952,31953,31954,31955,31956,31960,31962,31963,31965,31966,31969,31970,31971,31972,31973,31974,31975,31977,31978,31979,31980,31981,31982,31984,31985,31986,31987,31988,31989,31990,31991,31993,31994,31996,31997,31998,31999,32000,32001,32002,32003,32004,32005,32006,32007,32008,32009,32011,32012,32013,32014,32015,32016,32017,32018,32019,32020,32021,32022,32023,32024,32025,32026,32027,32028,32029,32030,32031,32033,32035,32036,32037,32038,32040,32041,32042,32044,32045,32046,32048,32049,32050,32051,32052,32053,32054,32908,39269,36857,28608,35749,40481,23020,32489,32521,21513,26497,26840,36753,31821,38598,21450,24613,30142,27762,21363,23241,32423,25380,20960,33034,24049,34015,25216,20864,23395,20238,31085,21058,24760,27982,23492,23490,35745,35760,26082,24524,38469,22931,32487,32426,22025,26551,22841,20339,23478,21152,33626,39050,36158,30002,38078,20551,31292,20215,26550,39550,23233,27516,30417,22362,23574,31546,38388,29006,20860,32937,33392,22904,32516,33575,26816,26604,30897,30839,25315,25441,31616,20461,21098,20943,33616,27099,37492,36341,36145,35265,38190,31661,20214,32055,32056,32057,32058,32059,32060,32061,32062,32063,32064,32065,32066,32067,32068,32069,32070,32071,32072,32073,32074,32075,32076,32077,32078,32079,32080,32081,32082,32083,32084,32085,32086,32087,32088,32089,32090,32091,32092,32093,32094,32095,32096,32097,32098,32099,32100,32101,32102,32103,32104,32105,32106,32107,32108,32109,32111,32112,32113,32114,32115,32116,32117,32118,32120,32121,32122,32123,32124,32125,32126,32127,32128,32129,32130,32131,32132,32133,32134,32135,32136,32137,32138,32139,32140,32141,32142,32143,32144,32145,32146,32147,32148,32149,32150,32151,32152,20581,33328,21073,39279,28176,28293,28071,24314,20725,23004,23558,27974,27743,30086,33931,26728,22870,35762,21280,37233,38477,34121,26898,30977,28966,33014,20132,37066,27975,39556,23047,22204,25605,38128,30699,20389,33050,29409,35282,39290,32564,32478,21119,25945,37237,36735,36739,21483,31382,25581,25509,30342,31224,34903,38454,25130,21163,33410,26708,26480,25463,30571,31469,27905,32467,35299,22992,25106,34249,33445,30028,20511,20171,30117,35819,23626,24062,31563,26020,37329,20170,27941,35167,32039,38182,20165,35880,36827,38771,26187,31105,36817,28908,28024,32153,32154,32155,32156,32157,32158,32159,32160,32161,32162,32163,32164,32165,32167,32168,32169,32170,32171,32172,32173,32175,32176,32177,32178,32179,32180,32181,32182,32183,32184,32185,32186,32187,32188,32189,32190,32191,32192,32193,32194,32195,32196,32197,32198,32199,32200,32201,32202,32203,32204,32205,32206,32207,32208,32209,32210,32211,32212,32213,32214,32215,32216,32217,32218,32219,32220,32221,32222,32223,32224,32225,32226,32227,32228,32229,32230,32231,32232,32233,32234,32235,32236,32237,32238,32239,32240,32241,32242,32243,32244,32245,32246,32247,32248,32249,32250,23613,21170,33606,20834,33550,30555,26230,40120,20140,24778,31934,31923,32463,20117,35686,26223,39048,38745,22659,25964,38236,24452,30153,38742,31455,31454,20928,28847,31384,25578,31350,32416,29590,38893,20037,28792,20061,37202,21417,25937,26087,33276,33285,21646,23601,30106,38816,25304,29401,30141,23621,39545,33738,23616,21632,30697,20030,27822,32858,25298,25454,24040,20855,36317,36382,38191,20465,21477,24807,28844,21095,25424,40515,23071,20518,30519,21367,32482,25733,25899,25225,25496,20500,29237,35273,20915,35776,32477,22343,33740,38055,20891,21531,23803,32251,32252,32253,32254,32255,32256,32257,32258,32259,32260,32261,32262,32263,32264,32265,32266,32267,32268,32269,32270,32271,32272,32273,32274,32275,32276,32277,32278,32279,32280,32281,32282,32283,32284,32285,32286,32287,32288,32289,32290,32291,32292,32293,32294,32295,32296,32297,32298,32299,32300,32301,32302,32303,32304,32305,32306,32307,32308,32309,32310,32311,32312,32313,32314,32316,32317,32318,32319,32320,32322,32323,32324,32325,32326,32328,32329,32330,32331,32332,32333,32334,32335,32336,32337,32338,32339,32340,32341,32342,32343,32344,32345,32346,32347,32348,32349,20426,31459,27994,37089,39567,21888,21654,21345,21679,24320,25577,26999,20975,24936,21002,22570,21208,22350,30733,30475,24247,24951,31968,25179,25239,20130,28821,32771,25335,28900,38752,22391,33499,26607,26869,30933,39063,31185,22771,21683,21487,28212,20811,21051,23458,35838,32943,21827,22438,24691,22353,21549,31354,24656,23380,25511,25248,21475,25187,23495,26543,21741,31391,33510,37239,24211,35044,22840,22446,25358,36328,33007,22359,31607,20393,24555,23485,27454,21281,31568,29378,26694,30719,30518,26103,20917,20111,30420,23743,31397,33909,22862,39745,20608,32350,32351,32352,32353,32354,32355,32356,32357,32358,32359,32360,32361,32362,32363,32364,32365,32366,32367,32368,32369,32370,32371,32372,32373,32374,32375,32376,32377,32378,32379,32380,32381,32382,32383,32384,32385,32387,32388,32389,32390,32391,32392,32393,32394,32395,32396,32397,32398,32399,32400,32401,32402,32403,32404,32405,32406,32407,32408,32409,32410,32412,32413,32414,32430,32436,32443,32444,32470,32484,32492,32505,32522,32528,32542,32567,32569,32571,32572,32573,32574,32575,32576,32577,32579,32582,32583,32584,32585,32586,32587,32588,32589,32590,32591,32594,32595,39304,24871,28291,22372,26118,25414,22256,25324,25193,24275,38420,22403,25289,21895,34593,33098,36771,21862,33713,26469,36182,34013,23146,26639,25318,31726,38417,20848,28572,35888,25597,35272,25042,32518,28866,28389,29701,27028,29436,24266,37070,26391,28010,25438,21171,29282,32769,20332,23013,37226,28889,28061,21202,20048,38647,38253,34174,30922,32047,20769,22418,25794,32907,31867,27882,26865,26974,20919,21400,26792,29313,40654,31729,29432,31163,28435,29702,26446,37324,40100,31036,33673,33620,21519,26647,20029,21385,21169,30782,21382,21033,20616,20363,20432,32598,32601,32603,32604,32605,32606,32608,32611,32612,32613,32614,32615,32619,32620,32621,32623,32624,32627,32629,32630,32631,32632,32634,32635,32636,32637,32639,32640,32642,32643,32644,32645,32646,32647,32648,32649,32651,32653,32655,32656,32657,32658,32659,32661,32662,32663,32664,32665,32667,32668,32672,32674,32675,32677,32678,32680,32681,32682,32683,32684,32685,32686,32689,32691,32692,32693,32694,32695,32698,32699,32702,32704,32706,32707,32708,32710,32711,32712,32713,32715,32717,32719,32720,32721,32722,32723,32726,32727,32729,32730,32731,32732,32733,32734,32738,32739,30178,31435,31890,27813,38582,21147,29827,21737,20457,32852,33714,36830,38256,24265,24604,28063,24088,25947,33080,38142,24651,28860,32451,31918,20937,26753,31921,33391,20004,36742,37327,26238,20142,35845,25769,32842,20698,30103,29134,23525,36797,28518,20102,25730,38243,24278,26009,21015,35010,28872,21155,29454,29747,26519,30967,38678,20020,37051,40158,28107,20955,36161,21533,25294,29618,33777,38646,40836,38083,20278,32666,20940,28789,38517,23725,39046,21478,20196,28316,29705,27060,30827,39311,30041,21016,30244,27969,26611,20845,40857,32843,21657,31548,31423,32740,32743,32744,32746,32747,32748,32749,32751,32754,32756,32757,32758,32759,32760,32761,32762,32765,32766,32767,32770,32775,32776,32777,32778,32782,32783,32785,32787,32794,32795,32797,32798,32799,32801,32803,32804,32811,32812,32813,32814,32815,32816,32818,32820,32825,32826,32828,32830,32832,32833,32836,32837,32839,32840,32841,32846,32847,32848,32849,32851,32853,32854,32855,32857,32859,32860,32861,32862,32863,32864,32865,32866,32867,32868,32869,32870,32871,32872,32875,32876,32877,32878,32879,32880,32882,32883,32884,32885,32886,32887,32888,32889,32890,32891,32892,32893,38534,22404,25314,38471,27004,23044,25602,31699,28431,38475,33446,21346,39045,24208,28809,25523,21348,34383,40065,40595,30860,38706,36335,36162,40575,28510,31108,24405,38470,25134,39540,21525,38109,20387,26053,23653,23649,32533,34385,27695,24459,29575,28388,32511,23782,25371,23402,28390,21365,20081,25504,30053,25249,36718,20262,20177,27814,32438,35770,33821,34746,32599,36923,38179,31657,39585,35064,33853,27931,39558,32476,22920,40635,29595,30721,34434,39532,39554,22043,21527,22475,20080,40614,21334,36808,33033,30610,39314,34542,28385,34067,26364,24930,28459,32894,32897,32898,32901,32904,32906,32909,32910,32911,32912,32913,32914,32916,32917,32919,32921,32926,32931,32934,32935,32936,32940,32944,32947,32949,32950,32952,32953,32955,32965,32967,32968,32969,32970,32971,32975,32976,32977,32978,32979,32980,32981,32984,32991,32992,32994,32995,32998,33006,33013,33015,33017,33019,33022,33023,33024,33025,33027,33028,33029,33031,33032,33035,33036,33045,33047,33049,33051,33052,33053,33055,33056,33057,33058,33059,33060,33061,33062,33063,33064,33065,33066,33067,33069,33070,33072,33075,33076,33077,33079,33081,33082,33083,33084,33085,33087,35881,33426,33579,30450,27667,24537,33725,29483,33541,38170,27611,30683,38086,21359,33538,20882,24125,35980,36152,20040,29611,26522,26757,37238,38665,29028,27809,30473,23186,38209,27599,32654,26151,23504,22969,23194,38376,38391,20204,33804,33945,27308,30431,38192,29467,26790,23391,30511,37274,38753,31964,36855,35868,24357,31859,31192,35269,27852,34588,23494,24130,26825,30496,32501,20885,20813,21193,23081,32517,38754,33495,25551,30596,34256,31186,28218,24217,22937,34065,28781,27665,25279,30399,25935,24751,38397,26126,34719,40483,38125,21517,21629,35884,25720,33088,33089,33090,33091,33092,33093,33095,33097,33101,33102,33103,33106,33110,33111,33112,33115,33116,33117,33118,33119,33121,33122,33123,33124,33126,33128,33130,33131,33132,33135,33138,33139,33141,33142,33143,33144,33153,33155,33156,33157,33158,33159,33161,33163,33164,33165,33166,33168,33170,33171,33172,33173,33174,33175,33177,33178,33182,33183,33184,33185,33186,33188,33189,33191,33193,33195,33196,33197,33198,33199,33200,33201,33202,33204,33205,33206,33207,33208,33209,33212,33213,33214,33215,33220,33221,33223,33224,33225,33227,33229,33230,33231,33232,33233,33234,33235,25721,34321,27169,33180,30952,25705,39764,25273,26411,33707,22696,40664,27819,28448,23518,38476,35851,29279,26576,25287,29281,20137,22982,27597,22675,26286,24149,21215,24917,26408,30446,30566,29287,31302,25343,21738,21584,38048,37027,23068,32435,27670,20035,22902,32784,22856,21335,30007,38590,22218,25376,33041,24700,38393,28118,21602,39297,20869,23273,33021,22958,38675,20522,27877,23612,25311,20320,21311,33147,36870,28346,34091,25288,24180,30910,25781,25467,24565,23064,37247,40479,23615,25423,32834,23421,21870,38218,38221,28037,24744,26592,29406,20957,23425,33236,33237,33238,33239,33240,33241,33242,33243,33244,33245,33246,33247,33248,33249,33250,33252,33253,33254,33256,33257,33259,33262,33263,33264,33265,33266,33269,33270,33271,33272,33273,33274,33277,33279,33283,33287,33288,33289,33290,33291,33294,33295,33297,33299,33301,33302,33303,33304,33305,33306,33309,33312,33316,33317,33318,33319,33321,33326,33330,33338,33340,33341,33343,33344,33345,33346,33347,33349,33350,33352,33354,33356,33357,33358,33360,33361,33362,33363,33364,33365,33366,33367,33369,33371,33372,33373,33374,33376,33377,33378,33379,33380,33381,33382,33383,33385,25319,27870,29275,25197,38062,32445,33043,27987,20892,24324,22900,21162,24594,22899,26262,34384,30111,25386,25062,31983,35834,21734,27431,40485,27572,34261,21589,20598,27812,21866,36276,29228,24085,24597,29750,25293,25490,29260,24472,28227,27966,25856,28504,30424,30928,30460,30036,21028,21467,20051,24222,26049,32810,32982,25243,21638,21032,28846,34957,36305,27873,21624,32986,22521,35060,36180,38506,37197,20329,27803,21943,30406,30768,25256,28921,28558,24429,34028,26842,30844,31735,33192,26379,40527,25447,30896,22383,30738,38713,25209,25259,21128,29749,27607,33386,33387,33388,33389,33393,33397,33398,33399,33400,33403,33404,33408,33409,33411,33413,33414,33415,33417,33420,33424,33427,33428,33429,33430,33434,33435,33438,33440,33442,33443,33447,33458,33461,33462,33466,33467,33468,33471,33472,33474,33475,33477,33478,33481,33488,33494,33497,33498,33501,33506,33511,33512,33513,33514,33516,33517,33518,33520,33522,33523,33525,33526,33528,33530,33532,33533,33534,33535,33536,33546,33547,33549,33552,33554,33555,33558,33560,33561,33565,33566,33567,33568,33569,33570,33571,33572,33573,33574,33577,33578,33582,33584,33586,33591,33595,33597,21860,33086,30130,30382,21305,30174,20731,23617,35692,31687,20559,29255,39575,39128,28418,29922,31080,25735,30629,25340,39057,36139,21697,32856,20050,22378,33529,33805,24179,20973,29942,35780,23631,22369,27900,39047,23110,30772,39748,36843,31893,21078,25169,38138,20166,33670,33889,33769,33970,22484,26420,22275,26222,28006,35889,26333,28689,26399,27450,26646,25114,22971,19971,20932,28422,26578,27791,20854,26827,22855,27495,30054,23822,33040,40784,26071,31048,31041,39569,36215,23682,20062,20225,21551,22865,30732,22120,27668,36804,24323,27773,27875,35755,25488,33598,33599,33601,33602,33604,33605,33608,33610,33611,33612,33613,33614,33619,33621,33622,33623,33624,33625,33629,33634,33648,33649,33650,33651,33652,33653,33654,33657,33658,33662,33663,33664,33665,33666,33667,33668,33671,33672,33674,33675,33676,33677,33679,33680,33681,33684,33685,33686,33687,33689,33690,33693,33695,33697,33698,33699,33700,33701,33702,33703,33708,33709,33710,33711,33717,33723,33726,33727,33730,33731,33732,33734,33736,33737,33739,33741,33742,33744,33745,33746,33747,33749,33751,33753,33754,33755,33758,33762,33763,33764,33766,33767,33768,33771,33772,33773,24688,27965,29301,25190,38030,38085,21315,36801,31614,20191,35878,20094,40660,38065,38067,21069,28508,36963,27973,35892,22545,23884,27424,27465,26538,21595,33108,32652,22681,34103,24378,25250,27207,38201,25970,24708,26725,30631,20052,20392,24039,38808,25772,32728,23789,20431,31373,20999,33540,19988,24623,31363,38054,20405,20146,31206,29748,21220,33465,25810,31165,23517,27777,38738,36731,27682,20542,21375,28165,25806,26228,27696,24773,39031,35831,24198,29756,31351,31179,19992,37041,29699,27714,22234,37195,27845,36235,21306,34502,26354,36527,23624,39537,28192,33774,33775,33779,33780,33781,33782,33783,33786,33787,33788,33790,33791,33792,33794,33797,33799,33800,33801,33802,33808,33810,33811,33812,33813,33814,33815,33817,33818,33819,33822,33823,33824,33825,33826,33827,33833,33834,33835,33836,33837,33838,33839,33840,33842,33843,33844,33845,33846,33847,33849,33850,33851,33854,33855,33856,33857,33858,33859,33860,33861,33863,33864,33865,33866,33867,33868,33869,33870,33871,33872,33874,33875,33876,33877,33878,33880,33885,33886,33887,33888,33890,33892,33893,33894,33895,33896,33898,33902,33903,33904,33906,33908,33911,33913,33915,33916,21462,23094,40843,36259,21435,22280,39079,26435,37275,27849,20840,30154,25331,29356,21048,21149,32570,28820,30264,21364,40522,27063,30830,38592,35033,32676,28982,29123,20873,26579,29924,22756,25880,22199,35753,39286,25200,32469,24825,28909,22764,20161,20154,24525,38887,20219,35748,20995,22922,32427,25172,20173,26085,25102,33592,33993,33635,34701,29076,28342,23481,32466,20887,25545,26580,32905,33593,34837,20754,23418,22914,36785,20083,27741,20837,35109,36719,38446,34122,29790,38160,38384,28070,33509,24369,25746,27922,33832,33134,40131,22622,36187,19977,21441,33917,33918,33919,33920,33921,33923,33924,33925,33926,33930,33933,33935,33936,33937,33938,33939,33940,33941,33942,33944,33946,33947,33949,33950,33951,33952,33954,33955,33956,33957,33958,33959,33960,33961,33962,33963,33964,33965,33966,33968,33969,33971,33973,33974,33975,33979,33980,33982,33984,33986,33987,33989,33990,33991,33992,33995,33996,33998,33999,34002,34004,34005,34007,34008,34009,34010,34011,34012,34014,34017,34018,34020,34023,34024,34025,34026,34027,34029,34030,34031,34033,34034,34035,34036,34037,34038,34039,34040,34041,34042,34043,34045,34046,34048,34049,34050,20254,25955,26705,21971,20007,25620,39578,25195,23234,29791,33394,28073,26862,20711,33678,30722,26432,21049,27801,32433,20667,21861,29022,31579,26194,29642,33515,26441,23665,21024,29053,34923,38378,38485,25797,36193,33203,21892,27733,25159,32558,22674,20260,21830,36175,26188,19978,23578,35059,26786,25422,31245,28903,33421,21242,38902,23569,21736,37045,32461,22882,36170,34503,33292,33293,36198,25668,23556,24913,28041,31038,35774,30775,30003,21627,20280,36523,28145,23072,32453,31070,27784,23457,23158,29978,32958,24910,28183,22768,29983,29989,29298,21319,32499,34051,34052,34053,34054,34055,34056,34057,34058,34059,34061,34062,34063,34064,34066,34068,34069,34070,34072,34073,34075,34076,34077,34078,34080,34082,34083,34084,34085,34086,34087,34088,34089,34090,34093,34094,34095,34096,34097,34098,34099,34100,34101,34102,34110,34111,34112,34113,34114,34116,34117,34118,34119,34123,34124,34125,34126,34127,34128,34129,34130,34131,34132,34133,34135,34136,34138,34139,34140,34141,34143,34144,34145,34146,34147,34149,34150,34151,34153,34154,34155,34156,34157,34158,34159,34160,34161,34163,34165,34166,34167,34168,34172,34173,34175,34176,34177,30465,30427,21097,32988,22307,24072,22833,29422,26045,28287,35799,23608,34417,21313,30707,25342,26102,20160,39135,34432,23454,35782,21490,30690,20351,23630,39542,22987,24335,31034,22763,19990,26623,20107,25325,35475,36893,21183,26159,21980,22124,36866,20181,20365,37322,39280,27663,24066,24643,23460,35270,35797,25910,25163,39318,23432,23551,25480,21806,21463,30246,20861,34092,26530,26803,27530,25234,36755,21460,33298,28113,30095,20070,36174,23408,29087,34223,26257,26329,32626,34560,40653,40736,23646,26415,36848,26641,26463,25101,31446,22661,24246,25968,28465,34178,34179,34182,34184,34185,34186,34187,34188,34189,34190,34192,34193,34194,34195,34196,34197,34198,34199,34200,34201,34202,34205,34206,34207,34208,34209,34210,34211,34213,34214,34215,34217,34219,34220,34221,34225,34226,34227,34228,34229,34230,34232,34234,34235,34236,34237,34238,34239,34240,34242,34243,34244,34245,34246,34247,34248,34250,34251,34252,34253,34254,34257,34258,34260,34262,34263,34264,34265,34266,34267,34269,34270,34271,34272,34273,34274,34275,34277,34278,34279,34280,34282,34283,34284,34285,34286,34287,34288,34289,34290,34291,34292,34293,34294,34295,34296,24661,21047,32781,25684,34928,29993,24069,26643,25332,38684,21452,29245,35841,27700,30561,31246,21550,30636,39034,33308,35828,30805,26388,28865,26031,25749,22070,24605,31169,21496,19997,27515,32902,23546,21987,22235,20282,20284,39282,24051,26494,32824,24578,39042,36865,23435,35772,35829,25628,33368,25822,22013,33487,37221,20439,32032,36895,31903,20723,22609,28335,23487,35785,32899,37240,33948,31639,34429,38539,38543,32485,39635,30862,23681,31319,36930,38567,31071,23385,25439,31499,34001,26797,21766,32553,29712,32034,38145,25152,22604,20182,23427,22905,22612,34297,34298,34300,34301,34302,34304,34305,34306,34307,34308,34310,34311,34312,34313,34314,34315,34316,34317,34318,34319,34320,34322,34323,34324,34325,34327,34328,34329,34330,34331,34332,34333,34334,34335,34336,34337,34338,34339,34340,34341,34342,34344,34346,34347,34348,34349,34350,34351,34352,34353,34354,34355,34356,34357,34358,34359,34361,34362,34363,34365,34366,34367,34368,34369,34370,34371,34372,34373,34374,34375,34376,34377,34378,34379,34380,34386,34387,34389,34390,34391,34392,34393,34395,34396,34397,34399,34400,34401,34403,34404,34405,34406,34407,34408,34409,34410,29549,25374,36427,36367,32974,33492,25260,21488,27888,37214,22826,24577,27760,22349,25674,36138,30251,28393,22363,27264,30192,28525,35885,35848,22374,27631,34962,30899,25506,21497,28845,27748,22616,25642,22530,26848,33179,21776,31958,20504,36538,28108,36255,28907,25487,28059,28372,32486,33796,26691,36867,28120,38518,35752,22871,29305,34276,33150,30140,35466,26799,21076,36386,38161,25552,39064,36420,21884,20307,26367,22159,24789,28053,21059,23625,22825,28155,22635,30000,29980,24684,33300,33094,25361,26465,36834,30522,36339,36148,38081,24086,21381,21548,28867,34413,34415,34416,34418,34419,34420,34421,34422,34423,34424,34435,34436,34437,34438,34439,34440,34441,34446,34447,34448,34449,34450,34452,34454,34455,34456,34457,34458,34459,34462,34463,34464,34465,34466,34469,34470,34475,34477,34478,34482,34483,34487,34488,34489,34491,34492,34493,34494,34495,34497,34498,34499,34501,34504,34508,34509,34514,34515,34517,34518,34519,34522,34524,34525,34528,34529,34530,34531,34533,34534,34535,34536,34538,34539,34540,34543,34549,34550,34551,34554,34555,34556,34557,34559,34561,34564,34565,34566,34571,34572,34574,34575,34576,34577,34580,34582,27712,24311,20572,20141,24237,25402,33351,36890,26704,37230,30643,21516,38108,24420,31461,26742,25413,31570,32479,30171,20599,25237,22836,36879,20984,31171,31361,22270,24466,36884,28034,23648,22303,21520,20820,28237,22242,25512,39059,33151,34581,35114,36864,21534,23663,33216,25302,25176,33073,40501,38464,39534,39548,26925,22949,25299,21822,25366,21703,34521,27964,23043,29926,34972,27498,22806,35916,24367,28286,29609,39037,20024,28919,23436,30871,25405,26202,30358,24779,23451,23113,19975,33109,27754,29579,20129,26505,32593,24448,26106,26395,24536,22916,23041,34585,34587,34589,34591,34592,34596,34598,34599,34600,34602,34603,34604,34605,34607,34608,34610,34611,34613,34614,34616,34617,34618,34620,34621,34624,34625,34626,34627,34628,34629,34630,34634,34635,34637,34639,34640,34641,34642,34644,34645,34646,34648,34650,34651,34652,34653,34654,34655,34657,34658,34662,34663,34664,34665,34666,34667,34668,34669,34671,34673,34674,34675,34677,34679,34680,34681,34682,34687,34688,34689,34692,34694,34695,34697,34698,34700,34702,34703,34704,34705,34706,34708,34709,34710,34712,34713,34714,34715,34716,34717,34718,34720,34721,34722,34723,34724,24013,24494,21361,38886,36829,26693,22260,21807,24799,20026,28493,32500,33479,33806,22996,20255,20266,23614,32428,26410,34074,21619,30031,32963,21890,39759,20301,28205,35859,23561,24944,21355,30239,28201,34442,25991,38395,32441,21563,31283,32010,38382,21985,32705,29934,25373,34583,28065,31389,25105,26017,21351,25569,27779,24043,21596,38056,20044,27745,35820,23627,26080,33436,26791,21566,21556,27595,27494,20116,25410,21320,33310,20237,20398,22366,25098,38654,26212,29289,21247,21153,24735,35823,26132,29081,26512,35199,30802,30717,26224,22075,21560,38177,29306,34725,34726,34727,34729,34730,34734,34736,34737,34738,34740,34742,34743,34744,34745,34747,34748,34750,34751,34753,34754,34755,34756,34757,34759,34760,34761,34764,34765,34766,34767,34768,34772,34773,34774,34775,34776,34777,34778,34780,34781,34782,34783,34785,34786,34787,34788,34790,34791,34792,34793,34795,34796,34797,34799,34800,34801,34802,34803,34804,34805,34806,34807,34808,34810,34811,34812,34813,34815,34816,34817,34818,34820,34821,34822,34823,34824,34825,34827,34828,34829,34830,34831,34832,34833,34834,34836,34839,34840,34841,34842,34844,34845,34846,34847,34848,34851,31232,24687,24076,24713,33181,22805,24796,29060,28911,28330,27728,29312,27268,34989,24109,20064,23219,21916,38115,27927,31995,38553,25103,32454,30606,34430,21283,38686,36758,26247,23777,20384,29421,19979,21414,22799,21523,25472,38184,20808,20185,40092,32420,21688,36132,34900,33335,38386,28046,24358,23244,26174,38505,29616,29486,21439,33146,39301,32673,23466,38519,38480,32447,30456,21410,38262,39321,31665,35140,28248,20065,32724,31077,35814,24819,21709,20139,39033,24055,27233,20687,21521,35937,33831,30813,38660,21066,21742,22179,38144,28040,23477,28102,26195,34852,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34867,34868,34869,34870,34871,34872,34874,34875,34877,34878,34879,34881,34882,34883,34886,34887,34888,34889,34890,34891,34894,34895,34896,34897,34898,34899,34901,34902,34904,34906,34907,34908,34909,34910,34911,34912,34918,34919,34922,34925,34927,34929,34931,34932,34933,34934,34936,34937,34938,34939,34940,34944,34947,34950,34951,34953,34954,34956,34958,34959,34960,34961,34963,34964,34965,34967,34968,34969,34970,34971,34973,34974,34975,34976,34977,34979,34981,34982,34983,34984,34985,34986,23567,23389,26657,32918,21880,31505,25928,26964,20123,27463,34638,38795,21327,25375,25658,37034,26012,32961,35856,20889,26800,21368,34809,25032,27844,27899,35874,23633,34218,33455,38156,27427,36763,26032,24571,24515,20449,34885,26143,33125,29481,24826,20852,21009,22411,24418,37026,34892,37266,24184,26447,24615,22995,20804,20982,33016,21256,27769,38596,29066,20241,20462,32670,26429,21957,38152,31168,34966,32483,22687,25100,38656,34394,22040,39035,24464,35768,33988,37207,21465,26093,24207,30044,24676,32110,23167,32490,32493,36713,21927,23459,24748,26059,29572,34988,34990,34991,34992,34994,34995,34996,34997,34998,35000,35001,35002,35003,35005,35006,35007,35008,35011,35012,35015,35016,35018,35019,35020,35021,35023,35024,35025,35027,35030,35031,35034,35035,35036,35037,35038,35040,35041,35046,35047,35049,35050,35051,35052,35053,35054,35055,35058,35061,35062,35063,35066,35067,35069,35071,35072,35073,35075,35076,35077,35078,35079,35080,35081,35083,35084,35085,35086,35087,35089,35092,35093,35094,35095,35096,35100,35101,35102,35103,35104,35106,35107,35108,35110,35111,35112,35113,35116,35117,35118,35119,35121,35122,35123,35125,35127,36873,30307,30505,32474,38772,34203,23398,31348,38634,34880,21195,29071,24490,26092,35810,23547,39535,24033,27529,27739,35757,35759,36874,36805,21387,25276,40486,40493,21568,20011,33469,29273,34460,23830,34905,28079,38597,21713,20122,35766,28937,21693,38409,28895,28153,30416,20005,30740,34578,23721,24310,35328,39068,38414,28814,27839,22852,25513,30524,34893,28436,33395,22576,29141,21388,30746,38593,21761,24422,28976,23476,35866,39564,27523,22830,40495,31207,26472,25196,20335,30113,32650,27915,38451,27687,20208,30162,20859,26679,28478,36992,33136,22934,29814,35128,35129,35130,35131,35132,35133,35134,35135,35136,35138,35139,35141,35142,35143,35144,35145,35146,35147,35148,35149,35150,35151,35152,35153,35154,35155,35156,35157,35158,35159,35160,35161,35162,35163,35164,35165,35168,35169,35170,35171,35172,35173,35175,35176,35177,35178,35179,35180,35181,35182,35183,35184,35185,35186,35187,35188,35189,35190,35191,35192,35193,35194,35196,35197,35198,35200,35202,35204,35205,35207,35208,35209,35210,35211,35212,35213,35214,35215,35216,35217,35218,35219,35220,35221,35222,35223,35224,35225,35226,35227,35228,35229,35230,35231,35232,35233,25671,23591,36965,31377,35875,23002,21676,33280,33647,35201,32768,26928,22094,32822,29239,37326,20918,20063,39029,25494,19994,21494,26355,33099,22812,28082,19968,22777,21307,25558,38129,20381,20234,34915,39056,22839,36951,31227,20202,33008,30097,27778,23452,23016,24413,26885,34433,20506,24050,20057,30691,20197,33402,25233,26131,37009,23673,20159,24441,33222,36920,32900,30123,20134,35028,24847,27589,24518,20041,30410,28322,35811,35758,35850,35793,24322,32764,32716,32462,33589,33643,22240,27575,38899,38452,23035,21535,38134,28139,23493,39278,23609,24341,38544,35234,35235,35236,35237,35238,35239,35240,35241,35242,35243,35244,35245,35246,35247,35248,35249,35250,35251,35252,35253,35254,35255,35256,35257,35258,35259,35260,35261,35262,35263,35264,35267,35277,35283,35284,35285,35287,35288,35289,35291,35293,35295,35296,35297,35298,35300,35303,35304,35305,35306,35308,35309,35310,35312,35313,35314,35316,35317,35318,35319,35320,35321,35322,35323,35324,35325,35326,35327,35329,35330,35331,35332,35333,35334,35336,35337,35338,35339,35340,35341,35342,35343,35344,35345,35346,35347,35348,35349,35350,35351,35352,35353,35354,35355,35356,35357,21360,33521,27185,23156,40560,24212,32552,33721,33828,33829,33639,34631,36814,36194,30408,24433,39062,30828,26144,21727,25317,20323,33219,30152,24248,38605,36362,34553,21647,27891,28044,27704,24703,21191,29992,24189,20248,24736,24551,23588,30001,37038,38080,29369,27833,28216,37193,26377,21451,21491,20305,37321,35825,21448,24188,36802,28132,20110,30402,27014,34398,24858,33286,20313,20446,36926,40060,24841,28189,28180,38533,20104,23089,38632,19982,23679,31161,23431,35821,32701,29577,22495,33419,37057,21505,36935,21947,23786,24481,24840,27442,29425,32946,35465,35358,35359,35360,35361,35362,35363,35364,35365,35366,35367,35368,35369,35370,35371,35372,35373,35374,35375,35376,35377,35378,35379,35380,35381,35382,35383,35384,35385,35386,35387,35388,35389,35391,35392,35393,35394,35395,35396,35397,35398,35399,35401,35402,35403,35404,35405,35406,35407,35408,35409,35410,35411,35412,35413,35414,35415,35416,35417,35418,35419,35420,35421,35422,35423,35424,35425,35426,35427,35428,35429,35430,35431,35432,35433,35434,35435,35436,35437,35438,35439,35440,35441,35442,35443,35444,35445,35446,35447,35448,35450,35451,35452,35453,35454,35455,35456,28020,23507,35029,39044,35947,39533,40499,28170,20900,20803,22435,34945,21407,25588,36757,22253,21592,22278,29503,28304,32536,36828,33489,24895,24616,38498,26352,32422,36234,36291,38053,23731,31908,26376,24742,38405,32792,20113,37095,21248,38504,20801,36816,34164,37213,26197,38901,23381,21277,30776,26434,26685,21705,28798,23472,36733,20877,22312,21681,25874,26242,36190,36163,33039,33900,36973,31967,20991,34299,26531,26089,28577,34468,36481,22122,36896,30338,28790,29157,36131,25321,21017,27901,36156,24590,22686,24974,26366,36192,25166,21939,28195,26413,36711,35457,35458,35459,35460,35461,35462,35463,35464,35467,35468,35469,35470,35471,35472,35473,35474,35476,35477,35478,35479,35480,35481,35482,35483,35484,35485,35486,35487,35488,35489,35490,35491,35492,35493,35494,35495,35496,35497,35498,35499,35500,35501,35502,35503,35504,35505,35506,35507,35508,35509,35510,35511,35512,35513,35514,35515,35516,35517,35518,35519,35520,35521,35522,35523,35524,35525,35526,35527,35528,35529,35530,35531,35532,35533,35534,35535,35536,35537,35538,35539,35540,35541,35542,35543,35544,35545,35546,35547,35548,35549,35550,35551,35552,35553,35554,35555,38113,38392,30504,26629,27048,21643,20045,28856,35784,25688,25995,23429,31364,20538,23528,30651,27617,35449,31896,27838,30415,26025,36759,23853,23637,34360,26632,21344,25112,31449,28251,32509,27167,31456,24432,28467,24352,25484,28072,26454,19976,24080,36134,20183,32960,30260,38556,25307,26157,25214,27836,36213,29031,32617,20806,32903,21484,36974,25240,21746,34544,36761,32773,38167,34071,36825,27993,29645,26015,30495,29956,30759,33275,36126,38024,20390,26517,30137,35786,38663,25391,38215,38453,33976,25379,30529,24449,29424,20105,24596,25972,25327,27491,25919,35556,35557,35558,35559,35560,35561,35562,35563,35564,35565,35566,35567,35568,35569,35570,35571,35572,35573,35574,35575,35576,35577,35578,35579,35580,35581,35582,35583,35584,35585,35586,35587,35588,35589,35590,35592,35593,35594,35595,35596,35597,35598,35599,35600,35601,35602,35603,35604,35605,35606,35607,35608,35609,35610,35611,35612,35613,35614,35615,35616,35617,35618,35619,35620,35621,35623,35624,35625,35626,35627,35628,35629,35630,35631,35632,35633,35634,35635,35636,35637,35638,35639,35640,35641,35642,35643,35644,35645,35646,35647,35648,35649,35650,35651,35652,35653,24103,30151,37073,35777,33437,26525,25903,21553,34584,30693,32930,33026,27713,20043,32455,32844,30452,26893,27542,25191,20540,20356,22336,25351,27490,36286,21482,26088,32440,24535,25370,25527,33267,33268,32622,24092,23769,21046,26234,31209,31258,36136,28825,30164,28382,27835,31378,20013,30405,24544,38047,34935,32456,31181,32959,37325,20210,20247,33311,21608,24030,27954,35788,31909,36724,32920,24090,21650,30385,23449,26172,39588,29664,26666,34523,26417,29482,35832,35803,36880,31481,28891,29038,25284,30633,22065,20027,33879,26609,21161,34496,36142,38136,31569,35654,35655,35656,35657,35658,35659,35660,35661,35662,35663,35664,35665,35666,35667,35668,35669,35670,35671,35672,35673,35674,35675,35676,35677,35678,35679,35680,35681,35682,35683,35684,35685,35687,35688,35689,35690,35691,35693,35694,35695,35696,35697,35698,35699,35700,35701,35702,35703,35704,35705,35706,35707,35708,35709,35710,35711,35712,35713,35714,35715,35716,35717,35718,35719,35720,35721,35722,35723,35724,35725,35726,35727,35728,35729,35730,35731,35732,35733,35734,35735,35736,35737,35738,35739,35740,35741,35742,35743,35756,35761,35771,35783,35792,35818,35849,35870,20303,27880,31069,39547,25235,29226,25341,19987,30742,36716,25776,36186,31686,26729,24196,35013,22918,25758,22766,29366,26894,38181,36861,36184,22368,32512,35846,20934,25417,25305,21331,26700,29730,33537,37196,21828,30528,28796,27978,20857,21672,36164,23039,28363,28100,23388,32043,20180,31869,28371,23376,33258,28173,23383,39683,26837,36394,23447,32508,24635,32437,37049,36208,22863,25549,31199,36275,21330,26063,31062,35781,38459,32452,38075,32386,22068,37257,26368,32618,23562,36981,26152,24038,20304,26590,20570,20316,22352,24231,59408,59409,59410,59411,59412,35896,35897,35898,35899,35900,35901,35902,35903,35904,35906,35907,35908,35909,35912,35914,35915,35917,35918,35919,35920,35921,35922,35923,35924,35926,35927,35928,35929,35931,35932,35933,35934,35935,35936,35939,35940,35941,35942,35943,35944,35945,35948,35949,35950,35951,35952,35953,35954,35956,35957,35958,35959,35963,35964,35965,35966,35967,35968,35969,35971,35972,35974,35975,35976,35979,35981,35982,35983,35984,35985,35986,35987,35989,35990,35991,35993,35994,35995,35996,35997,35998,35999,36000,36001,36002,36003,36004,36005,36006,36007,36008,36009,36010,36011,36012,36013,20109,19980,20800,19984,24319,21317,19989,20120,19998,39730,23404,22121,20008,31162,20031,21269,20039,22829,29243,21358,27664,22239,32996,39319,27603,30590,40727,20022,20127,40720,20060,20073,20115,33416,23387,21868,22031,20164,21389,21405,21411,21413,21422,38757,36189,21274,21493,21286,21294,21310,36188,21350,21347,20994,21000,21006,21037,21043,21055,21056,21068,21086,21089,21084,33967,21117,21122,21121,21136,21139,20866,32596,20155,20163,20169,20162,20200,20193,20203,20190,20251,20211,20258,20324,20213,20261,20263,20233,20267,20318,20327,25912,20314,20317,36014,36015,36016,36017,36018,36019,36020,36021,36022,36023,36024,36025,36026,36027,36028,36029,36030,36031,36032,36033,36034,36035,36036,36037,36038,36039,36040,36041,36042,36043,36044,36045,36046,36047,36048,36049,36050,36051,36052,36053,36054,36055,36056,36057,36058,36059,36060,36061,36062,36063,36064,36065,36066,36067,36068,36069,36070,36071,36072,36073,36074,36075,36076,36077,36078,36079,36080,36081,36082,36083,36084,36085,36086,36087,36088,36089,36090,36091,36092,36093,36094,36095,36096,36097,36098,36099,36100,36101,36102,36103,36104,36105,36106,36107,36108,36109,20319,20311,20274,20285,20342,20340,20369,20361,20355,20367,20350,20347,20394,20348,20396,20372,20454,20456,20458,20421,20442,20451,20444,20433,20447,20472,20521,20556,20467,20524,20495,20526,20525,20478,20508,20492,20517,20520,20606,20547,20565,20552,20558,20588,20603,20645,20647,20649,20666,20694,20742,20717,20716,20710,20718,20743,20747,20189,27709,20312,20325,20430,40864,27718,31860,20846,24061,40649,39320,20865,22804,21241,21261,35335,21264,20971,22809,20821,20128,20822,20147,34926,34980,20149,33044,35026,31104,23348,34819,32696,20907,20913,20925,20924,36110,36111,36112,36113,36114,36115,36116,36117,36118,36119,36120,36121,36122,36123,36124,36128,36177,36178,36183,36191,36197,36200,36201,36202,36204,36206,36207,36209,36210,36216,36217,36218,36219,36220,36221,36222,36223,36224,36226,36227,36230,36231,36232,36233,36236,36237,36238,36239,36240,36242,36243,36245,36246,36247,36248,36249,36250,36251,36252,36253,36254,36256,36257,36258,36260,36261,36262,36263,36264,36265,36266,36267,36268,36269,36270,36271,36272,36274,36278,36279,36281,36283,36285,36288,36289,36290,36293,36295,36296,36297,36298,36301,36304,36306,36307,36308,20935,20886,20898,20901,35744,35750,35751,35754,35764,35765,35767,35778,35779,35787,35791,35790,35794,35795,35796,35798,35800,35801,35804,35807,35808,35812,35816,35817,35822,35824,35827,35830,35833,35836,35839,35840,35842,35844,35847,35852,35855,35857,35858,35860,35861,35862,35865,35867,35864,35869,35871,35872,35873,35877,35879,35882,35883,35886,35887,35890,35891,35893,35894,21353,21370,38429,38434,38433,38449,38442,38461,38460,38466,38473,38484,38495,38503,38508,38514,38516,38536,38541,38551,38576,37015,37019,37021,37017,37036,37025,37044,37043,37046,37050,36309,36312,36313,36316,36320,36321,36322,36325,36326,36327,36329,36333,36334,36336,36337,36338,36340,36342,36348,36350,36351,36352,36353,36354,36355,36356,36358,36359,36360,36363,36365,36366,36368,36369,36370,36371,36373,36374,36375,36376,36377,36378,36379,36380,36384,36385,36388,36389,36390,36391,36392,36395,36397,36400,36402,36403,36404,36406,36407,36408,36411,36412,36414,36415,36419,36421,36422,36428,36429,36430,36431,36432,36435,36436,36437,36438,36439,36440,36442,36443,36444,36445,36446,36447,36448,36449,36450,36451,36452,36453,36455,36456,36458,36459,36462,36465,37048,37040,37071,37061,37054,37072,37060,37063,37075,37094,37090,37084,37079,37083,37099,37103,37118,37124,37154,37150,37155,37169,37167,37177,37187,37190,21005,22850,21154,21164,21165,21182,21759,21200,21206,21232,21471,29166,30669,24308,20981,20988,39727,21430,24321,30042,24047,22348,22441,22433,22654,22716,22725,22737,22313,22316,22314,22323,22329,22318,22319,22364,22331,22338,22377,22405,22379,22406,22396,22395,22376,22381,22390,22387,22445,22436,22412,22450,22479,22439,22452,22419,22432,22485,22488,22490,22489,22482,22456,22516,22511,22520,22500,22493,36467,36469,36471,36472,36473,36474,36475,36477,36478,36480,36482,36483,36484,36486,36488,36489,36490,36491,36492,36493,36494,36497,36498,36499,36501,36502,36503,36504,36505,36506,36507,36509,36511,36512,36513,36514,36515,36516,36517,36518,36519,36520,36521,36522,36525,36526,36528,36529,36531,36532,36533,36534,36535,36536,36537,36539,36540,36541,36542,36543,36544,36545,36546,36547,36548,36549,36550,36551,36552,36553,36554,36555,36556,36557,36559,36560,36561,36562,36563,36564,36565,36566,36567,36568,36569,36570,36571,36572,36573,36574,36575,36576,36577,36578,36579,36580,22539,22541,22525,22509,22528,22558,22553,22596,22560,22629,22636,22657,22665,22682,22656,39336,40729,25087,33401,33405,33407,33423,33418,33448,33412,33422,33425,33431,33433,33451,33464,33470,33456,33480,33482,33507,33432,33463,33454,33483,33484,33473,33449,33460,33441,33450,33439,33476,33486,33444,33505,33545,33527,33508,33551,33543,33500,33524,33490,33496,33548,33531,33491,33553,33562,33542,33556,33557,33504,33493,33564,33617,33627,33628,33544,33682,33596,33588,33585,33691,33630,33583,33615,33607,33603,33631,33600,33559,33632,33581,33594,33587,33638,33637,36581,36582,36583,36584,36585,36586,36587,36588,36589,36590,36591,36592,36593,36594,36595,36596,36597,36598,36599,36600,36601,36602,36603,36604,36605,36606,36607,36608,36609,36610,36611,36612,36613,36614,36615,36616,36617,36618,36619,36620,36621,36622,36623,36624,36625,36626,36627,36628,36629,36630,36631,36632,36633,36634,36635,36636,36637,36638,36639,36640,36641,36642,36643,36644,36645,36646,36647,36648,36649,36650,36651,36652,36653,36654,36655,36656,36657,36658,36659,36660,36661,36662,36663,36664,36665,36666,36667,36668,36669,36670,36671,36672,36673,36674,36675,36676,33640,33563,33641,33644,33642,33645,33646,33712,33656,33715,33716,33696,33706,33683,33692,33669,33660,33718,33705,33661,33720,33659,33688,33694,33704,33722,33724,33729,33793,33765,33752,22535,33816,33803,33757,33789,33750,33820,33848,33809,33798,33748,33759,33807,33795,33784,33785,33770,33733,33728,33830,33776,33761,33884,33873,33882,33881,33907,33927,33928,33914,33929,33912,33852,33862,33897,33910,33932,33934,33841,33901,33985,33997,34000,34022,33981,34003,33994,33983,33978,34016,33953,33977,33972,33943,34021,34019,34060,29965,34104,34032,34105,34079,34106,36677,36678,36679,36680,36681,36682,36683,36684,36685,36686,36687,36688,36689,36690,36691,36692,36693,36694,36695,36696,36697,36698,36699,36700,36701,36702,36703,36704,36705,36706,36707,36708,36709,36714,36736,36748,36754,36765,36768,36769,36770,36772,36773,36774,36775,36778,36780,36781,36782,36783,36786,36787,36788,36789,36791,36792,36794,36795,36796,36799,36800,36803,36806,36809,36810,36811,36812,36813,36815,36818,36822,36823,36826,36832,36833,36835,36839,36844,36847,36849,36850,36852,36853,36854,36858,36859,36860,36862,36863,36871,36872,36876,36878,36883,36885,36888,34134,34107,34047,34044,34137,34120,34152,34148,34142,34170,30626,34115,34162,34171,34212,34216,34183,34191,34169,34222,34204,34181,34233,34231,34224,34259,34241,34268,34303,34343,34309,34345,34326,34364,24318,24328,22844,22849,32823,22869,22874,22872,21263,23586,23589,23596,23604,25164,25194,25247,25275,25290,25306,25303,25326,25378,25334,25401,25419,25411,25517,25590,25457,25466,25486,25524,25453,25516,25482,25449,25518,25532,25586,25592,25568,25599,25540,25566,25550,25682,25542,25534,25669,25665,25611,25627,25632,25612,25638,25633,25694,25732,25709,25750,36889,36892,36899,36900,36901,36903,36904,36905,36906,36907,36908,36912,36913,36914,36915,36916,36919,36921,36922,36925,36927,36928,36931,36933,36934,36936,36937,36938,36939,36940,36942,36948,36949,36950,36953,36954,36956,36957,36958,36959,36960,36961,36964,36966,36967,36969,36970,36971,36972,36975,36976,36977,36978,36979,36982,36983,36984,36985,36986,36987,36988,36990,36993,36996,36997,36998,36999,37001,37002,37004,37005,37006,37007,37008,37010,37012,37014,37016,37018,37020,37022,37023,37024,37028,37029,37031,37032,37033,37035,37037,37042,37047,37052,37053,37055,37056,25722,25783,25784,25753,25786,25792,25808,25815,25828,25826,25865,25893,25902,24331,24530,29977,24337,21343,21489,21501,21481,21480,21499,21522,21526,21510,21579,21586,21587,21588,21590,21571,21537,21591,21593,21539,21554,21634,21652,21623,21617,21604,21658,21659,21636,21622,21606,21661,21712,21677,21698,21684,21714,21671,21670,21715,21716,21618,21667,21717,21691,21695,21708,21721,21722,21724,21673,21674,21668,21725,21711,21726,21787,21735,21792,21757,21780,21747,21794,21795,21775,21777,21799,21802,21863,21903,21941,21833,21869,21825,21845,21823,21840,21820,37058,37059,37062,37064,37065,37067,37068,37069,37074,37076,37077,37078,37080,37081,37082,37086,37087,37088,37091,37092,37093,37097,37098,37100,37102,37104,37105,37106,37107,37109,37110,37111,37113,37114,37115,37116,37119,37120,37121,37123,37125,37126,37127,37128,37129,37130,37131,37132,37133,37134,37135,37136,37137,37138,37139,37140,37141,37142,37143,37144,37146,37147,37148,37149,37151,37152,37153,37156,37157,37158,37159,37160,37161,37162,37163,37164,37165,37166,37168,37170,37171,37172,37173,37174,37175,37176,37178,37179,37180,37181,37182,37183,37184,37185,37186,37188,21815,21846,21877,21878,21879,21811,21808,21852,21899,21970,21891,21937,21945,21896,21889,21919,21886,21974,21905,21883,21983,21949,21950,21908,21913,21994,22007,21961,22047,21969,21995,21996,21972,21990,21981,21956,21999,21989,22002,22003,21964,21965,21992,22005,21988,36756,22046,22024,22028,22017,22052,22051,22014,22016,22055,22061,22104,22073,22103,22060,22093,22114,22105,22108,22092,22100,22150,22116,22129,22123,22139,22140,22149,22163,22191,22228,22231,22237,22241,22261,22251,22265,22271,22276,22282,22281,22300,24079,24089,24084,24081,24113,24123,24124,37189,37191,37192,37201,37203,37204,37205,37206,37208,37209,37211,37212,37215,37216,37222,37223,37224,37227,37229,37235,37242,37243,37244,37248,37249,37250,37251,37252,37254,37256,37258,37262,37263,37267,37268,37269,37270,37271,37272,37273,37276,37277,37278,37279,37280,37281,37284,37285,37286,37287,37288,37289,37291,37292,37296,37297,37298,37299,37302,37303,37304,37305,37307,37308,37309,37310,37311,37312,37313,37314,37315,37316,37317,37318,37320,37323,37328,37330,37331,37332,37333,37334,37335,37336,37337,37338,37339,37341,37342,37343,37344,37345,37346,37347,37348,37349,24119,24132,24148,24155,24158,24161,23692,23674,23693,23696,23702,23688,23704,23705,23697,23706,23708,23733,23714,23741,23724,23723,23729,23715,23745,23735,23748,23762,23780,23755,23781,23810,23811,23847,23846,23854,23844,23838,23814,23835,23896,23870,23860,23869,23916,23899,23919,23901,23915,23883,23882,23913,23924,23938,23961,23965,35955,23991,24005,24435,24439,24450,24455,24457,24460,24469,24473,24476,24488,24493,24501,24508,34914,24417,29357,29360,29364,29367,29368,29379,29377,29390,29389,29394,29416,29423,29417,29426,29428,29431,29441,29427,29443,29434,37350,37351,37352,37353,37354,37355,37356,37357,37358,37359,37360,37361,37362,37363,37364,37365,37366,37367,37368,37369,37370,37371,37372,37373,37374,37375,37376,37377,37378,37379,37380,37381,37382,37383,37384,37385,37386,37387,37388,37389,37390,37391,37392,37393,37394,37395,37396,37397,37398,37399,37400,37401,37402,37403,37404,37405,37406,37407,37408,37409,37410,37411,37412,37413,37414,37415,37416,37417,37418,37419,37420,37421,37422,37423,37424,37425,37426,37427,37428,37429,37430,37431,37432,37433,37434,37435,37436,37437,37438,37439,37440,37441,37442,37443,37444,37445,29435,29463,29459,29473,29450,29470,29469,29461,29474,29497,29477,29484,29496,29489,29520,29517,29527,29536,29548,29551,29566,33307,22821,39143,22820,22786,39267,39271,39272,39273,39274,39275,39276,39284,39287,39293,39296,39300,39303,39306,39309,39312,39313,39315,39316,39317,24192,24209,24203,24214,24229,24224,24249,24245,24254,24243,36179,24274,24273,24283,24296,24298,33210,24516,24521,24534,24527,24579,24558,24580,24545,24548,24574,24581,24582,24554,24557,24568,24601,24629,24614,24603,24591,24589,24617,24619,24586,24639,24609,24696,24697,24699,24698,24642,37446,37447,37448,37449,37450,37451,37452,37453,37454,37455,37456,37457,37458,37459,37460,37461,37462,37463,37464,37465,37466,37467,37468,37469,37470,37471,37472,37473,37474,37475,37476,37477,37478,37479,37480,37481,37482,37483,37484,37485,37486,37487,37488,37489,37490,37491,37493,37494,37495,37496,37497,37498,37499,37500,37501,37502,37503,37504,37505,37506,37507,37508,37509,37510,37511,37512,37513,37514,37515,37516,37517,37519,37520,37521,37522,37523,37524,37525,37526,37527,37528,37529,37530,37531,37532,37533,37534,37535,37536,37537,37538,37539,37540,37541,37542,37543,24682,24701,24726,24730,24749,24733,24707,24722,24716,24731,24812,24763,24753,24797,24792,24774,24794,24756,24864,24870,24853,24867,24820,24832,24846,24875,24906,24949,25004,24980,24999,25015,25044,25077,24541,38579,38377,38379,38385,38387,38389,38390,38396,38398,38403,38404,38406,38408,38410,38411,38412,38413,38415,38418,38421,38422,38423,38425,38426,20012,29247,25109,27701,27732,27740,27722,27811,27781,27792,27796,27788,27752,27753,27764,27766,27782,27817,27856,27860,27821,27895,27896,27889,27863,27826,27872,27862,27898,27883,27886,27825,27859,27887,27902,37544,37545,37546,37547,37548,37549,37551,37552,37553,37554,37555,37556,37557,37558,37559,37560,37561,37562,37563,37564,37565,37566,37567,37568,37569,37570,37571,37572,37573,37574,37575,37577,37578,37579,37580,37581,37582,37583,37584,37585,37586,37587,37588,37589,37590,37591,37592,37593,37594,37595,37596,37597,37598,37599,37600,37601,37602,37603,37604,37605,37606,37607,37608,37609,37610,37611,37612,37613,37614,37615,37616,37617,37618,37619,37620,37621,37622,37623,37624,37625,37626,37627,37628,37629,37630,37631,37632,37633,37634,37635,37636,37637,37638,37639,37640,37641,27961,27943,27916,27971,27976,27911,27908,27929,27918,27947,27981,27950,27957,27930,27983,27986,27988,27955,28049,28015,28062,28064,27998,28051,28052,27996,28000,28028,28003,28186,28103,28101,28126,28174,28095,28128,28177,28134,28125,28121,28182,28075,28172,28078,28203,28270,28238,28267,28338,28255,28294,28243,28244,28210,28197,28228,28383,28337,28312,28384,28461,28386,28325,28327,28349,28347,28343,28375,28340,28367,28303,28354,28319,28514,28486,28487,28452,28437,28409,28463,28470,28491,28532,28458,28425,28457,28553,28557,28556,28536,28530,28540,28538,28625,37642,37643,37644,37645,37646,37647,37648,37649,37650,37651,37652,37653,37654,37655,37656,37657,37658,37659,37660,37661,37662,37663,37664,37665,37666,37667,37668,37669,37670,37671,37672,37673,37674,37675,37676,37677,37678,37679,37680,37681,37682,37683,37684,37685,37686,37687,37688,37689,37690,37691,37692,37693,37695,37696,37697,37698,37699,37700,37701,37702,37703,37704,37705,37706,37707,37708,37709,37710,37711,37712,37713,37714,37715,37716,37717,37718,37719,37720,37721,37722,37723,37724,37725,37726,37727,37728,37729,37730,37731,37732,37733,37734,37735,37736,37737,37739,28617,28583,28601,28598,28610,28641,28654,28638,28640,28655,28698,28707,28699,28729,28725,28751,28766,23424,23428,23445,23443,23461,23480,29999,39582,25652,23524,23534,35120,23536,36423,35591,36790,36819,36821,36837,36846,36836,36841,36838,36851,36840,36869,36868,36875,36902,36881,36877,36886,36897,36917,36918,36909,36911,36932,36945,36946,36944,36968,36952,36962,36955,26297,36980,36989,36994,37000,36995,37003,24400,24407,24406,24408,23611,21675,23632,23641,23409,23651,23654,32700,24362,24361,24365,33396,24380,39739,23662,22913,22915,22925,22953,22954,22947,37740,37741,37742,37743,37744,37745,37746,37747,37748,37749,37750,37751,37752,37753,37754,37755,37756,37757,37758,37759,37760,37761,37762,37763,37764,37765,37766,37767,37768,37769,37770,37771,37772,37773,37774,37776,37777,37778,37779,37780,37781,37782,37783,37784,37785,37786,37787,37788,37789,37790,37791,37792,37793,37794,37795,37796,37797,37798,37799,37800,37801,37802,37803,37804,37805,37806,37807,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,37822,37823,37824,37825,37826,37827,37828,37829,37830,37831,37832,37833,37835,37836,37837,22935,22986,22955,22942,22948,22994,22962,22959,22999,22974,23045,23046,23005,23048,23011,23000,23033,23052,23049,23090,23092,23057,23075,23059,23104,23143,23114,23125,23100,23138,23157,33004,23210,23195,23159,23162,23230,23275,23218,23250,23252,23224,23264,23267,23281,23254,23270,23256,23260,23305,23319,23318,23346,23351,23360,23573,23580,23386,23397,23411,23377,23379,23394,39541,39543,39544,39546,39551,39549,39552,39553,39557,39560,39562,39568,39570,39571,39574,39576,39579,39580,39581,39583,39584,39586,39587,39589,39591,32415,32417,32419,32421,32424,32425,37838,37839,37840,37841,37842,37843,37844,37845,37847,37848,37849,37850,37851,37852,37853,37854,37855,37856,37857,37858,37859,37860,37861,37862,37863,37864,37865,37866,37867,37868,37869,37870,37871,37872,37873,37874,37875,37876,37877,37878,37879,37880,37881,37882,37883,37884,37885,37886,37887,37888,37889,37890,37891,37892,37893,37894,37895,37896,37897,37898,37899,37900,37901,37902,37903,37904,37905,37906,37907,37908,37909,37910,37911,37912,37913,37914,37915,37916,37917,37918,37919,37920,37921,37922,37923,37924,37925,37926,37927,37928,37929,37930,37931,37932,37933,37934,32429,32432,32446,32448,32449,32450,32457,32459,32460,32464,32468,32471,32475,32480,32481,32488,32491,32494,32495,32497,32498,32525,32502,32506,32507,32510,32513,32514,32515,32519,32520,32523,32524,32527,32529,32530,32535,32537,32540,32539,32543,32545,32546,32547,32548,32549,32550,32551,32554,32555,32556,32557,32559,32560,32561,32562,32563,32565,24186,30079,24027,30014,37013,29582,29585,29614,29602,29599,29647,29634,29649,29623,29619,29632,29641,29640,29669,29657,39036,29706,29673,29671,29662,29626,29682,29711,29738,29787,29734,29733,29736,29744,29742,29740,37935,37936,37937,37938,37939,37940,37941,37942,37943,37944,37945,37946,37947,37948,37949,37951,37952,37953,37954,37955,37956,37957,37958,37959,37960,37961,37962,37963,37964,37965,37966,37967,37968,37969,37970,37971,37972,37973,37974,37975,37976,37977,37978,37979,37980,37981,37982,37983,37984,37985,37986,37987,37988,37989,37990,37991,37992,37993,37994,37996,37997,37998,37999,38000,38001,38002,38003,38004,38005,38006,38007,38008,38009,38010,38011,38012,38013,38014,38015,38016,38017,38018,38019,38020,38033,38038,38040,38087,38095,38099,38100,38106,38118,38139,38172,38176,29723,29722,29761,29788,29783,29781,29785,29815,29805,29822,29852,29838,29824,29825,29831,29835,29854,29864,29865,29840,29863,29906,29882,38890,38891,38892,26444,26451,26462,26440,26473,26533,26503,26474,26483,26520,26535,26485,26536,26526,26541,26507,26487,26492,26608,26633,26584,26634,26601,26544,26636,26585,26549,26586,26547,26589,26624,26563,26552,26594,26638,26561,26621,26674,26675,26720,26721,26702,26722,26692,26724,26755,26653,26709,26726,26689,26727,26688,26686,26698,26697,26665,26805,26767,26740,26743,26771,26731,26818,26990,26876,26911,26912,26873,38183,38195,38205,38211,38216,38219,38229,38234,38240,38254,38260,38261,38263,38264,38265,38266,38267,38268,38269,38270,38272,38273,38274,38275,38276,38277,38278,38279,38280,38281,38282,38283,38284,38285,38286,38287,38288,38289,38290,38291,38292,38293,38294,38295,38296,38297,38298,38299,38300,38301,38302,38303,38304,38305,38306,38307,38308,38309,38310,38311,38312,38313,38314,38315,38316,38317,38318,38319,38320,38321,38322,38323,38324,38325,38326,38327,38328,38329,38330,38331,38332,38333,38334,38335,38336,38337,38338,38339,38340,38341,38342,38343,38344,38345,38346,38347,26916,26864,26891,26881,26967,26851,26896,26993,26937,26976,26946,26973,27012,26987,27008,27032,27000,26932,27084,27015,27016,27086,27017,26982,26979,27001,27035,27047,27067,27051,27053,27092,27057,27073,27082,27103,27029,27104,27021,27135,27183,27117,27159,27160,27237,27122,27204,27198,27296,27216,27227,27189,27278,27257,27197,27176,27224,27260,27281,27280,27305,27287,27307,29495,29522,27521,27522,27527,27524,27538,27539,27533,27546,27547,27553,27562,36715,36717,36721,36722,36723,36725,36726,36728,36727,36729,36730,36732,36734,36737,36738,36740,36743,36747,38348,38349,38350,38351,38352,38353,38354,38355,38356,38357,38358,38359,38360,38361,38362,38363,38364,38365,38366,38367,38368,38369,38370,38371,38372,38373,38374,38375,38380,38399,38407,38419,38424,38427,38430,38432,38435,38436,38437,38438,38439,38440,38441,38443,38444,38445,38447,38448,38455,38456,38457,38458,38462,38465,38467,38474,38478,38479,38481,38482,38483,38486,38487,38488,38489,38490,38492,38493,38494,38496,38499,38501,38502,38507,38509,38510,38511,38512,38513,38515,38520,38521,38522,38523,38524,38525,38526,38527,38528,38529,38530,38531,38532,38535,38537,38538,36749,36750,36751,36760,36762,36558,25099,25111,25115,25119,25122,25121,25125,25124,25132,33255,29935,29940,29951,29967,29969,29971,25908,26094,26095,26096,26122,26137,26482,26115,26133,26112,28805,26359,26141,26164,26161,26166,26165,32774,26207,26196,26177,26191,26198,26209,26199,26231,26244,26252,26279,26269,26302,26331,26332,26342,26345,36146,36147,36150,36155,36157,36160,36165,36166,36168,36169,36167,36173,36181,36185,35271,35274,35275,35276,35278,35279,35280,35281,29294,29343,29277,29286,29295,29310,29311,29316,29323,29325,29327,29330,25352,25394,25520,38540,38542,38545,38546,38547,38549,38550,38554,38555,38557,38558,38559,38560,38561,38562,38563,38564,38565,38566,38568,38569,38570,38571,38572,38573,38574,38575,38577,38578,38580,38581,38583,38584,38586,38587,38591,38594,38595,38600,38602,38603,38608,38609,38611,38612,38614,38615,38616,38617,38618,38619,38620,38621,38622,38623,38625,38626,38627,38628,38629,38630,38631,38635,38636,38637,38638,38640,38641,38642,38644,38645,38648,38650,38651,38652,38653,38655,38658,38659,38661,38666,38667,38668,38672,38673,38674,38676,38677,38679,38680,38681,38682,38683,38685,38687,38688,25663,25816,32772,27626,27635,27645,27637,27641,27653,27655,27654,27661,27669,27672,27673,27674,27681,27689,27684,27690,27698,25909,25941,25963,29261,29266,29270,29232,34402,21014,32927,32924,32915,32956,26378,32957,32945,32939,32941,32948,32951,32999,33000,33001,33002,32987,32962,32964,32985,32973,32983,26384,32989,33003,33009,33012,33005,33037,33038,33010,33020,26389,33042,35930,33078,33054,33068,33048,33074,33096,33100,33107,33140,33113,33114,33137,33120,33129,33148,33149,33133,33127,22605,23221,33160,33154,33169,28373,33187,33194,33228,26406,33226,33211,38689,38690,38691,38692,38693,38694,38695,38696,38697,38699,38700,38702,38703,38705,38707,38708,38709,38710,38711,38714,38715,38716,38717,38719,38720,38721,38722,38723,38724,38725,38726,38727,38728,38729,38730,38731,38732,38733,38734,38735,38736,38737,38740,38741,38743,38744,38746,38748,38749,38751,38755,38756,38758,38759,38760,38762,38763,38764,38765,38766,38767,38768,38769,38770,38773,38775,38776,38777,38778,38779,38781,38782,38783,38784,38785,38786,38787,38788,38790,38791,38792,38793,38794,38796,38798,38799,38800,38803,38805,38806,38807,38809,38810,38811,38812,38813,33217,33190,27428,27447,27449,27459,27462,27481,39121,39122,39123,39125,39129,39130,27571,24384,27586,35315,26000,40785,26003,26044,26054,26052,26051,26060,26062,26066,26070,28800,28828,28822,28829,28859,28864,28855,28843,28849,28904,28874,28944,28947,28950,28975,28977,29043,29020,29032,28997,29042,29002,29048,29050,29080,29107,29109,29096,29088,29152,29140,29159,29177,29213,29224,28780,28952,29030,29113,25150,25149,25155,25160,25161,31035,31040,31046,31049,31067,31068,31059,31066,31074,31063,31072,31087,31079,31098,31109,31114,31130,31143,31155,24529,24528,38814,38815,38817,38818,38820,38821,38822,38823,38824,38825,38826,38828,38830,38832,38833,38835,38837,38838,38839,38840,38841,38842,38843,38844,38845,38846,38847,38848,38849,38850,38851,38852,38853,38854,38855,38856,38857,38858,38859,38860,38861,38862,38863,38864,38865,38866,38867,38868,38869,38870,38871,38872,38873,38874,38875,38876,38877,38878,38879,38880,38881,38882,38883,38884,38885,38888,38894,38895,38896,38897,38898,38900,38903,38904,38905,38906,38907,38908,38909,38910,38911,38912,38913,38914,38915,38916,38917,38918,38919,38920,38921,38922,38923,38924,38925,38926,24636,24669,24666,24679,24641,24665,24675,24747,24838,24845,24925,25001,24989,25035,25041,25094,32896,32895,27795,27894,28156,30710,30712,30720,30729,30743,30744,30737,26027,30765,30748,30749,30777,30778,30779,30751,30780,30757,30764,30755,30761,30798,30829,30806,30807,30758,30800,30791,30796,30826,30875,30867,30874,30855,30876,30881,30883,30898,30905,30885,30932,30937,30921,30956,30962,30981,30964,30995,31012,31006,31028,40859,40697,40699,40700,30449,30468,30477,30457,30471,30472,30490,30498,30489,30509,30502,30517,30520,30544,30545,30535,30531,30554,30568,38927,38928,38929,38930,38931,38932,38933,38934,38935,38936,38937,38938,38939,38940,38941,38942,38943,38944,38945,38946,38947,38948,38949,38950,38951,38952,38953,38954,38955,38956,38957,38958,38959,38960,38961,38962,38963,38964,38965,38966,38967,38968,38969,38970,38971,38972,38973,38974,38975,38976,38977,38978,38979,38980,38981,38982,38983,38984,38985,38986,38987,38988,38989,38990,38991,38992,38993,38994,38995,38996,38997,38998,38999,39000,39001,39002,39003,39004,39005,39006,39007,39008,39009,39010,39011,39012,39013,39014,39015,39016,39017,39018,39019,39020,39021,39022,30562,30565,30591,30605,30589,30592,30604,30609,30623,30624,30640,30645,30653,30010,30016,30030,30027,30024,30043,30066,30073,30083,32600,32609,32607,35400,32616,32628,32625,32633,32641,32638,30413,30437,34866,38021,38022,38023,38027,38026,38028,38029,38031,38032,38036,38039,38037,38042,38043,38044,38051,38052,38059,38058,38061,38060,38063,38064,38066,38068,38070,38071,38072,38073,38074,38076,38077,38079,38084,38088,38089,38090,38091,38092,38093,38094,38096,38097,38098,38101,38102,38103,38105,38104,38107,38110,38111,38112,38114,38116,38117,38119,38120,38122,39023,39024,39025,39026,39027,39028,39051,39054,39058,39061,39065,39075,39080,39081,39082,39083,39084,39085,39086,39087,39088,39089,39090,39091,39092,39093,39094,39095,39096,39097,39098,39099,39100,39101,39102,39103,39104,39105,39106,39107,39108,39109,39110,39111,39112,39113,39114,39115,39116,39117,39119,39120,39124,39126,39127,39131,39132,39133,39136,39137,39138,39139,39140,39141,39142,39145,39146,39147,39148,39149,39150,39151,39152,39153,39154,39155,39156,39157,39158,39159,39160,39161,39162,39163,39164,39165,39166,39167,39168,39169,39170,39171,39172,39173,39174,39175,38121,38123,38126,38127,38131,38132,38133,38135,38137,38140,38141,38143,38147,38146,38150,38151,38153,38154,38157,38158,38159,38162,38163,38164,38165,38166,38168,38171,38173,38174,38175,38178,38186,38187,38185,38188,38193,38194,38196,38198,38199,38200,38204,38206,38207,38210,38197,38212,38213,38214,38217,38220,38222,38223,38226,38227,38228,38230,38231,38232,38233,38235,38238,38239,38237,38241,38242,38244,38245,38246,38247,38248,38249,38250,38251,38252,38255,38257,38258,38259,38202,30695,30700,38601,31189,31213,31203,31211,31238,23879,31235,31234,31262,31252,39176,39177,39178,39179,39180,39182,39183,39185,39186,39187,39188,39189,39190,39191,39192,39193,39194,39195,39196,39197,39198,39199,39200,39201,39202,39203,39204,39205,39206,39207,39208,39209,39210,39211,39212,39213,39215,39216,39217,39218,39219,39220,39221,39222,39223,39224,39225,39226,39227,39228,39229,39230,39231,39232,39233,39234,39235,39236,39237,39238,39239,39240,39241,39242,39243,39244,39245,39246,39247,39248,39249,39250,39251,39254,39255,39256,39257,39258,39259,39260,39261,39262,39263,39264,39265,39266,39268,39270,39283,39288,39289,39291,39294,39298,39299,39305,31289,31287,31313,40655,39333,31344,30344,30350,30355,30361,30372,29918,29920,29996,40480,40482,40488,40489,40490,40491,40492,40498,40497,40502,40504,40503,40505,40506,40510,40513,40514,40516,40518,40519,40520,40521,40523,40524,40526,40529,40533,40535,40538,40539,40540,40542,40547,40550,40551,40552,40553,40554,40555,40556,40561,40557,40563,30098,30100,30102,30112,30109,30124,30115,30131,30132,30136,30148,30129,30128,30147,30146,30166,30157,30179,30184,30182,30180,30187,30183,30211,30193,30204,30207,30224,30208,30213,30220,30231,30218,30245,30232,30229,30233,39308,39310,39322,39323,39324,39325,39326,39327,39328,39329,39330,39331,39332,39334,39335,39337,39338,39339,39340,39341,39342,39343,39344,39345,39346,39347,39348,39349,39350,39351,39352,39353,39354,39355,39356,39357,39358,39359,39360,39361,39362,39363,39364,39365,39366,39367,39368,39369,39370,39371,39372,39373,39374,39375,39376,39377,39378,39379,39380,39381,39382,39383,39384,39385,39386,39387,39388,39389,39390,39391,39392,39393,39394,39395,39396,39397,39398,39399,39400,39401,39402,39403,39404,39405,39406,39407,39408,39409,39410,39411,39412,39413,39414,39415,39416,39417,30235,30268,30242,30240,30272,30253,30256,30271,30261,30275,30270,30259,30285,30302,30292,30300,30294,30315,30319,32714,31462,31352,31353,31360,31366,31368,31381,31398,31392,31404,31400,31405,31411,34916,34921,34930,34941,34943,34946,34978,35014,34999,35004,35017,35042,35022,35043,35045,35057,35098,35068,35048,35070,35056,35105,35097,35091,35099,35082,35124,35115,35126,35137,35174,35195,30091,32997,30386,30388,30684,32786,32788,32790,32796,32800,32802,32805,32806,32807,32809,32808,32817,32779,32821,32835,32838,32845,32850,32873,32881,35203,39032,39040,39043,39418,39419,39420,39421,39422,39423,39424,39425,39426,39427,39428,39429,39430,39431,39432,39433,39434,39435,39436,39437,39438,39439,39440,39441,39442,39443,39444,39445,39446,39447,39448,39449,39450,39451,39452,39453,39454,39455,39456,39457,39458,39459,39460,39461,39462,39463,39464,39465,39466,39467,39468,39469,39470,39471,39472,39473,39474,39475,39476,39477,39478,39479,39480,39481,39482,39483,39484,39485,39486,39487,39488,39489,39490,39491,39492,39493,39494,39495,39496,39497,39498,39499,39500,39501,39502,39503,39504,39505,39506,39507,39508,39509,39510,39511,39512,39513,39049,39052,39053,39055,39060,39066,39067,39070,39071,39073,39074,39077,39078,34381,34388,34412,34414,34431,34426,34428,34427,34472,34445,34443,34476,34461,34471,34467,34474,34451,34473,34486,34500,34485,34510,34480,34490,34481,34479,34505,34511,34484,34537,34545,34546,34541,34547,34512,34579,34526,34548,34527,34520,34513,34563,34567,34552,34568,34570,34573,34569,34595,34619,34590,34597,34606,34586,34622,34632,34612,34609,34601,34615,34623,34690,34594,34685,34686,34683,34656,34672,34636,34670,34699,34643,34659,34684,34660,34649,34661,34707,34735,34728,34770,39514,39515,39516,39517,39518,39519,39520,39521,39522,39523,39524,39525,39526,39527,39528,39529,39530,39531,39538,39555,39561,39565,39566,39572,39573,39577,39590,39593,39594,39595,39596,39597,39598,39599,39602,39603,39604,39605,39609,39611,39613,39614,39615,39619,39620,39622,39623,39624,39625,39626,39629,39630,39631,39632,39634,39636,39637,39638,39639,39641,39642,39643,39644,39645,39646,39648,39650,39651,39652,39653,39655,39656,39657,39658,39660,39662,39664,39665,39666,39667,39668,39669,39670,39671,39672,39674,39676,39677,39678,39679,39680,39681,39682,39684,39685,39686,34758,34696,34693,34733,34711,34691,34731,34789,34732,34741,34739,34763,34771,34749,34769,34752,34762,34779,34794,34784,34798,34838,34835,34814,34826,34843,34849,34873,34876,32566,32578,32580,32581,33296,31482,31485,31496,31491,31492,31509,31498,31531,31503,31559,31544,31530,31513,31534,31537,31520,31525,31524,31539,31550,31518,31576,31578,31557,31605,31564,31581,31584,31598,31611,31586,31602,31601,31632,31654,31655,31672,31660,31645,31656,31621,31658,31644,31650,31659,31668,31697,31681,31692,31709,31706,31717,31718,31722,31756,31742,31740,31759,31766,31755,39687,39689,39690,39691,39692,39693,39694,39696,39697,39698,39700,39701,39702,39703,39704,39705,39706,39707,39708,39709,39710,39712,39713,39714,39716,39717,39718,39719,39720,39721,39722,39723,39724,39725,39726,39728,39729,39731,39732,39733,39734,39735,39736,39737,39738,39741,39742,39743,39744,39750,39754,39755,39756,39758,39760,39762,39763,39765,39766,39767,39768,39769,39770,39771,39772,39773,39774,39775,39776,39777,39778,39779,39780,39781,39782,39783,39784,39785,39786,39787,39788,39789,39790,39791,39792,39793,39794,39795,39796,39797,39798,39799,39800,39801,39802,39803,31775,31786,31782,31800,31809,31808,33278,33281,33282,33284,33260,34884,33313,33314,33315,33325,33327,33320,33323,33336,33339,33331,33332,33342,33348,33353,33355,33359,33370,33375,33384,34942,34949,34952,35032,35039,35166,32669,32671,32679,32687,32688,32690,31868,25929,31889,31901,31900,31902,31906,31922,31932,31933,31937,31943,31948,31949,31944,31941,31959,31976,33390,26280,32703,32718,32725,32741,32737,32742,32745,32750,32755,31992,32119,32166,32174,32327,32411,40632,40628,36211,36228,36244,36241,36273,36199,36205,35911,35913,37194,37200,37198,37199,37220,39804,39805,39806,39807,39808,39809,39810,39811,39812,39813,39814,39815,39816,39817,39818,39819,39820,39821,39822,39823,39824,39825,39826,39827,39828,39829,39830,39831,39832,39833,39834,39835,39836,39837,39838,39839,39840,39841,39842,39843,39844,39845,39846,39847,39848,39849,39850,39851,39852,39853,39854,39855,39856,39857,39858,39859,39860,39861,39862,39863,39864,39865,39866,39867,39868,39869,39870,39871,39872,39873,39874,39875,39876,39877,39878,39879,39880,39881,39882,39883,39884,39885,39886,39887,39888,39889,39890,39891,39892,39893,39894,39895,39896,39897,39898,39899,37218,37217,37232,37225,37231,37245,37246,37234,37236,37241,37260,37253,37264,37261,37265,37282,37283,37290,37293,37294,37295,37301,37300,37306,35925,40574,36280,36331,36357,36441,36457,36277,36287,36284,36282,36292,36310,36311,36314,36318,36302,36303,36315,36294,36332,36343,36344,36323,36345,36347,36324,36361,36349,36372,36381,36383,36396,36398,36387,36399,36410,36416,36409,36405,36413,36401,36425,36417,36418,36433,36434,36426,36464,36470,36476,36463,36468,36485,36495,36500,36496,36508,36510,35960,35970,35978,35973,35992,35988,26011,35286,35294,35290,35292,39900,39901,39902,39903,39904,39905,39906,39907,39908,39909,39910,39911,39912,39913,39914,39915,39916,39917,39918,39919,39920,39921,39922,39923,39924,39925,39926,39927,39928,39929,39930,39931,39932,39933,39934,39935,39936,39937,39938,39939,39940,39941,39942,39943,39944,39945,39946,39947,39948,39949,39950,39951,39952,39953,39954,39955,39956,39957,39958,39959,39960,39961,39962,39963,39964,39965,39966,39967,39968,39969,39970,39971,39972,39973,39974,39975,39976,39977,39978,39979,39980,39981,39982,39983,39984,39985,39986,39987,39988,39989,39990,39991,39992,39993,39994,39995,35301,35307,35311,35390,35622,38739,38633,38643,38639,38662,38657,38664,38671,38670,38698,38701,38704,38718,40832,40835,40837,40838,40839,40840,40841,40842,40844,40702,40715,40717,38585,38588,38589,38606,38610,30655,38624,37518,37550,37576,37694,37738,37834,37775,37950,37995,40063,40066,40069,40070,40071,40072,31267,40075,40078,40080,40081,40082,40084,40085,40090,40091,40094,40095,40096,40097,40098,40099,40101,40102,40103,40104,40105,40107,40109,40110,40112,40113,40114,40115,40116,40117,40118,40119,40122,40123,40124,40125,40132,40133,40134,40135,40138,40139,39996,39997,39998,39999,40000,40001,40002,40003,40004,40005,40006,40007,40008,40009,40010,40011,40012,40013,40014,40015,40016,40017,40018,40019,40020,40021,40022,40023,40024,40025,40026,40027,40028,40029,40030,40031,40032,40033,40034,40035,40036,40037,40038,40039,40040,40041,40042,40043,40044,40045,40046,40047,40048,40049,40050,40051,40052,40053,40054,40055,40056,40057,40058,40059,40061,40062,40064,40067,40068,40073,40074,40076,40079,40083,40086,40087,40088,40089,40093,40106,40108,40111,40121,40126,40127,40128,40129,40130,40136,40137,40145,40146,40154,40155,40160,40161,40140,40141,40142,40143,40144,40147,40148,40149,40151,40152,40153,40156,40157,40159,40162,38780,38789,38801,38802,38804,38831,38827,38819,38834,38836,39601,39600,39607,40536,39606,39610,39612,39617,39616,39621,39618,39627,39628,39633,39749,39747,39751,39753,39752,39757,39761,39144,39181,39214,39253,39252,39647,39649,39654,39663,39659,39675,39661,39673,39688,39695,39699,39711,39715,40637,40638,32315,40578,40583,40584,40587,40594,37846,40605,40607,40667,40668,40669,40672,40671,40674,40681,40679,40677,40682,40687,40738,40748,40751,40761,40759,40765,40766,40772,40163,40164,40165,40166,40167,40168,40169,40170,40171,40172,40173,40174,40175,40176,40177,40178,40179,40180,40181,40182,40183,40184,40185,40186,40187,40188,40189,40190,40191,40192,40193,40194,40195,40196,40197,40198,40199,40200,40201,40202,40203,40204,40205,40206,40207,40208,40209,40210,40211,40212,40213,40214,40215,40216,40217,40218,40219,40220,40221,40222,40223,40224,40225,40226,40227,40228,40229,40230,40231,40232,40233,40234,40235,40236,40237,40238,40239,40240,40241,40242,40243,40244,40245,40246,40247,40248,40249,40250,40251,40252,40253,40254,40255,40256,40257,40258,57908,57909,57910,57911,57912,57913,57914,57915,57916,57917,57918,57919,57920,57921,57922,57923,57924,57925,57926,57927,57928,57929,57930,57931,57932,57933,57934,57935,57936,57937,57938,57939,57940,57941,57942,57943,57944,57945,57946,57947,57948,57949,57950,57951,57952,57953,57954,57955,57956,57957,57958,57959,57960,57961,57962,57963,57964,57965,57966,57967,57968,57969,57970,57971,57972,57973,57974,57975,57976,57977,57978,57979,57980,57981,57982,57983,57984,57985,57986,57987,57988,57989,57990,57991,57992,57993,57994,57995,57996,57997,57998,57999,58000,58001,40259,40260,40261,40262,40263,40264,40265,40266,40267,40268,40269,40270,40271,40272,40273,40274,40275,40276,40277,40278,40279,40280,40281,40282,40283,40284,40285,40286,40287,40288,40289,40290,40291,40292,40293,40294,40295,40296,40297,40298,40299,40300,40301,40302,40303,40304,40305,40306,40307,40308,40309,40310,40311,40312,40313,40314,40315,40316,40317,40318,40319,40320,40321,40322,40323,40324,40325,40326,40327,40328,40329,40330,40331,40332,40333,40334,40335,40336,40337,40338,40339,40340,40341,40342,40343,40344,40345,40346,40347,40348,40349,40350,40351,40352,40353,40354,58002,58003,58004,58005,58006,58007,58008,58009,58010,58011,58012,58013,58014,58015,58016,58017,58018,58019,58020,58021,58022,58023,58024,58025,58026,58027,58028,58029,58030,58031,58032,58033,58034,58035,58036,58037,58038,58039,58040,58041,58042,58043,58044,58045,58046,58047,58048,58049,58050,58051,58052,58053,58054,58055,58056,58057,58058,58059,58060,58061,58062,58063,58064,58065,58066,58067,58068,58069,58070,58071,58072,58073,58074,58075,58076,58077,58078,58079,58080,58081,58082,58083,58084,58085,58086,58087,58088,58089,58090,58091,58092,58093,58094,58095,40355,40356,40357,40358,40359,40360,40361,40362,40363,40364,40365,40366,40367,40368,40369,40370,40371,40372,40373,40374,40375,40376,40377,40378,40379,40380,40381,40382,40383,40384,40385,40386,40387,40388,40389,40390,40391,40392,40393,40394,40395,40396,40397,40398,40399,40400,40401,40402,40403,40404,40405,40406,40407,40408,40409,40410,40411,40412,40413,40414,40415,40416,40417,40418,40419,40420,40421,40422,40423,40424,40425,40426,40427,40428,40429,40430,40431,40432,40433,40434,40435,40436,40437,40438,40439,40440,40441,40442,40443,40444,40445,40446,40447,40448,40449,40450,58096,58097,58098,58099,58100,58101,58102,58103,58104,58105,58106,58107,58108,58109,58110,58111,58112,58113,58114,58115,58116,58117,58118,58119,58120,58121,58122,58123,58124,58125,58126,58127,58128,58129,58130,58131,58132,58133,58134,58135,58136,58137,58138,58139,58140,58141,58142,58143,58144,58145,58146,58147,58148,58149,58150,58151,58152,58153,58154,58155,58156,58157,58158,58159,58160,58161,58162,58163,58164,58165,58166,58167,58168,58169,58170,58171,58172,58173,58174,58175,58176,58177,58178,58179,58180,58181,58182,58183,58184,58185,58186,58187,58188,58189,40451,40452,40453,40454,40455,40456,40457,40458,40459,40460,40461,40462,40463,40464,40465,40466,40467,40468,40469,40470,40471,40472,40473,40474,40475,40476,40477,40478,40484,40487,40494,40496,40500,40507,40508,40512,40525,40528,40530,40531,40532,40534,40537,40541,40543,40544,40545,40546,40549,40558,40559,40562,40564,40565,40566,40567,40568,40569,40570,40571,40572,40573,40576,40577,40579,40580,40581,40582,40585,40586,40588,40589,40590,40591,40592,40593,40596,40597,40598,40599,40600,40601,40602,40603,40604,40606,40608,40609,40610,40611,40612,40613,40615,40616,40617,40618,58190,58191,58192,58193,58194,58195,58196,58197,58198,58199,58200,58201,58202,58203,58204,58205,58206,58207,58208,58209,58210,58211,58212,58213,58214,58215,58216,58217,58218,58219,58220,58221,58222,58223,58224,58225,58226,58227,58228,58229,58230,58231,58232,58233,58234,58235,58236,58237,58238,58239,58240,58241,58242,58243,58244,58245,58246,58247,58248,58249,58250,58251,58252,58253,58254,58255,58256,58257,58258,58259,58260,58261,58262,58263,58264,58265,58266,58267,58268,58269,58270,58271,58272,58273,58274,58275,58276,58277,58278,58279,58280,58281,58282,58283,40619,40620,40621,40622,40623,40624,40625,40626,40627,40629,40630,40631,40633,40634,40636,40639,40640,40641,40642,40643,40645,40646,40647,40648,40650,40651,40652,40656,40658,40659,40661,40662,40663,40665,40666,40670,40673,40675,40676,40678,40680,40683,40684,40685,40686,40688,40689,40690,40691,40692,40693,40694,40695,40696,40698,40701,40703,40704,40705,40706,40707,40708,40709,40710,40711,40712,40713,40714,40716,40719,40721,40722,40724,40725,40726,40728,40730,40731,40732,40733,40734,40735,40737,40739,40740,40741,40742,40743,40744,40745,40746,40747,40749,40750,40752,40753,58284,58285,58286,58287,58288,58289,58290,58291,58292,58293,58294,58295,58296,58297,58298,58299,58300,58301,58302,58303,58304,58305,58306,58307,58308,58309,58310,58311,58312,58313,58314,58315,58316,58317,58318,58319,58320,58321,58322,58323,58324,58325,58326,58327,58328,58329,58330,58331,58332,58333,58334,58335,58336,58337,58338,58339,58340,58341,58342,58343,58344,58345,58346,58347,58348,58349,58350,58351,58352,58353,58354,58355,58356,58357,58358,58359,58360,58361,58362,58363,58364,58365,58366,58367,58368,58369,58370,58371,58372,58373,58374,58375,58376,58377,40754,40755,40756,40757,40758,40760,40762,40764,40767,40768,40769,40770,40771,40773,40774,40775,40776,40777,40778,40779,40780,40781,40782,40783,40786,40787,40788,40789,40790,40791,40792,40793,40794,40795,40796,40797,40798,40799,40800,40801,40802,40803,40804,40805,40806,40807,40808,40809,40810,40811,40812,40813,40814,40815,40816,40817,40818,40819,40820,40821,40822,40823,40824,40825,40826,40827,40828,40829,40830,40833,40834,40845,40846,40847,40848,40849,40850,40851,40852,40853,40854,40855,40856,40860,40861,40862,40865,40866,40867,40868,40869,63788,63865,63893,63975,63985,58378,58379,58380,58381,58382,58383,58384,58385,58386,58387,58388,58389,58390,58391,58392,58393,58394,58395,58396,58397,58398,58399,58400,58401,58402,58403,58404,58405,58406,58407,58408,58409,58410,58411,58412,58413,58414,58415,58416,58417,58418,58419,58420,58421,58422,58423,58424,58425,58426,58427,58428,58429,58430,58431,58432,58433,58434,58435,58436,58437,58438,58439,58440,58441,58442,58443,58444,58445,58446,58447,58448,58449,58450,58451,58452,58453,58454,58455,58456,58457,58458,58459,58460,58461,58462,58463,58464,58465,58466,58467,58468,58469,58470,58471,64012,64013,64014,64015,64017,64019,64020,64024,64031,64032,64033,64035,64036,64039,64040,64041,11905,59414,59415,59416,11908,13427,13383,11912,11915,59422,13726,13850,13838,11916,11927,14702,14616,59430,14799,14815,14963,14800,59435,59436,15182,15470,15584,11943,59441,59442,11946,16470,16735,11950,17207,11955,11958,11959,59451,17329,17324,11963,17373,17622,18017,17996,59459,18211,18217,18300,18317,11978,18759,18810,18813,18818,18819,18821,18822,18847,18843,18871,18870,59476,59477,19619,19615,19616,19617,19575,19618,19731,19732,19733,19734,19735,19736,19737,19886,59492,58472,58473,58474,58475,58476,58477,58478,58479,58480,58481,58482,58483,58484,58485,58486,58487,58488,58489,58490,58491,58492,58493,58494,58495,58496,58497,58498,58499,58500,58501,58502,58503,58504,58505,58506,58507,58508,58509,58510,58511,58512,58513,58514,58515,58516,58517,58518,58519,58520,58521,58522,58523,58524,58525,58526,58527,58528,58529,58530,58531,58532,58533,58534,58535,58536,58537,58538,58539,58540,58541,58542,58543,58544,58545,58546,58547,58548,58549,58550,58551,58552,58553,58554,58555,58556,58557,58558,58559,58560,58561,58562,58563,58564,58565], + "gb18030-ranges":[[0,128],[36,165],[38,169],[45,178],[50,184],[81,216],[89,226],[95,235],[96,238],[100,244],[103,248],[104,251],[105,253],[109,258],[126,276],[133,284],[148,300],[172,325],[175,329],[179,334],[208,364],[306,463],[307,465],[308,467],[309,469],[310,471],[311,473],[312,475],[313,477],[341,506],[428,594],[443,610],[544,712],[545,716],[558,730],[741,930],[742,938],[749,962],[750,970],[805,1026],[819,1104],[820,1106],[7922,8209],[7924,8215],[7925,8218],[7927,8222],[7934,8231],[7943,8241],[7944,8244],[7945,8246],[7950,8252],[8062,8365],[8148,8452],[8149,8454],[8152,8458],[8164,8471],[8174,8482],[8236,8556],[8240,8570],[8262,8596],[8264,8602],[8374,8713],[8380,8720],[8381,8722],[8384,8726],[8388,8731],[8390,8737],[8392,8740],[8393,8742],[8394,8748],[8396,8751],[8401,8760],[8406,8766],[8416,8777],[8419,8781],[8424,8787],[8437,8802],[8439,8808],[8445,8816],[8482,8854],[8485,8858],[8496,8870],[8521,8896],[8603,8979],[8936,9322],[8946,9372],[9046,9548],[9050,9588],[9063,9616],[9066,9622],[9076,9634],[9092,9652],[9100,9662],[9108,9672],[9111,9676],[9113,9680],[9131,9702],[9162,9735],[9164,9738],[9218,9793],[9219,9795],[11329,11906],[11331,11909],[11334,11913],[11336,11917],[11346,11928],[11361,11944],[11363,11947],[11366,11951],[11370,11956],[11372,11960],[11375,11964],[11389,11979],[11682,12284],[11686,12292],[11687,12312],[11692,12319],[11694,12330],[11714,12351],[11716,12436],[11723,12447],[11725,12535],[11730,12543],[11736,12586],[11982,12842],[11989,12850],[12102,12964],[12336,13200],[12348,13215],[12350,13218],[12384,13253],[12393,13263],[12395,13267],[12397,13270],[12510,13384],[12553,13428],[12851,13727],[12962,13839],[12973,13851],[13738,14617],[13823,14703],[13919,14801],[13933,14816],[14080,14964],[14298,15183],[14585,15471],[14698,15585],[15583,16471],[15847,16736],[16318,17208],[16434,17325],[16438,17330],[16481,17374],[16729,17623],[17102,17997],[17122,18018],[17315,18212],[17320,18218],[17402,18301],[17418,18318],[17859,18760],[17909,18811],[17911,18814],[17915,18820],[17916,18823],[17936,18844],[17939,18848],[17961,18872],[18664,19576],[18703,19620],[18814,19738],[18962,19887],[19043,40870],[33469,59244],[33470,59336],[33471,59367],[33484,59413],[33485,59417],[33490,59423],[33497,59431],[33501,59437],[33505,59443],[33513,59452],[33520,59460],[33536,59478],[33550,59493],[37845,63789],[37921,63866],[37948,63894],[38029,63976],[38038,63986],[38064,64016],[38065,64018],[38066,64021],[38069,64025],[38075,64034],[38076,64037],[38078,64042],[39108,65074],[39109,65093],[39113,65107],[39114,65112],[39115,65127],[39116,65132],[39265,65375],[39394,65510],[189000,65536]], + "jis0208":[12288,12289,12290,65292,65294,12539,65306,65307,65311,65281,12443,12444,180,65344,168,65342,65507,65343,12541,12542,12445,12446,12291,20189,12293,12294,12295,12540,8213,8208,65295,65340,65374,8741,65372,8230,8229,8216,8217,8220,8221,65288,65289,12308,12309,65339,65341,65371,65373,12296,12297,12298,12299,12300,12301,12302,12303,12304,12305,65291,65293,177,215,247,65309,8800,65308,65310,8806,8807,8734,8756,9794,9792,176,8242,8243,8451,65509,65284,65504,65505,65285,65283,65286,65290,65312,167,9734,9733,9675,9679,9678,9671,9670,9633,9632,9651,9650,9661,9660,8251,12306,8594,8592,8593,8595,12307,null,null,null,null,null,null,null,null,null,null,null,8712,8715,8838,8839,8834,8835,8746,8745,null,null,null,null,null,null,null,null,8743,8744,65506,8658,8660,8704,8707,null,null,null,null,null,null,null,null,null,null,null,8736,8869,8978,8706,8711,8801,8786,8810,8811,8730,8765,8733,8757,8747,8748,null,null,null,null,null,null,null,8491,8240,9839,9837,9834,8224,8225,182,null,null,null,null,9711,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,65296,65297,65298,65299,65300,65301,65302,65303,65304,65305,null,null,null,null,null,null,null,65313,65314,65315,65316,65317,65318,65319,65320,65321,65322,65323,65324,65325,65326,65327,65328,65329,65330,65331,65332,65333,65334,65335,65336,65337,65338,null,null,null,null,null,null,65345,65346,65347,65348,65349,65350,65351,65352,65353,65354,65355,65356,65357,65358,65359,65360,65361,65362,65363,65364,65365,65366,65367,65368,65369,65370,null,null,null,null,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,null,null,null,null,null,null,null,null,null,null,null,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,null,null,null,null,null,null,null,null,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,null,null,null,null,null,null,null,null,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,963,964,965,966,967,968,969,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,1040,1041,1042,1043,1044,1045,1025,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,1072,1073,1074,1075,1076,1077,1105,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,null,null,null,null,null,null,null,null,null,null,null,null,null,9472,9474,9484,9488,9496,9492,9500,9516,9508,9524,9532,9473,9475,9487,9491,9499,9495,9507,9523,9515,9531,9547,9504,9519,9512,9527,9535,9501,9520,9509,9528,9538,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,9312,9313,9314,9315,9316,9317,9318,9319,9320,9321,9322,9323,9324,9325,9326,9327,9328,9329,9330,9331,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,null,13129,13076,13090,13133,13080,13095,13059,13110,13137,13143,13069,13094,13091,13099,13130,13115,13212,13213,13214,13198,13199,13252,13217,null,null,null,null,null,null,null,null,13179,12317,12319,8470,13261,8481,12964,12965,12966,12967,12968,12849,12850,12857,13182,13181,13180,8786,8801,8747,8750,8721,8730,8869,8736,8735,8895,8757,8745,8746,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,20124,21782,23043,38463,21696,24859,25384,23030,36898,33909,33564,31312,24746,25569,28197,26093,33894,33446,39925,26771,22311,26017,25201,23451,22992,34427,39156,32098,32190,39822,25110,31903,34999,23433,24245,25353,26263,26696,38343,38797,26447,20197,20234,20301,20381,20553,22258,22839,22996,23041,23561,24799,24847,24944,26131,26885,28858,30031,30064,31227,32173,32239,32963,33806,34915,35586,36949,36986,21307,20117,20133,22495,32946,37057,30959,19968,22769,28322,36920,31282,33576,33419,39983,20801,21360,21693,21729,22240,23035,24341,39154,28139,32996,34093,38498,38512,38560,38907,21515,21491,23431,28879,32701,36802,38632,21359,40284,31418,19985,30867,33276,28198,22040,21764,27421,34074,39995,23013,21417,28006,29916,38287,22082,20113,36939,38642,33615,39180,21473,21942,23344,24433,26144,26355,26628,27704,27891,27945,29787,30408,31310,38964,33521,34907,35424,37613,28082,30123,30410,39365,24742,35585,36234,38322,27022,21421,20870,22290,22576,22852,23476,24310,24616,25513,25588,27839,28436,28814,28948,29017,29141,29503,32257,33398,33489,34199,36960,37467,40219,22633,26044,27738,29989,20985,22830,22885,24448,24540,25276,26106,27178,27431,27572,29579,32705,35158,40236,40206,40644,23713,27798,33659,20740,23627,25014,33222,26742,29281,20057,20474,21368,24681,28201,31311,38899,19979,21270,20206,20309,20285,20385,20339,21152,21487,22025,22799,23233,23478,23521,31185,26247,26524,26550,27468,27827,28779,29634,31117,31166,31292,31623,33457,33499,33540,33655,33775,33747,34662,35506,22057,36008,36838,36942,38686,34442,20420,23784,25105,29273,30011,33253,33469,34558,36032,38597,39187,39381,20171,20250,35299,22238,22602,22730,24315,24555,24618,24724,24674,25040,25106,25296,25913,39745,26214,26800,28023,28784,30028,30342,32117,33445,34809,38283,38542,35997,20977,21182,22806,21683,23475,23830,24936,27010,28079,30861,33995,34903,35442,37799,39608,28012,39336,34521,22435,26623,34510,37390,21123,22151,21508,24275,25313,25785,26684,26680,27579,29554,30906,31339,35226,35282,36203,36611,37101,38307,38548,38761,23398,23731,27005,38989,38990,25499,31520,27179,27263,26806,39949,28511,21106,21917,24688,25324,27963,28167,28369,33883,35088,36676,19988,39993,21494,26907,27194,38788,26666,20828,31427,33970,37340,37772,22107,40232,26658,33541,33841,31909,21000,33477,29926,20094,20355,20896,23506,21002,21208,21223,24059,21914,22570,23014,23436,23448,23515,24178,24185,24739,24863,24931,25022,25563,25954,26577,26707,26874,27454,27475,27735,28450,28567,28485,29872,29976,30435,30475,31487,31649,31777,32233,32566,32752,32925,33382,33694,35251,35532,36011,36996,37969,38291,38289,38306,38501,38867,39208,33304,20024,21547,23736,24012,29609,30284,30524,23721,32747,36107,38593,38929,38996,39000,20225,20238,21361,21916,22120,22522,22855,23305,23492,23696,24076,24190,24524,25582,26426,26071,26082,26399,26827,26820,27231,24112,27589,27671,27773,30079,31048,23395,31232,32000,24509,35215,35352,36020,36215,36556,36637,39138,39438,39740,20096,20605,20736,22931,23452,25135,25216,25836,27450,29344,30097,31047,32681,34811,35516,35696,25516,33738,38816,21513,21507,21931,26708,27224,35440,30759,26485,40653,21364,23458,33050,34384,36870,19992,20037,20167,20241,21450,21560,23470,24339,24613,25937,26429,27714,27762,27875,28792,29699,31350,31406,31496,32026,31998,32102,26087,29275,21435,23621,24040,25298,25312,25369,28192,34394,35377,36317,37624,28417,31142,39770,20136,20139,20140,20379,20384,20689,20807,31478,20849,20982,21332,21281,21375,21483,21932,22659,23777,24375,24394,24623,24656,24685,25375,25945,27211,27841,29378,29421,30703,33016,33029,33288,34126,37111,37857,38911,39255,39514,20208,20957,23597,26241,26989,23616,26354,26997,29577,26704,31873,20677,21220,22343,24062,37670,26020,27427,27453,29748,31105,31165,31563,32202,33465,33740,34943,35167,35641,36817,37329,21535,37504,20061,20534,21477,21306,29399,29590,30697,33510,36527,39366,39368,39378,20855,24858,34398,21936,31354,20598,23507,36935,38533,20018,27355,37351,23633,23624,25496,31391,27795,38772,36705,31402,29066,38536,31874,26647,32368,26705,37740,21234,21531,34219,35347,32676,36557,37089,21350,34952,31041,20418,20670,21009,20804,21843,22317,29674,22411,22865,24418,24452,24693,24950,24935,25001,25522,25658,25964,26223,26690,28179,30054,31293,31995,32076,32153,32331,32619,33550,33610,34509,35336,35427,35686,36605,38938,40335,33464,36814,39912,21127,25119,25731,28608,38553,26689,20625,27424,27770,28500,31348,32080,34880,35363,26376,20214,20537,20518,20581,20860,21048,21091,21927,22287,22533,23244,24314,25010,25080,25331,25458,26908,27177,29309,29356,29486,30740,30831,32121,30476,32937,35211,35609,36066,36562,36963,37749,38522,38997,39443,40568,20803,21407,21427,24187,24358,28187,28304,29572,29694,32067,33335,35328,35578,38480,20046,20491,21476,21628,22266,22993,23396,24049,24235,24359,25144,25925,26543,28246,29392,31946,34996,32929,32993,33776,34382,35463,36328,37431,38599,39015,40723,20116,20114,20237,21320,21577,21566,23087,24460,24481,24735,26791,27278,29786,30849,35486,35492,35703,37264,20062,39881,20132,20348,20399,20505,20502,20809,20844,21151,21177,21246,21402,21475,21521,21518,21897,22353,22434,22909,23380,23389,23439,24037,24039,24055,24184,24195,24218,24247,24344,24658,24908,25239,25304,25511,25915,26114,26179,26356,26477,26657,26775,27083,27743,27946,28009,28207,28317,30002,30343,30828,31295,31968,32005,32024,32094,32177,32789,32771,32943,32945,33108,33167,33322,33618,34892,34913,35611,36002,36092,37066,37237,37489,30783,37628,38308,38477,38917,39321,39640,40251,21083,21163,21495,21512,22741,25335,28640,35946,36703,40633,20811,21051,21578,22269,31296,37239,40288,40658,29508,28425,33136,29969,24573,24794,39592,29403,36796,27492,38915,20170,22256,22372,22718,23130,24680,25031,26127,26118,26681,26801,28151,30165,32058,33390,39746,20123,20304,21449,21766,23919,24038,24046,26619,27801,29811,30722,35408,37782,35039,22352,24231,25387,20661,20652,20877,26368,21705,22622,22971,23472,24425,25165,25505,26685,27507,28168,28797,37319,29312,30741,30758,31085,25998,32048,33756,35009,36617,38555,21092,22312,26448,32618,36001,20916,22338,38442,22586,27018,32948,21682,23822,22524,30869,40442,20316,21066,21643,25662,26152,26388,26613,31364,31574,32034,37679,26716,39853,31545,21273,20874,21047,23519,25334,25774,25830,26413,27578,34217,38609,30352,39894,25420,37638,39851,30399,26194,19977,20632,21442,23665,24808,25746,25955,26719,29158,29642,29987,31639,32386,34453,35715,36059,37240,39184,26028,26283,27531,20181,20180,20282,20351,21050,21496,21490,21987,22235,22763,22987,22985,23039,23376,23629,24066,24107,24535,24605,25351,25903,23388,26031,26045,26088,26525,27490,27515,27663,29509,31049,31169,31992,32025,32043,32930,33026,33267,35222,35422,35433,35430,35468,35566,36039,36060,38604,39164,27503,20107,20284,20365,20816,23383,23546,24904,25345,26178,27425,28363,27835,29246,29885,30164,30913,31034,32780,32819,33258,33940,36766,27728,40575,24335,35672,40235,31482,36600,23437,38635,19971,21489,22519,22833,23241,23460,24713,28287,28422,30142,36074,23455,34048,31712,20594,26612,33437,23649,34122,32286,33294,20889,23556,25448,36198,26012,29038,31038,32023,32773,35613,36554,36974,34503,37034,20511,21242,23610,26451,28796,29237,37196,37320,37675,33509,23490,24369,24825,20027,21462,23432,25163,26417,27530,29417,29664,31278,33131,36259,37202,39318,20754,21463,21610,23551,25480,27193,32172,38656,22234,21454,21608,23447,23601,24030,20462,24833,25342,27954,31168,31179,32066,32333,32722,33261,33311,33936,34886,35186,35728,36468,36655,36913,37195,37228,38598,37276,20160,20303,20805,21313,24467,25102,26580,27713,28171,29539,32294,37325,37507,21460,22809,23487,28113,31069,32302,31899,22654,29087,20986,34899,36848,20426,23803,26149,30636,31459,33308,39423,20934,24490,26092,26991,27529,28147,28310,28516,30462,32020,24033,36981,37255,38918,20966,21021,25152,26257,26329,28186,24246,32210,32626,26360,34223,34295,35576,21161,21465,22899,24207,24464,24661,37604,38500,20663,20767,21213,21280,21319,21484,21736,21830,21809,22039,22888,22974,23100,23477,23558,23567,23569,23578,24196,24202,24288,24432,25215,25220,25307,25484,25463,26119,26124,26157,26230,26494,26786,27167,27189,27836,28040,28169,28248,28988,28966,29031,30151,30465,30813,30977,31077,31216,31456,31505,31911,32057,32918,33750,33931,34121,34909,35059,35359,35388,35412,35443,35937,36062,37284,37478,37758,37912,38556,38808,19978,19976,19998,20055,20887,21104,22478,22580,22732,23330,24120,24773,25854,26465,26454,27972,29366,30067,31331,33976,35698,37304,37664,22065,22516,39166,25325,26893,27542,29165,32340,32887,33394,35302,39135,34645,36785,23611,20280,20449,20405,21767,23072,23517,23529,24515,24910,25391,26032,26187,26862,27035,28024,28145,30003,30137,30495,31070,31206,32051,33251,33455,34218,35242,35386,36523,36763,36914,37341,38663,20154,20161,20995,22645,22764,23563,29978,23613,33102,35338,36805,38499,38765,31525,35535,38920,37218,22259,21416,36887,21561,22402,24101,25512,27700,28810,30561,31883,32736,34928,36930,37204,37648,37656,38543,29790,39620,23815,23913,25968,26530,36264,38619,25454,26441,26905,33733,38935,38592,35070,28548,25722,23544,19990,28716,30045,26159,20932,21046,21218,22995,24449,24615,25104,25919,25972,26143,26228,26866,26646,27491,28165,29298,29983,30427,31934,32854,22768,35069,35199,35488,35475,35531,36893,37266,38738,38745,25993,31246,33030,38587,24109,24796,25114,26021,26132,26512,30707,31309,31821,32318,33034,36012,36196,36321,36447,30889,20999,25305,25509,25666,25240,35373,31363,31680,35500,38634,32118,33292,34633,20185,20808,21315,21344,23459,23554,23574,24029,25126,25159,25776,26643,26676,27849,27973,27927,26579,28508,29006,29053,26059,31359,31661,32218,32330,32680,33146,33307,33337,34214,35438,36046,36341,36984,36983,37549,37521,38275,39854,21069,21892,28472,28982,20840,31109,32341,33203,31950,22092,22609,23720,25514,26366,26365,26970,29401,30095,30094,30990,31062,31199,31895,32032,32068,34311,35380,38459,36961,40736,20711,21109,21452,21474,20489,21930,22766,22863,29245,23435,23652,21277,24803,24819,25436,25475,25407,25531,25805,26089,26361,24035,27085,27133,28437,29157,20105,30185,30456,31379,31967,32207,32156,32865,33609,33624,33900,33980,34299,35013,36208,36865,36973,37783,38684,39442,20687,22679,24974,33235,34101,36104,36896,20419,20596,21063,21363,24687,25417,26463,28204,36275,36895,20439,23646,36042,26063,32154,21330,34966,20854,25539,23384,23403,23562,25613,26449,36956,20182,22810,22826,27760,35409,21822,22549,22949,24816,25171,26561,33333,26965,38464,39364,39464,20307,22534,23550,32784,23729,24111,24453,24608,24907,25140,26367,27888,28382,32974,33151,33492,34955,36024,36864,36910,38538,40667,39899,20195,21488,22823,31532,37261,38988,40441,28381,28711,21331,21828,23429,25176,25246,25299,27810,28655,29730,35351,37944,28609,35582,33592,20967,34552,21482,21481,20294,36948,36784,22890,33073,24061,31466,36799,26842,35895,29432,40008,27197,35504,20025,21336,22022,22374,25285,25506,26086,27470,28129,28251,28845,30701,31471,31658,32187,32829,32966,34507,35477,37723,22243,22727,24382,26029,26262,27264,27573,30007,35527,20516,30693,22320,24347,24677,26234,27744,30196,31258,32622,33268,34584,36933,39347,31689,30044,31481,31569,33988,36880,31209,31378,33590,23265,30528,20013,20210,23449,24544,25277,26172,26609,27880,34411,34935,35387,37198,37619,39376,27159,28710,29482,33511,33879,36015,19969,20806,20939,21899,23541,24086,24115,24193,24340,24373,24427,24500,25074,25361,26274,26397,28526,29266,30010,30522,32884,33081,33144,34678,35519,35548,36229,36339,37530,38263,38914,40165,21189,25431,30452,26389,27784,29645,36035,37806,38515,27941,22684,26894,27084,36861,37786,30171,36890,22618,26626,25524,27131,20291,28460,26584,36795,34086,32180,37716,26943,28528,22378,22775,23340,32044,29226,21514,37347,40372,20141,20302,20572,20597,21059,35998,21576,22564,23450,24093,24213,24237,24311,24351,24716,25269,25402,25552,26799,27712,30855,31118,31243,32224,33351,35330,35558,36420,36883,37048,37165,37336,40718,27877,25688,25826,25973,28404,30340,31515,36969,37841,28346,21746,24505,25764,36685,36845,37444,20856,22635,22825,23637,24215,28155,32399,29980,36028,36578,39003,28857,20253,27583,28593,30000,38651,20814,21520,22581,22615,22956,23648,24466,26007,26460,28193,30331,33759,36077,36884,37117,37709,30757,30778,21162,24230,22303,22900,24594,20498,20826,20908,20941,20992,21776,22612,22616,22871,23445,23798,23947,24764,25237,25645,26481,26691,26812,26847,30423,28120,28271,28059,28783,29128,24403,30168,31095,31561,31572,31570,31958,32113,21040,33891,34153,34276,35342,35588,35910,36367,36867,36879,37913,38518,38957,39472,38360,20685,21205,21516,22530,23566,24999,25758,27934,30643,31461,33012,33796,36947,37509,23776,40199,21311,24471,24499,28060,29305,30563,31167,31716,27602,29420,35501,26627,27233,20984,31361,26932,23626,40182,33515,23493,37193,28702,22136,23663,24775,25958,27788,35930,36929,38931,21585,26311,37389,22856,37027,20869,20045,20970,34201,35598,28760,25466,37707,26978,39348,32260,30071,21335,26976,36575,38627,27741,20108,23612,24336,36841,21250,36049,32905,34425,24319,26085,20083,20837,22914,23615,38894,20219,22922,24525,35469,28641,31152,31074,23527,33905,29483,29105,24180,24565,25467,25754,29123,31896,20035,24316,20043,22492,22178,24745,28611,32013,33021,33075,33215,36786,35223,34468,24052,25226,25773,35207,26487,27874,27966,29750,30772,23110,32629,33453,39340,20467,24259,25309,25490,25943,26479,30403,29260,32972,32954,36649,37197,20493,22521,23186,26757,26995,29028,29437,36023,22770,36064,38506,36889,34687,31204,30695,33833,20271,21093,21338,25293,26575,27850,30333,31636,31893,33334,34180,36843,26333,28448,29190,32283,33707,39361,40614,20989,31665,30834,31672,32903,31560,27368,24161,32908,30033,30048,20843,37474,28300,30330,37271,39658,20240,32624,25244,31567,38309,40169,22138,22617,34532,38588,20276,21028,21322,21453,21467,24070,25644,26001,26495,27710,27726,29256,29359,29677,30036,32321,33324,34281,36009,31684,37318,29033,38930,39151,25405,26217,30058,30436,30928,34115,34542,21290,21329,21542,22915,24199,24444,24754,25161,25209,25259,26000,27604,27852,30130,30382,30865,31192,32203,32631,32933,34987,35513,36027,36991,38750,39131,27147,31800,20633,23614,24494,26503,27608,29749,30473,32654,40763,26570,31255,21305,30091,39661,24422,33181,33777,32920,24380,24517,30050,31558,36924,26727,23019,23195,32016,30334,35628,20469,24426,27161,27703,28418,29922,31080,34920,35413,35961,24287,25551,30149,31186,33495,37672,37618,33948,34541,39981,21697,24428,25996,27996,28693,36007,36051,38971,25935,29942,19981,20184,22496,22827,23142,23500,20904,24067,24220,24598,25206,25975,26023,26222,28014,29238,31526,33104,33178,33433,35676,36000,36070,36212,38428,38468,20398,25771,27494,33310,33889,34154,37096,23553,26963,39080,33914,34135,20239,21103,24489,24133,26381,31119,33145,35079,35206,28149,24343,25173,27832,20175,29289,39826,20998,21563,22132,22707,24996,25198,28954,22894,31881,31966,32027,38640,25991,32862,19993,20341,20853,22592,24163,24179,24330,26564,20006,34109,38281,38491,31859,38913,20731,22721,30294,30887,21029,30629,34065,31622,20559,22793,29255,31687,32232,36794,36820,36941,20415,21193,23081,24321,38829,20445,33303,37610,22275,25429,27497,29995,35036,36628,31298,21215,22675,24917,25098,26286,27597,31807,33769,20515,20472,21253,21574,22577,22857,23453,23792,23791,23849,24214,25265,25447,25918,26041,26379,27861,27873,28921,30770,32299,32990,33459,33804,34028,34562,35090,35370,35914,37030,37586,39165,40179,40300,20047,20129,20621,21078,22346,22952,24125,24536,24537,25151,26292,26395,26576,26834,20882,32033,32938,33192,35584,35980,36031,37502,38450,21536,38956,21271,20693,21340,22696,25778,26420,29287,30566,31302,37350,21187,27809,27526,22528,24140,22868,26412,32763,20961,30406,25705,30952,39764,40635,22475,22969,26151,26522,27598,21737,27097,24149,33180,26517,39850,26622,40018,26717,20134,20451,21448,25273,26411,27819,36804,20397,32365,40639,19975,24930,28288,28459,34067,21619,26410,39749,24051,31637,23724,23494,34588,28234,34001,31252,33032,22937,31885,27665,30496,21209,22818,28961,29279,30683,38695,40289,26891,23167,23064,20901,21517,21629,26126,30431,36855,37528,40180,23018,29277,28357,20813,26825,32191,32236,38754,40634,25720,27169,33538,22916,23391,27611,29467,30450,32178,32791,33945,20786,26408,40665,30446,26466,21247,39173,23588,25147,31870,36016,21839,24758,32011,38272,21249,20063,20918,22812,29242,32822,37326,24357,30690,21380,24441,32004,34220,35379,36493,38742,26611,34222,37971,24841,24840,27833,30290,35565,36664,21807,20305,20778,21191,21451,23461,24189,24736,24962,25558,26377,26586,28263,28044,29494,29495,30001,31056,35029,35480,36938,37009,37109,38596,34701,22805,20104,20313,19982,35465,36671,38928,20653,24188,22934,23481,24248,25562,25594,25793,26332,26954,27096,27915,28342,29076,29992,31407,32650,32768,33865,33993,35201,35617,36362,36965,38525,39178,24958,25233,27442,27779,28020,32716,32764,28096,32645,34746,35064,26469,33713,38972,38647,27931,32097,33853,37226,20081,21365,23888,27396,28651,34253,34349,35239,21033,21519,23653,26446,26792,29702,29827,30178,35023,35041,37324,38626,38520,24459,29575,31435,33870,25504,30053,21129,27969,28316,29705,30041,30827,31890,38534,31452,40845,20406,24942,26053,34396,20102,20142,20698,20001,20940,23534,26009,26753,28092,29471,30274,30637,31260,31975,33391,35538,36988,37327,38517,38936,21147,32209,20523,21400,26519,28107,29136,29747,33256,36650,38563,40023,40607,29792,22593,28057,32047,39006,20196,20278,20363,20919,21169,23994,24604,29618,31036,33491,37428,38583,38646,38666,40599,40802,26278,27508,21015,21155,28872,35010,24265,24651,24976,28451,29001,31806,32244,32879,34030,36899,37676,21570,39791,27347,28809,36034,36335,38706,21172,23105,24266,24324,26391,27004,27028,28010,28431,29282,29436,31725,32769,32894,34635,37070,20845,40595,31108,32907,37682,35542,20525,21644,35441,27498,36036,33031,24785,26528,40434,20121,20120,39952,35435,34241,34152,26880,28286,30871,33109,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,24332,19984,19989,20010,20017,20022,20028,20031,20034,20054,20056,20098,20101,35947,20106,33298,24333,20110,20126,20127,20128,20130,20144,20147,20150,20174,20173,20164,20166,20162,20183,20190,20205,20191,20215,20233,20314,20272,20315,20317,20311,20295,20342,20360,20367,20376,20347,20329,20336,20369,20335,20358,20374,20760,20436,20447,20430,20440,20443,20433,20442,20432,20452,20453,20506,20520,20500,20522,20517,20485,20252,20470,20513,20521,20524,20478,20463,20497,20486,20547,20551,26371,20565,20560,20552,20570,20566,20588,20600,20608,20634,20613,20660,20658,20681,20682,20659,20674,20694,20702,20709,20717,20707,20718,20729,20725,20745,20737,20738,20758,20757,20756,20762,20769,20794,20791,20796,20795,20799,20800,20818,20812,20820,20834,31480,20841,20842,20846,20864,20866,22232,20876,20873,20879,20881,20883,20885,20886,20900,20902,20898,20905,20906,20907,20915,20913,20914,20912,20917,20925,20933,20937,20955,20960,34389,20969,20973,20976,20981,20990,20996,21003,21012,21006,21031,21034,21038,21043,21049,21071,21060,21067,21068,21086,21076,21098,21108,21097,21107,21119,21117,21133,21140,21138,21105,21128,21137,36776,36775,21164,21165,21180,21173,21185,21197,21207,21214,21219,21222,39149,21216,21235,21237,21240,21241,21254,21256,30008,21261,21264,21263,21269,21274,21283,21295,21297,21299,21304,21312,21318,21317,19991,21321,21325,20950,21342,21353,21358,22808,21371,21367,21378,21398,21408,21414,21413,21422,21424,21430,21443,31762,38617,21471,26364,29166,21486,21480,21485,21498,21505,21565,21568,21548,21549,21564,21550,21558,21545,21533,21582,21647,21621,21646,21599,21617,21623,21616,21650,21627,21632,21622,21636,21648,21638,21703,21666,21688,21669,21676,21700,21704,21672,21675,21698,21668,21694,21692,21720,21733,21734,21775,21780,21757,21742,21741,21754,21730,21817,21824,21859,21836,21806,21852,21829,21846,21847,21816,21811,21853,21913,21888,21679,21898,21919,21883,21886,21912,21918,21934,21884,21891,21929,21895,21928,21978,21957,21983,21956,21980,21988,21972,22036,22007,22038,22014,22013,22043,22009,22094,22096,29151,22068,22070,22066,22072,22123,22116,22063,22124,22122,22150,22144,22154,22176,22164,22159,22181,22190,22198,22196,22210,22204,22209,22211,22208,22216,22222,22225,22227,22231,22254,22265,22272,22271,22276,22281,22280,22283,22285,22291,22296,22294,21959,22300,22310,22327,22328,22350,22331,22336,22351,22377,22464,22408,22369,22399,22409,22419,22432,22451,22436,22442,22448,22467,22470,22484,22482,22483,22538,22486,22499,22539,22553,22557,22642,22561,22626,22603,22640,27584,22610,22589,22649,22661,22713,22687,22699,22714,22750,22715,22712,22702,22725,22739,22737,22743,22745,22744,22757,22748,22756,22751,22767,22778,22777,22779,22780,22781,22786,22794,22800,22811,26790,22821,22828,22829,22834,22840,22846,31442,22869,22864,22862,22874,22872,22882,22880,22887,22892,22889,22904,22913,22941,20318,20395,22947,22962,22982,23016,23004,22925,23001,23002,23077,23071,23057,23068,23049,23066,23104,23148,23113,23093,23094,23138,23146,23194,23228,23230,23243,23234,23229,23267,23255,23270,23273,23254,23290,23291,23308,23307,23318,23346,23248,23338,23350,23358,23363,23365,23360,23377,23381,23386,23387,23397,23401,23408,23411,23413,23416,25992,23418,23424,23427,23462,23480,23491,23495,23497,23508,23504,23524,23526,23522,23518,23525,23531,23536,23542,23539,23557,23559,23560,23565,23571,23584,23586,23592,23608,23609,23617,23622,23630,23635,23632,23631,23409,23660,23662,20066,23670,23673,23692,23697,23700,22939,23723,23739,23734,23740,23735,23749,23742,23751,23769,23785,23805,23802,23789,23948,23786,23819,23829,23831,23900,23839,23835,23825,23828,23842,23834,23833,23832,23884,23890,23886,23883,23916,23923,23926,23943,23940,23938,23970,23965,23980,23982,23997,23952,23991,23996,24009,24013,24019,24018,24022,24027,24043,24050,24053,24075,24090,24089,24081,24091,24118,24119,24132,24131,24128,24142,24151,24148,24159,24162,24164,24135,24181,24182,24186,40636,24191,24224,24257,24258,24264,24272,24271,24278,24291,24285,24282,24283,24290,24289,24296,24297,24300,24305,24307,24304,24308,24312,24318,24323,24329,24413,24412,24331,24337,24342,24361,24365,24376,24385,24392,24396,24398,24367,24401,24406,24407,24409,24417,24429,24435,24439,24451,24450,24447,24458,24456,24465,24455,24478,24473,24472,24480,24488,24493,24508,24534,24571,24548,24568,24561,24541,24755,24575,24609,24672,24601,24592,24617,24590,24625,24603,24597,24619,24614,24591,24634,24666,24641,24682,24695,24671,24650,24646,24653,24675,24643,24676,24642,24684,24683,24665,24705,24717,24807,24707,24730,24708,24731,24726,24727,24722,24743,24715,24801,24760,24800,24787,24756,24560,24765,24774,24757,24792,24909,24853,24838,24822,24823,24832,24820,24826,24835,24865,24827,24817,24845,24846,24903,24894,24872,24871,24906,24895,24892,24876,24884,24893,24898,24900,24947,24951,24920,24921,24922,24939,24948,24943,24933,24945,24927,24925,24915,24949,24985,24982,24967,25004,24980,24986,24970,24977,25003,25006,25036,25034,25033,25079,25032,25027,25030,25018,25035,32633,25037,25062,25059,25078,25082,25076,25087,25085,25084,25086,25088,25096,25097,25101,25100,25108,25115,25118,25121,25130,25134,25136,25138,25139,25153,25166,25182,25187,25179,25184,25192,25212,25218,25225,25214,25234,25235,25238,25300,25219,25236,25303,25297,25275,25295,25343,25286,25812,25288,25308,25292,25290,25282,25287,25243,25289,25356,25326,25329,25383,25346,25352,25327,25333,25424,25406,25421,25628,25423,25494,25486,25472,25515,25462,25507,25487,25481,25503,25525,25451,25449,25534,25577,25536,25542,25571,25545,25554,25590,25540,25622,25652,25606,25619,25638,25654,25885,25623,25640,25615,25703,25711,25718,25678,25898,25749,25747,25765,25769,25736,25788,25818,25810,25797,25799,25787,25816,25794,25841,25831,33289,25824,25825,25260,25827,25839,25900,25846,25844,25842,25850,25856,25853,25880,25884,25861,25892,25891,25899,25908,25909,25911,25910,25912,30027,25928,25942,25941,25933,25944,25950,25949,25970,25976,25986,25987,35722,26011,26015,26027,26039,26051,26054,26049,26052,26060,26066,26075,26073,26080,26081,26097,26482,26122,26115,26107,26483,26165,26166,26164,26140,26191,26180,26185,26177,26206,26205,26212,26215,26216,26207,26210,26224,26243,26248,26254,26249,26244,26264,26269,26305,26297,26313,26302,26300,26308,26296,26326,26330,26336,26175,26342,26345,26352,26357,26359,26383,26390,26398,26406,26407,38712,26414,26431,26422,26433,26424,26423,26438,26462,26464,26457,26467,26468,26505,26480,26537,26492,26474,26508,26507,26534,26529,26501,26551,26607,26548,26604,26547,26601,26552,26596,26590,26589,26594,26606,26553,26574,26566,26599,27292,26654,26694,26665,26688,26701,26674,26702,26803,26667,26713,26723,26743,26751,26783,26767,26797,26772,26781,26779,26755,27310,26809,26740,26805,26784,26810,26895,26765,26750,26881,26826,26888,26840,26914,26918,26849,26892,26829,26836,26855,26837,26934,26898,26884,26839,26851,26917,26873,26848,26863,26920,26922,26906,26915,26913,26822,27001,26999,26972,27000,26987,26964,27006,26990,26937,26996,26941,26969,26928,26977,26974,26973,27009,26986,27058,27054,27088,27071,27073,27091,27070,27086,23528,27082,27101,27067,27075,27047,27182,27025,27040,27036,27029,27060,27102,27112,27138,27163,27135,27402,27129,27122,27111,27141,27057,27166,27117,27156,27115,27146,27154,27329,27171,27155,27204,27148,27250,27190,27256,27207,27234,27225,27238,27208,27192,27170,27280,27277,27296,27268,27298,27299,27287,34327,27323,27331,27330,27320,27315,27308,27358,27345,27359,27306,27354,27370,27387,27397,34326,27386,27410,27414,39729,27423,27448,27447,30428,27449,39150,27463,27459,27465,27472,27481,27476,27483,27487,27489,27512,27513,27519,27520,27524,27523,27533,27544,27541,27550,27556,27562,27563,27567,27570,27569,27571,27575,27580,27590,27595,27603,27615,27628,27627,27635,27631,40638,27656,27667,27668,27675,27684,27683,27742,27733,27746,27754,27778,27789,27802,27777,27803,27774,27752,27763,27794,27792,27844,27889,27859,27837,27863,27845,27869,27822,27825,27838,27834,27867,27887,27865,27882,27935,34893,27958,27947,27965,27960,27929,27957,27955,27922,27916,28003,28051,28004,27994,28025,27993,28046,28053,28644,28037,28153,28181,28170,28085,28103,28134,28088,28102,28140,28126,28108,28136,28114,28101,28154,28121,28132,28117,28138,28142,28205,28270,28206,28185,28274,28255,28222,28195,28267,28203,28278,28237,28191,28227,28218,28238,28196,28415,28189,28216,28290,28330,28312,28361,28343,28371,28349,28335,28356,28338,28372,28373,28303,28325,28354,28319,28481,28433,28748,28396,28408,28414,28479,28402,28465,28399,28466,28364,28478,28435,28407,28550,28538,28536,28545,28544,28527,28507,28659,28525,28546,28540,28504,28558,28561,28610,28518,28595,28579,28577,28580,28601,28614,28586,28639,28629,28652,28628,28632,28657,28654,28635,28681,28683,28666,28689,28673,28687,28670,28699,28698,28532,28701,28696,28703,28720,28734,28722,28753,28771,28825,28818,28847,28913,28844,28856,28851,28846,28895,28875,28893,28889,28937,28925,28956,28953,29029,29013,29064,29030,29026,29004,29014,29036,29071,29179,29060,29077,29096,29100,29143,29113,29118,29138,29129,29140,29134,29152,29164,29159,29173,29180,29177,29183,29197,29200,29211,29224,29229,29228,29232,29234,29243,29244,29247,29248,29254,29259,29272,29300,29310,29314,29313,29319,29330,29334,29346,29351,29369,29362,29379,29382,29380,29390,29394,29410,29408,29409,29433,29431,20495,29463,29450,29468,29462,29469,29492,29487,29481,29477,29502,29518,29519,40664,29527,29546,29544,29552,29560,29557,29563,29562,29640,29619,29646,29627,29632,29669,29678,29662,29858,29701,29807,29733,29688,29746,29754,29781,29759,29791,29785,29761,29788,29801,29808,29795,29802,29814,29822,29835,29854,29863,29898,29903,29908,29681,29920,29923,29927,29929,29934,29938,29936,29937,29944,29943,29956,29955,29957,29964,29966,29965,29973,29971,29982,29990,29996,30012,30020,30029,30026,30025,30043,30022,30042,30057,30052,30055,30059,30061,30072,30070,30086,30087,30068,30090,30089,30082,30100,30106,30109,30117,30115,30146,30131,30147,30133,30141,30136,30140,30129,30157,30154,30162,30169,30179,30174,30206,30207,30204,30209,30192,30202,30194,30195,30219,30221,30217,30239,30247,30240,30241,30242,30244,30260,30256,30267,30279,30280,30278,30300,30296,30305,30306,30312,30313,30314,30311,30316,30320,30322,30326,30328,30332,30336,30339,30344,30347,30350,30358,30355,30361,30362,30384,30388,30392,30393,30394,30402,30413,30422,30418,30430,30433,30437,30439,30442,34351,30459,30472,30471,30468,30505,30500,30494,30501,30502,30491,30519,30520,30535,30554,30568,30571,30555,30565,30591,30590,30585,30606,30603,30609,30624,30622,30640,30646,30649,30655,30652,30653,30651,30663,30669,30679,30682,30684,30691,30702,30716,30732,30738,31014,30752,31018,30789,30862,30836,30854,30844,30874,30860,30883,30901,30890,30895,30929,30918,30923,30932,30910,30908,30917,30922,30956,30951,30938,30973,30964,30983,30994,30993,31001,31020,31019,31040,31072,31063,31071,31066,31061,31059,31098,31103,31114,31133,31143,40779,31146,31150,31155,31161,31162,31177,31189,31207,31212,31201,31203,31240,31245,31256,31257,31264,31263,31104,31281,31291,31294,31287,31299,31319,31305,31329,31330,31337,40861,31344,31353,31357,31368,31383,31381,31384,31382,31401,31432,31408,31414,31429,31428,31423,36995,31431,31434,31437,31439,31445,31443,31449,31450,31453,31457,31458,31462,31469,31472,31490,31503,31498,31494,31539,31512,31513,31518,31541,31528,31542,31568,31610,31492,31565,31499,31564,31557,31605,31589,31604,31591,31600,31601,31596,31598,31645,31640,31647,31629,31644,31642,31627,31634,31631,31581,31641,31691,31681,31692,31695,31668,31686,31709,31721,31761,31764,31718,31717,31840,31744,31751,31763,31731,31735,31767,31757,31734,31779,31783,31786,31775,31799,31787,31805,31820,31811,31828,31823,31808,31824,31832,31839,31844,31830,31845,31852,31861,31875,31888,31908,31917,31906,31915,31905,31912,31923,31922,31921,31918,31929,31933,31936,31941,31938,31960,31954,31964,31970,39739,31983,31986,31988,31990,31994,32006,32002,32028,32021,32010,32069,32075,32046,32050,32063,32053,32070,32115,32086,32078,32114,32104,32110,32079,32099,32147,32137,32091,32143,32125,32155,32186,32174,32163,32181,32199,32189,32171,32317,32162,32175,32220,32184,32159,32176,32216,32221,32228,32222,32251,32242,32225,32261,32266,32291,32289,32274,32305,32287,32265,32267,32290,32326,32358,32315,32309,32313,32323,32311,32306,32314,32359,32349,32342,32350,32345,32346,32377,32362,32361,32380,32379,32387,32213,32381,36782,32383,32392,32393,32396,32402,32400,32403,32404,32406,32398,32411,32412,32568,32570,32581,32588,32589,32590,32592,32593,32597,32596,32600,32607,32608,32616,32617,32615,32632,32642,32646,32643,32648,32647,32652,32660,32670,32669,32666,32675,32687,32690,32697,32686,32694,32696,35697,32709,32710,32714,32725,32724,32737,32742,32745,32755,32761,39132,32774,32772,32779,32786,32792,32793,32796,32801,32808,32831,32827,32842,32838,32850,32856,32858,32863,32866,32872,32883,32882,32880,32886,32889,32893,32895,32900,32902,32901,32923,32915,32922,32941,20880,32940,32987,32997,32985,32989,32964,32986,32982,33033,33007,33009,33051,33065,33059,33071,33099,38539,33094,33086,33107,33105,33020,33137,33134,33125,33126,33140,33155,33160,33162,33152,33154,33184,33173,33188,33187,33119,33171,33193,33200,33205,33214,33208,33213,33216,33218,33210,33225,33229,33233,33241,33240,33224,33242,33247,33248,33255,33274,33275,33278,33281,33282,33285,33287,33290,33293,33296,33302,33321,33323,33336,33331,33344,33369,33368,33373,33370,33375,33380,33378,33384,33386,33387,33326,33393,33399,33400,33406,33421,33426,33451,33439,33467,33452,33505,33507,33503,33490,33524,33523,33530,33683,33539,33531,33529,33502,33542,33500,33545,33497,33589,33588,33558,33586,33585,33600,33593,33616,33605,33583,33579,33559,33560,33669,33690,33706,33695,33698,33686,33571,33678,33671,33674,33660,33717,33651,33653,33696,33673,33704,33780,33811,33771,33742,33789,33795,33752,33803,33729,33783,33799,33760,33778,33805,33826,33824,33725,33848,34054,33787,33901,33834,33852,34138,33924,33911,33899,33965,33902,33922,33897,33862,33836,33903,33913,33845,33994,33890,33977,33983,33951,34009,33997,33979,34010,34000,33985,33990,34006,33953,34081,34047,34036,34071,34072,34092,34079,34069,34068,34044,34112,34147,34136,34120,34113,34306,34123,34133,34176,34212,34184,34193,34186,34216,34157,34196,34203,34282,34183,34204,34167,34174,34192,34249,34234,34255,34233,34256,34261,34269,34277,34268,34297,34314,34323,34315,34302,34298,34310,34338,34330,34352,34367,34381,20053,34388,34399,34407,34417,34451,34467,34473,34474,34443,34444,34486,34479,34500,34502,34480,34505,34851,34475,34516,34526,34537,34540,34527,34523,34543,34578,34566,34568,34560,34563,34555,34577,34569,34573,34553,34570,34612,34623,34615,34619,34597,34601,34586,34656,34655,34680,34636,34638,34676,34647,34664,34670,34649,34643,34659,34666,34821,34722,34719,34690,34735,34763,34749,34752,34768,38614,34731,34756,34739,34759,34758,34747,34799,34802,34784,34831,34829,34814,34806,34807,34830,34770,34833,34838,34837,34850,34849,34865,34870,34873,34855,34875,34884,34882,34898,34905,34910,34914,34923,34945,34942,34974,34933,34941,34997,34930,34946,34967,34962,34990,34969,34978,34957,34980,34992,35007,34993,35011,35012,35028,35032,35033,35037,35065,35074,35068,35060,35048,35058,35076,35084,35082,35091,35139,35102,35109,35114,35115,35137,35140,35131,35126,35128,35148,35101,35168,35166,35174,35172,35181,35178,35183,35188,35191,35198,35203,35208,35210,35219,35224,35233,35241,35238,35244,35247,35250,35258,35261,35263,35264,35290,35292,35293,35303,35316,35320,35331,35350,35344,35340,35355,35357,35365,35382,35393,35419,35410,35398,35400,35452,35437,35436,35426,35461,35458,35460,35496,35489,35473,35493,35494,35482,35491,35524,35533,35522,35546,35563,35571,35559,35556,35569,35604,35552,35554,35575,35550,35547,35596,35591,35610,35553,35606,35600,35607,35616,35635,38827,35622,35627,35646,35624,35649,35660,35663,35662,35657,35670,35675,35674,35691,35679,35692,35695,35700,35709,35712,35724,35726,35730,35731,35734,35737,35738,35898,35905,35903,35912,35916,35918,35920,35925,35938,35948,35960,35962,35970,35977,35973,35978,35981,35982,35988,35964,35992,25117,36013,36010,36029,36018,36019,36014,36022,36040,36033,36068,36067,36058,36093,36090,36091,36100,36101,36106,36103,36111,36109,36112,40782,36115,36045,36116,36118,36199,36205,36209,36211,36225,36249,36290,36286,36282,36303,36314,36310,36300,36315,36299,36330,36331,36319,36323,36348,36360,36361,36351,36381,36382,36368,36383,36418,36405,36400,36404,36426,36423,36425,36428,36432,36424,36441,36452,36448,36394,36451,36437,36470,36466,36476,36481,36487,36485,36484,36491,36490,36499,36497,36500,36505,36522,36513,36524,36528,36550,36529,36542,36549,36552,36555,36571,36579,36604,36603,36587,36606,36618,36613,36629,36626,36633,36627,36636,36639,36635,36620,36646,36659,36667,36665,36677,36674,36670,36684,36681,36678,36686,36695,36700,36706,36707,36708,36764,36767,36771,36781,36783,36791,36826,36837,36834,36842,36847,36999,36852,36869,36857,36858,36881,36885,36897,36877,36894,36886,36875,36903,36918,36917,36921,36856,36943,36944,36945,36946,36878,36937,36926,36950,36952,36958,36968,36975,36982,38568,36978,36994,36989,36993,36992,37002,37001,37007,37032,37039,37041,37045,37090,37092,25160,37083,37122,37138,37145,37170,37168,37194,37206,37208,37219,37221,37225,37235,37234,37259,37257,37250,37282,37291,37295,37290,37301,37300,37306,37312,37313,37321,37323,37328,37334,37343,37345,37339,37372,37365,37366,37406,37375,37396,37420,37397,37393,37470,37463,37445,37449,37476,37448,37525,37439,37451,37456,37532,37526,37523,37531,37466,37583,37561,37559,37609,37647,37626,37700,37678,37657,37666,37658,37667,37690,37685,37691,37724,37728,37756,37742,37718,37808,37804,37805,37780,37817,37846,37847,37864,37861,37848,37827,37853,37840,37832,37860,37914,37908,37907,37891,37895,37904,37942,37931,37941,37921,37946,37953,37970,37956,37979,37984,37986,37982,37994,37417,38000,38005,38007,38013,37978,38012,38014,38017,38015,38274,38279,38282,38292,38294,38296,38297,38304,38312,38311,38317,38332,38331,38329,38334,38346,28662,38339,38349,38348,38357,38356,38358,38364,38369,38373,38370,38433,38440,38446,38447,38466,38476,38479,38475,38519,38492,38494,38493,38495,38502,38514,38508,38541,38552,38549,38551,38570,38567,38577,38578,38576,38580,38582,38584,38585,38606,38603,38601,38605,35149,38620,38669,38613,38649,38660,38662,38664,38675,38670,38673,38671,38678,38681,38692,38698,38704,38713,38717,38718,38724,38726,38728,38722,38729,38748,38752,38756,38758,38760,21202,38763,38769,38777,38789,38780,38785,38778,38790,38795,38799,38800,38812,38824,38822,38819,38835,38836,38851,38854,38856,38859,38876,38893,40783,38898,31455,38902,38901,38927,38924,38968,38948,38945,38967,38973,38982,38991,38987,39019,39023,39024,39025,39028,39027,39082,39087,39089,39094,39108,39107,39110,39145,39147,39171,39177,39186,39188,39192,39201,39197,39198,39204,39200,39212,39214,39229,39230,39234,39241,39237,39248,39243,39249,39250,39244,39253,39319,39320,39333,39341,39342,39356,39391,39387,39389,39384,39377,39405,39406,39409,39410,39419,39416,39425,39439,39429,39394,39449,39467,39479,39493,39490,39488,39491,39486,39509,39501,39515,39511,39519,39522,39525,39524,39529,39531,39530,39597,39600,39612,39616,39631,39633,39635,39636,39646,39647,39650,39651,39654,39663,39659,39662,39668,39665,39671,39675,39686,39704,39706,39711,39714,39715,39717,39719,39720,39721,39722,39726,39727,39730,39748,39747,39759,39757,39758,39761,39768,39796,39827,39811,39825,39830,39831,39839,39840,39848,39860,39872,39882,39865,39878,39887,39889,39890,39907,39906,39908,39892,39905,39994,39922,39921,39920,39957,39956,39945,39955,39948,39942,39944,39954,39946,39940,39982,39963,39973,39972,39969,39984,40007,39986,40006,39998,40026,40032,40039,40054,40056,40167,40172,40176,40201,40200,40171,40195,40198,40234,40230,40367,40227,40223,40260,40213,40210,40257,40255,40254,40262,40264,40285,40286,40292,40273,40272,40281,40306,40329,40327,40363,40303,40314,40346,40356,40361,40370,40388,40385,40379,40376,40378,40390,40399,40386,40409,40403,40440,40422,40429,40431,40445,40474,40475,40478,40565,40569,40573,40577,40584,40587,40588,40594,40597,40593,40605,40613,40617,40632,40618,40621,38753,40652,40654,40655,40656,40660,40668,40670,40669,40672,40677,40680,40687,40692,40694,40695,40697,40699,40700,40701,40711,40712,30391,40725,40737,40748,40766,40778,40786,40788,40803,40799,40800,40801,40806,40807,40812,40810,40823,40818,40822,40853,40860,40864,22575,27079,36953,29796,20956,29081,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,32394,35100,37704,37512,34012,20425,28859,26161,26824,37625,26363,24389,20008,20193,20220,20224,20227,20281,20310,20370,20362,20378,20372,20429,20544,20514,20479,20510,20550,20592,20546,20628,20724,20696,20810,20836,20893,20926,20972,21013,21148,21158,21184,21211,21248,21255,21284,21362,21395,21426,21469,64014,21660,21642,21673,21759,21894,22361,22373,22444,22472,22471,64015,64016,22686,22706,22795,22867,22875,22877,22883,22948,22970,23382,23488,29999,23512,23532,23582,23718,23738,23797,23847,23891,64017,23874,23917,23992,23993,24016,24353,24372,24423,24503,24542,24669,24709,24714,24798,24789,24864,24818,24849,24887,24880,24984,25107,25254,25589,25696,25757,25806,25934,26112,26133,26171,26121,26158,26142,26148,26213,26199,26201,64018,26227,26265,26272,26290,26303,26362,26382,63785,26470,26555,26706,26560,26625,26692,26831,64019,26984,64020,27032,27106,27184,27243,27206,27251,27262,27362,27364,27606,27711,27740,27782,27759,27866,27908,28039,28015,28054,28076,28111,28152,28146,28156,28217,28252,28199,28220,28351,28552,28597,28661,28677,28679,28712,28805,28843,28943,28932,29020,28998,28999,64021,29121,29182,29361,29374,29476,64022,29559,29629,29641,29654,29667,29650,29703,29685,29734,29738,29737,29742,29794,29833,29855,29953,30063,30338,30364,30366,30363,30374,64023,30534,21167,30753,30798,30820,30842,31024,64024,64025,64026,31124,64027,31131,31441,31463,64028,31467,31646,64029,32072,32092,32183,32160,32214,32338,32583,32673,64030,33537,33634,33663,33735,33782,33864,33972,34131,34137,34155,64031,34224,64032,64033,34823,35061,35346,35383,35449,35495,35518,35551,64034,35574,35667,35711,36080,36084,36114,36214,64035,36559,64036,64037,36967,37086,64038,37141,37159,37338,37335,37342,37357,37358,37348,37349,37382,37392,37386,37434,37440,37436,37454,37465,37457,37433,37479,37543,37495,37496,37607,37591,37593,37584,64039,37589,37600,37587,37669,37665,37627,64040,37662,37631,37661,37634,37744,37719,37796,37830,37854,37880,37937,37957,37960,38290,63964,64041,38557,38575,38707,38715,38723,38733,38735,38737,38741,38999,39013,64042,64043,39207,64044,39326,39502,39641,39644,39797,39794,39823,39857,39867,39936,40304,40299,64045,40473,40657,null,null,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,65506,65508,65287,65282,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,65506,65508,65287,65282,12849,8470,8481,8757,32394,35100,37704,37512,34012,20425,28859,26161,26824,37625,26363,24389,20008,20193,20220,20224,20227,20281,20310,20370,20362,20378,20372,20429,20544,20514,20479,20510,20550,20592,20546,20628,20724,20696,20810,20836,20893,20926,20972,21013,21148,21158,21184,21211,21248,21255,21284,21362,21395,21426,21469,64014,21660,21642,21673,21759,21894,22361,22373,22444,22472,22471,64015,64016,22686,22706,22795,22867,22875,22877,22883,22948,22970,23382,23488,29999,23512,23532,23582,23718,23738,23797,23847,23891,64017,23874,23917,23992,23993,24016,24353,24372,24423,24503,24542,24669,24709,24714,24798,24789,24864,24818,24849,24887,24880,24984,25107,25254,25589,25696,25757,25806,25934,26112,26133,26171,26121,26158,26142,26148,26213,26199,26201,64018,26227,26265,26272,26290,26303,26362,26382,63785,26470,26555,26706,26560,26625,26692,26831,64019,26984,64020,27032,27106,27184,27243,27206,27251,27262,27362,27364,27606,27711,27740,27782,27759,27866,27908,28039,28015,28054,28076,28111,28152,28146,28156,28217,28252,28199,28220,28351,28552,28597,28661,28677,28679,28712,28805,28843,28943,28932,29020,28998,28999,64021,29121,29182,29361,29374,29476,64022,29559,29629,29641,29654,29667,29650,29703,29685,29734,29738,29737,29742,29794,29833,29855,29953,30063,30338,30364,30366,30363,30374,64023,30534,21167,30753,30798,30820,30842,31024,64024,64025,64026,31124,64027,31131,31441,31463,64028,31467,31646,64029,32072,32092,32183,32160,32214,32338,32583,32673,64030,33537,33634,33663,33735,33782,33864,33972,34131,34137,34155,64031,34224,64032,64033,34823,35061,35346,35383,35449,35495,35518,35551,64034,35574,35667,35711,36080,36084,36114,36214,64035,36559,64036,64037,36967,37086,64038,37141,37159,37338,37335,37342,37357,37358,37348,37349,37382,37392,37386,37434,37440,37436,37454,37465,37457,37433,37479,37543,37495,37496,37607,37591,37593,37584,64039,37589,37600,37587,37669,37665,37627,64040,37662,37631,37661,37634,37744,37719,37796,37830,37854,37880,37937,37957,37960,38290,63964,64041,38557,38575,38707,38715,38723,38733,38735,38737,38741,38999,39013,64042,64043,39207,64044,39326,39502,39641,39644,39797,39794,39823,39857,39867,39936,40304,40299,64045,40473,40657,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null], + "jis0212":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,728,711,184,729,733,175,731,730,65374,900,901,null,null,null,null,null,null,null,null,161,166,191,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,186,170,169,174,8482,164,8470,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,902,904,905,906,938,null,908,null,910,939,null,911,null,null,null,null,940,941,942,943,970,912,972,962,973,971,944,974,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1038,1039,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1118,1119,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,198,272,null,294,null,306,null,321,319,null,330,216,338,null,358,222,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,230,273,240,295,305,307,312,322,320,329,331,248,339,223,359,254,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,193,192,196,194,258,461,256,260,197,195,262,264,268,199,266,270,201,200,203,202,282,278,274,280,null,284,286,290,288,292,205,204,207,206,463,304,298,302,296,308,310,313,317,315,323,327,325,209,211,210,214,212,465,336,332,213,340,344,342,346,348,352,350,356,354,218,217,220,219,364,467,368,362,370,366,360,471,475,473,469,372,221,376,374,377,381,379,null,null,null,null,null,null,null,225,224,228,226,259,462,257,261,229,227,263,265,269,231,267,271,233,232,235,234,283,279,275,281,501,285,287,null,289,293,237,236,239,238,464,null,299,303,297,309,311,314,318,316,324,328,326,241,243,242,246,244,466,337,333,245,341,345,343,347,349,353,351,357,355,250,249,252,251,365,468,369,363,371,367,361,472,476,474,470,373,253,255,375,378,382,380,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,19970,19972,19973,19980,19986,19999,20003,20004,20008,20011,20014,20015,20016,20021,20032,20033,20036,20039,20049,20058,20060,20067,20072,20073,20084,20085,20089,20095,20109,20118,20119,20125,20143,20153,20163,20176,20186,20187,20192,20193,20194,20200,20207,20209,20211,20213,20221,20222,20223,20224,20226,20227,20232,20235,20236,20242,20245,20246,20247,20249,20270,20273,20320,20275,20277,20279,20281,20283,20286,20288,20290,20296,20297,20299,20300,20306,20308,20310,20312,20319,20323,20330,20332,20334,20337,20343,20344,20345,20346,20349,20350,20353,20354,20356,20357,20361,20362,20364,20366,20368,20370,20371,20372,20375,20377,20378,20382,20383,20402,20407,20409,20411,20412,20413,20414,20416,20417,20421,20422,20424,20425,20427,20428,20429,20431,20434,20444,20448,20450,20464,20466,20476,20477,20479,20480,20481,20484,20487,20490,20492,20494,20496,20499,20503,20504,20507,20508,20509,20510,20514,20519,20526,20528,20530,20531,20533,20544,20545,20546,20549,20550,20554,20556,20558,20561,20562,20563,20567,20569,20575,20576,20578,20579,20582,20583,20586,20589,20592,20593,20539,20609,20611,20612,20614,20618,20622,20623,20624,20626,20627,20628,20630,20635,20636,20638,20639,20640,20641,20642,20650,20655,20656,20665,20666,20669,20672,20675,20676,20679,20684,20686,20688,20691,20692,20696,20700,20701,20703,20706,20708,20710,20712,20713,20719,20721,20726,20730,20734,20739,20742,20743,20744,20747,20748,20749,20750,20722,20752,20759,20761,20763,20764,20765,20766,20771,20775,20776,20780,20781,20783,20785,20787,20788,20789,20792,20793,20802,20810,20815,20819,20821,20823,20824,20831,20836,20838,20862,20867,20868,20875,20878,20888,20893,20897,20899,20909,20920,20922,20924,20926,20927,20930,20936,20943,20945,20946,20947,20949,20952,20958,20962,20965,20974,20978,20979,20980,20983,20993,20994,20997,21010,21011,21013,21014,21016,21026,21032,21041,21042,21045,21052,21061,21065,21077,21079,21080,21082,21084,21087,21088,21089,21094,21102,21111,21112,21113,21120,21122,21125,21130,21132,21139,21141,21142,21143,21144,21146,21148,21156,21157,21158,21159,21167,21168,21174,21175,21176,21178,21179,21181,21184,21188,21190,21192,21196,21199,21201,21204,21206,21211,21212,21217,21221,21224,21225,21226,21228,21232,21233,21236,21238,21239,21248,21251,21258,21259,21260,21265,21267,21272,21275,21276,21278,21279,21285,21287,21288,21289,21291,21292,21293,21296,21298,21301,21308,21309,21310,21314,21324,21323,21337,21339,21345,21347,21349,21356,21357,21362,21369,21374,21379,21383,21384,21390,21395,21396,21401,21405,21409,21412,21418,21419,21423,21426,21428,21429,21431,21432,21434,21437,21440,21445,21455,21458,21459,21461,21466,21469,21470,21472,21478,21479,21493,21506,21523,21530,21537,21543,21544,21546,21551,21553,21556,21557,21571,21572,21575,21581,21583,21598,21602,21604,21606,21607,21609,21611,21613,21614,21620,21631,21633,21635,21637,21640,21641,21645,21649,21653,21654,21660,21663,21665,21670,21671,21673,21674,21677,21678,21681,21687,21689,21690,21691,21695,21702,21706,21709,21710,21728,21738,21740,21743,21750,21756,21758,21759,21760,21761,21765,21768,21769,21772,21773,21774,21781,21802,21803,21810,21813,21814,21819,21820,21821,21825,21831,21833,21834,21837,21840,21841,21848,21850,21851,21854,21856,21857,21860,21862,21887,21889,21890,21894,21896,21902,21903,21905,21906,21907,21908,21911,21923,21924,21933,21938,21951,21953,21955,21958,21961,21963,21964,21966,21969,21970,21971,21975,21976,21979,21982,21986,21993,22006,22015,22021,22024,22026,22029,22030,22031,22032,22033,22034,22041,22060,22064,22067,22069,22071,22073,22075,22076,22077,22079,22080,22081,22083,22084,22086,22089,22091,22093,22095,22100,22110,22112,22113,22114,22115,22118,22121,22125,22127,22129,22130,22133,22148,22149,22152,22155,22156,22165,22169,22170,22173,22174,22175,22182,22183,22184,22185,22187,22188,22189,22193,22195,22199,22206,22213,22217,22218,22219,22223,22224,22220,22221,22233,22236,22237,22239,22241,22244,22245,22246,22247,22248,22257,22251,22253,22262,22263,22273,22274,22279,22282,22284,22289,22293,22298,22299,22301,22304,22306,22307,22308,22309,22313,22314,22316,22318,22319,22323,22324,22333,22334,22335,22341,22342,22348,22349,22354,22370,22373,22375,22376,22379,22381,22382,22383,22384,22385,22387,22388,22389,22391,22393,22394,22395,22396,22398,22401,22403,22412,22420,22423,22425,22426,22428,22429,22430,22431,22433,22421,22439,22440,22441,22444,22456,22461,22471,22472,22476,22479,22485,22493,22494,22500,22502,22503,22505,22509,22512,22517,22518,22520,22525,22526,22527,22531,22532,22536,22537,22497,22540,22541,22555,22558,22559,22560,22566,22567,22573,22578,22585,22591,22601,22604,22605,22607,22608,22613,22623,22625,22628,22631,22632,22648,22652,22655,22656,22657,22663,22664,22665,22666,22668,22669,22671,22672,22676,22678,22685,22688,22689,22690,22694,22697,22705,22706,22724,22716,22722,22728,22733,22734,22736,22738,22740,22742,22746,22749,22753,22754,22761,22771,22789,22790,22795,22796,22802,22803,22804,34369,22813,22817,22819,22820,22824,22831,22832,22835,22837,22838,22847,22851,22854,22866,22867,22873,22875,22877,22878,22879,22881,22883,22891,22893,22895,22898,22901,22902,22905,22907,22908,22923,22924,22926,22930,22933,22935,22943,22948,22951,22957,22958,22959,22960,22963,22967,22970,22972,22977,22979,22980,22984,22986,22989,22994,23005,23006,23007,23011,23012,23015,23022,23023,23025,23026,23028,23031,23040,23044,23052,23053,23054,23058,23059,23070,23075,23076,23079,23080,23082,23085,23088,23108,23109,23111,23112,23116,23120,23125,23134,23139,23141,23143,23149,23159,23162,23163,23166,23179,23184,23187,23190,23193,23196,23198,23199,23200,23202,23207,23212,23217,23218,23219,23221,23224,23226,23227,23231,23236,23238,23240,23247,23258,23260,23264,23269,23274,23278,23285,23286,23293,23296,23297,23304,23319,23348,23321,23323,23325,23329,23333,23341,23352,23361,23371,23372,23378,23382,23390,23400,23406,23407,23420,23421,23422,23423,23425,23428,23430,23434,23438,23440,23441,23443,23444,23446,23464,23465,23468,23469,23471,23473,23474,23479,23482,23484,23488,23489,23501,23503,23510,23511,23512,23513,23514,23520,23535,23537,23540,23549,23564,23575,23582,23583,23587,23590,23593,23595,23596,23598,23600,23602,23605,23606,23641,23642,23644,23650,23651,23655,23656,23657,23661,23664,23668,23669,23674,23675,23676,23677,23687,23688,23690,23695,23698,23709,23711,23712,23714,23715,23718,23722,23730,23732,23733,23738,23753,23755,23762,23773,23767,23790,23793,23794,23796,23809,23814,23821,23826,23851,23843,23844,23846,23847,23857,23860,23865,23869,23871,23874,23875,23878,23880,23893,23889,23897,23882,23903,23904,23905,23906,23908,23914,23917,23920,23929,23930,23934,23935,23937,23939,23944,23946,23954,23955,23956,23957,23961,23963,23967,23968,23975,23979,23984,23988,23992,23993,24003,24007,24011,24016,24014,24024,24025,24032,24036,24041,24056,24057,24064,24071,24077,24082,24084,24085,24088,24095,24096,24110,24104,24114,24117,24126,24139,24144,24137,24145,24150,24152,24155,24156,24158,24168,24170,24171,24172,24173,24174,24176,24192,24203,24206,24226,24228,24229,24232,24234,24236,24241,24243,24253,24254,24255,24262,24268,24267,24270,24273,24274,24276,24277,24284,24286,24293,24299,24322,24326,24327,24328,24334,24345,24348,24349,24353,24354,24355,24356,24360,24363,24364,24366,24368,24372,24374,24379,24381,24383,24384,24388,24389,24391,24397,24400,24404,24408,24411,24416,24419,24420,24423,24431,24434,24436,24437,24440,24442,24445,24446,24457,24461,24463,24470,24476,24477,24482,24487,24491,24484,24492,24495,24496,24497,24504,24516,24519,24520,24521,24523,24528,24529,24530,24531,24532,24542,24545,24546,24552,24553,24554,24556,24557,24558,24559,24562,24563,24566,24570,24572,24583,24586,24589,24595,24596,24599,24600,24602,24607,24612,24621,24627,24629,24640,24647,24648,24649,24652,24657,24660,24662,24663,24669,24673,24679,24689,24702,24703,24706,24710,24712,24714,24718,24721,24723,24725,24728,24733,24734,24738,24740,24741,24744,24752,24753,24759,24763,24766,24770,24772,24776,24777,24778,24779,24782,24783,24788,24789,24793,24795,24797,24798,24802,24805,24818,24821,24824,24828,24829,24834,24839,24842,24844,24848,24849,24850,24851,24852,24854,24855,24857,24860,24862,24866,24874,24875,24880,24881,24885,24886,24887,24889,24897,24901,24902,24905,24926,24928,24940,24946,24952,24955,24956,24959,24960,24961,24963,24964,24971,24973,24978,24979,24983,24984,24988,24989,24991,24992,24997,25000,25002,25005,25016,25017,25020,25024,25025,25026,25038,25039,25045,25052,25053,25054,25055,25057,25058,25063,25065,25061,25068,25069,25071,25089,25091,25092,25095,25107,25109,25116,25120,25122,25123,25127,25129,25131,25145,25149,25154,25155,25156,25158,25164,25168,25169,25170,25172,25174,25178,25180,25188,25197,25199,25203,25210,25213,25229,25230,25231,25232,25254,25256,25267,25270,25271,25274,25278,25279,25284,25294,25301,25302,25306,25322,25330,25332,25340,25341,25347,25348,25354,25355,25357,25360,25363,25366,25368,25385,25386,25389,25397,25398,25401,25404,25409,25410,25411,25412,25414,25418,25419,25422,25426,25427,25428,25432,25435,25445,25446,25452,25453,25457,25460,25461,25464,25468,25469,25471,25474,25476,25479,25482,25488,25492,25493,25497,25498,25502,25508,25510,25517,25518,25519,25533,25537,25541,25544,25550,25553,25555,25556,25557,25564,25568,25573,25578,25580,25586,25587,25589,25592,25593,25609,25610,25616,25618,25620,25624,25630,25632,25634,25636,25637,25641,25642,25647,25648,25653,25661,25663,25675,25679,25681,25682,25683,25684,25690,25691,25692,25693,25695,25696,25697,25699,25709,25715,25716,25723,25725,25733,25735,25743,25744,25745,25752,25753,25755,25757,25759,25761,25763,25766,25768,25772,25779,25789,25790,25791,25796,25801,25802,25803,25804,25806,25808,25809,25813,25815,25828,25829,25833,25834,25837,25840,25845,25847,25851,25855,25857,25860,25864,25865,25866,25871,25875,25876,25878,25881,25883,25886,25887,25890,25894,25897,25902,25905,25914,25916,25917,25923,25927,25929,25936,25938,25940,25951,25952,25959,25963,25978,25981,25985,25989,25994,26002,26005,26008,26013,26016,26019,26022,26030,26034,26035,26036,26047,26050,26056,26057,26062,26064,26068,26070,26072,26079,26096,26098,26100,26101,26105,26110,26111,26112,26116,26120,26121,26125,26129,26130,26133,26134,26141,26142,26145,26146,26147,26148,26150,26153,26154,26155,26156,26158,26160,26161,26163,26169,26167,26176,26181,26182,26186,26188,26193,26190,26199,26200,26201,26203,26204,26208,26209,26363,26218,26219,26220,26238,26227,26229,26239,26231,26232,26233,26235,26240,26236,26251,26252,26253,26256,26258,26265,26266,26267,26268,26271,26272,26276,26285,26289,26290,26293,26299,26303,26304,26306,26307,26312,26316,26318,26319,26324,26331,26335,26344,26347,26348,26350,26362,26373,26375,26382,26387,26393,26396,26400,26402,26419,26430,26437,26439,26440,26444,26452,26453,26461,26470,26476,26478,26484,26486,26491,26497,26500,26510,26511,26513,26515,26518,26520,26521,26523,26544,26545,26546,26549,26555,26556,26557,26617,26560,26562,26563,26565,26568,26569,26578,26583,26585,26588,26593,26598,26608,26610,26614,26615,26706,26644,26649,26653,26655,26664,26663,26668,26669,26671,26672,26673,26675,26683,26687,26692,26693,26698,26700,26709,26711,26712,26715,26731,26734,26735,26736,26737,26738,26741,26745,26746,26747,26748,26754,26756,26758,26760,26774,26776,26778,26780,26785,26787,26789,26793,26794,26798,26802,26811,26821,26824,26828,26831,26832,26833,26835,26838,26841,26844,26845,26853,26856,26858,26859,26860,26861,26864,26865,26869,26870,26875,26876,26877,26886,26889,26890,26896,26897,26899,26902,26903,26929,26931,26933,26936,26939,26946,26949,26953,26958,26967,26971,26979,26980,26981,26982,26984,26985,26988,26992,26993,26994,27002,27003,27007,27008,27021,27026,27030,27032,27041,27045,27046,27048,27051,27053,27055,27063,27064,27066,27068,27077,27080,27089,27094,27095,27106,27109,27118,27119,27121,27123,27125,27134,27136,27137,27139,27151,27153,27157,27162,27165,27168,27172,27176,27184,27186,27188,27191,27195,27198,27199,27205,27206,27209,27210,27214,27216,27217,27218,27221,27222,27227,27236,27239,27242,27249,27251,27262,27265,27267,27270,27271,27273,27275,27281,27291,27293,27294,27295,27301,27307,27311,27312,27313,27316,27325,27326,27327,27334,27337,27336,27340,27344,27348,27349,27350,27356,27357,27364,27367,27372,27376,27377,27378,27388,27389,27394,27395,27398,27399,27401,27407,27408,27409,27415,27419,27422,27428,27432,27435,27436,27439,27445,27446,27451,27455,27462,27466,27469,27474,27478,27480,27485,27488,27495,27499,27502,27504,27509,27517,27518,27522,27525,27543,27547,27551,27552,27554,27555,27560,27561,27564,27565,27566,27568,27576,27577,27581,27582,27587,27588,27593,27596,27606,27610,27617,27619,27622,27623,27630,27633,27639,27641,27647,27650,27652,27653,27657,27661,27662,27664,27666,27673,27679,27686,27687,27688,27692,27694,27699,27701,27702,27706,27707,27711,27722,27723,27725,27727,27730,27732,27737,27739,27740,27755,27757,27759,27764,27766,27768,27769,27771,27781,27782,27783,27785,27796,27797,27799,27800,27804,27807,27824,27826,27828,27842,27846,27853,27855,27856,27857,27858,27860,27862,27866,27868,27872,27879,27881,27883,27884,27886,27890,27892,27908,27911,27914,27918,27919,27921,27923,27930,27942,27943,27944,27751,27950,27951,27953,27961,27964,27967,27991,27998,27999,28001,28005,28007,28015,28016,28028,28034,28039,28049,28050,28052,28054,28055,28056,28074,28076,28084,28087,28089,28093,28095,28100,28104,28106,28110,28111,28118,28123,28125,28127,28128,28130,28133,28137,28143,28144,28148,28150,28156,28160,28164,28190,28194,28199,28210,28214,28217,28219,28220,28228,28229,28232,28233,28235,28239,28241,28242,28243,28244,28247,28252,28253,28254,28258,28259,28264,28275,28283,28285,28301,28307,28313,28320,28327,28333,28334,28337,28339,28347,28351,28352,28353,28355,28359,28360,28362,28365,28366,28367,28395,28397,28398,28409,28411,28413,28420,28424,28426,28428,28429,28438,28440,28442,28443,28454,28457,28458,28463,28464,28467,28470,28475,28476,28461,28495,28497,28498,28499,28503,28505,28506,28509,28510,28513,28514,28520,28524,28541,28542,28547,28551,28552,28555,28556,28557,28560,28562,28563,28564,28566,28570,28575,28576,28581,28582,28583,28584,28590,28591,28592,28597,28598,28604,28613,28615,28616,28618,28634,28638,28648,28649,28656,28661,28665,28668,28669,28672,28677,28678,28679,28685,28695,28704,28707,28719,28724,28727,28729,28732,28739,28740,28744,28745,28746,28747,28756,28757,28765,28766,28750,28772,28773,28780,28782,28789,28790,28798,28801,28805,28806,28820,28821,28822,28823,28824,28827,28836,28843,28848,28849,28852,28855,28874,28881,28883,28884,28885,28886,28888,28892,28900,28922,28931,28932,28933,28934,28935,28939,28940,28943,28958,28960,28971,28973,28975,28976,28977,28984,28993,28997,28998,28999,29002,29003,29008,29010,29015,29018,29020,29022,29024,29032,29049,29056,29061,29063,29068,29074,29082,29083,29088,29090,29103,29104,29106,29107,29114,29119,29120,29121,29124,29131,29132,29139,29142,29145,29146,29148,29176,29182,29184,29191,29192,29193,29203,29207,29210,29213,29215,29220,29227,29231,29236,29240,29241,29249,29250,29251,29253,29262,29263,29264,29267,29269,29270,29274,29276,29278,29280,29283,29288,29291,29294,29295,29297,29303,29304,29307,29308,29311,29316,29321,29325,29326,29331,29339,29352,29357,29358,29361,29364,29374,29377,29383,29385,29388,29397,29398,29400,29407,29413,29427,29428,29434,29435,29438,29442,29444,29445,29447,29451,29453,29458,29459,29464,29465,29470,29474,29476,29479,29480,29484,29489,29490,29493,29498,29499,29501,29507,29517,29520,29522,29526,29528,29533,29534,29535,29536,29542,29543,29545,29547,29548,29550,29551,29553,29559,29561,29564,29568,29569,29571,29573,29574,29582,29584,29587,29589,29591,29592,29596,29598,29599,29600,29602,29605,29606,29610,29611,29613,29621,29623,29625,29628,29629,29631,29637,29638,29641,29643,29644,29647,29650,29651,29654,29657,29661,29665,29667,29670,29671,29673,29684,29685,29687,29689,29690,29691,29693,29695,29696,29697,29700,29703,29706,29713,29722,29723,29732,29734,29736,29737,29738,29739,29740,29741,29742,29743,29744,29745,29753,29760,29763,29764,29766,29767,29771,29773,29777,29778,29783,29789,29794,29798,29799,29800,29803,29805,29806,29809,29810,29824,29825,29829,29830,29831,29833,29839,29840,29841,29842,29848,29849,29850,29852,29855,29856,29857,29859,29862,29864,29865,29866,29867,29870,29871,29873,29874,29877,29881,29883,29887,29896,29897,29900,29904,29907,29912,29914,29915,29918,29919,29924,29928,29930,29931,29935,29940,29946,29947,29948,29951,29958,29970,29974,29975,29984,29985,29988,29991,29993,29994,29999,30006,30009,30013,30014,30015,30016,30019,30023,30024,30030,30032,30034,30039,30046,30047,30049,30063,30065,30073,30074,30075,30076,30077,30078,30081,30085,30096,30098,30099,30101,30105,30108,30114,30116,30132,30138,30143,30144,30145,30148,30150,30156,30158,30159,30167,30172,30175,30176,30177,30180,30183,30188,30190,30191,30193,30201,30208,30210,30211,30212,30215,30216,30218,30220,30223,30226,30227,30229,30230,30233,30235,30236,30237,30238,30243,30245,30246,30249,30253,30258,30259,30261,30264,30265,30266,30268,30282,30272,30273,30275,30276,30277,30281,30283,30293,30297,30303,30308,30309,30317,30318,30319,30321,30324,30337,30341,30348,30349,30357,30363,30364,30365,30367,30368,30370,30371,30372,30373,30374,30375,30376,30378,30381,30397,30401,30405,30409,30411,30412,30414,30420,30425,30432,30438,30440,30444,30448,30449,30454,30457,30460,30464,30470,30474,30478,30482,30484,30485,30487,30489,30490,30492,30498,30504,30509,30510,30511,30516,30517,30518,30521,30525,30526,30530,30533,30534,30538,30541,30542,30543,30546,30550,30551,30556,30558,30559,30560,30562,30564,30567,30570,30572,30576,30578,30579,30580,30586,30589,30592,30596,30604,30605,30612,30613,30614,30618,30623,30626,30631,30634,30638,30639,30641,30645,30654,30659,30665,30673,30674,30677,30681,30686,30687,30688,30692,30694,30698,30700,30704,30705,30708,30712,30715,30725,30726,30729,30733,30734,30737,30749,30753,30754,30755,30765,30766,30768,30773,30775,30787,30788,30791,30792,30796,30798,30802,30812,30814,30816,30817,30819,30820,30824,30826,30830,30842,30846,30858,30863,30868,30872,30881,30877,30878,30879,30884,30888,30892,30893,30896,30897,30898,30899,30907,30909,30911,30919,30920,30921,30924,30926,30930,30931,30933,30934,30948,30939,30943,30944,30945,30950,30954,30962,30963,30976,30966,30967,30970,30971,30975,30982,30988,30992,31002,31004,31006,31007,31008,31013,31015,31017,31021,31025,31028,31029,31035,31037,31039,31044,31045,31046,31050,31051,31055,31057,31060,31064,31067,31068,31079,31081,31083,31090,31097,31099,31100,31102,31115,31116,31121,31123,31124,31125,31126,31128,31131,31132,31137,31144,31145,31147,31151,31153,31156,31160,31163,31170,31172,31175,31176,31178,31183,31188,31190,31194,31197,31198,31200,31202,31205,31210,31211,31213,31217,31224,31228,31234,31235,31239,31241,31242,31244,31249,31253,31259,31262,31265,31271,31275,31277,31279,31280,31284,31285,31288,31289,31290,31300,31301,31303,31304,31308,31317,31318,31321,31324,31325,31327,31328,31333,31335,31338,31341,31349,31352,31358,31360,31362,31365,31366,31370,31371,31376,31377,31380,31390,31392,31395,31404,31411,31413,31417,31419,31420,31430,31433,31436,31438,31441,31451,31464,31465,31467,31468,31473,31476,31483,31485,31486,31495,31508,31519,31523,31527,31529,31530,31531,31533,31534,31535,31536,31537,31540,31549,31551,31552,31553,31559,31566,31573,31584,31588,31590,31593,31594,31597,31599,31602,31603,31607,31620,31625,31630,31632,31633,31638,31643,31646,31648,31653,31660,31663,31664,31666,31669,31670,31674,31675,31676,31677,31682,31685,31688,31690,31700,31702,31703,31705,31706,31707,31720,31722,31730,31732,31733,31736,31737,31738,31740,31742,31745,31746,31747,31748,31750,31753,31755,31756,31758,31759,31769,31771,31776,31781,31782,31784,31788,31793,31795,31796,31798,31801,31802,31814,31818,31829,31825,31826,31827,31833,31834,31835,31836,31837,31838,31841,31843,31847,31849,31853,31854,31856,31858,31865,31868,31869,31878,31879,31887,31892,31902,31904,31910,31920,31926,31927,31930,31931,31932,31935,31940,31943,31944,31945,31949,31951,31955,31956,31957,31959,31961,31962,31965,31974,31977,31979,31989,32003,32007,32008,32009,32015,32017,32018,32019,32022,32029,32030,32035,32038,32042,32045,32049,32060,32061,32062,32064,32065,32071,32072,32077,32081,32083,32087,32089,32090,32092,32093,32101,32103,32106,32112,32120,32122,32123,32127,32129,32130,32131,32133,32134,32136,32139,32140,32141,32145,32150,32151,32157,32158,32166,32167,32170,32179,32182,32183,32185,32194,32195,32196,32197,32198,32204,32205,32206,32215,32217,32256,32226,32229,32230,32234,32235,32237,32241,32245,32246,32249,32250,32264,32272,32273,32277,32279,32284,32285,32288,32295,32296,32300,32301,32303,32307,32310,32319,32324,32325,32327,32334,32336,32338,32344,32351,32353,32354,32357,32363,32366,32367,32371,32376,32382,32385,32390,32391,32394,32397,32401,32405,32408,32410,32413,32414,32572,32571,32573,32574,32575,32579,32580,32583,32591,32594,32595,32603,32604,32605,32609,32611,32612,32613,32614,32621,32625,32637,32638,32639,32640,32651,32653,32655,32656,32657,32662,32663,32668,32673,32674,32678,32682,32685,32692,32700,32703,32704,32707,32712,32718,32719,32731,32735,32739,32741,32744,32748,32750,32751,32754,32762,32765,32766,32767,32775,32776,32778,32781,32782,32783,32785,32787,32788,32790,32797,32798,32799,32800,32804,32806,32812,32814,32816,32820,32821,32823,32825,32826,32828,32830,32832,32836,32864,32868,32870,32877,32881,32885,32897,32904,32910,32924,32926,32934,32935,32939,32952,32953,32968,32973,32975,32978,32980,32981,32983,32984,32992,33005,33006,33008,33010,33011,33014,33017,33018,33022,33027,33035,33046,33047,33048,33052,33054,33056,33060,33063,33068,33072,33077,33082,33084,33093,33095,33098,33100,33106,33111,33120,33121,33127,33128,33129,33133,33135,33143,33153,33168,33156,33157,33158,33163,33166,33174,33176,33179,33182,33186,33198,33202,33204,33211,33227,33219,33221,33226,33230,33231,33237,33239,33243,33245,33246,33249,33252,33259,33260,33264,33265,33266,33269,33270,33272,33273,33277,33279,33280,33283,33295,33299,33300,33305,33306,33309,33313,33314,33320,33330,33332,33338,33347,33348,33349,33350,33355,33358,33359,33361,33366,33372,33376,33379,33383,33389,33396,33403,33405,33407,33408,33409,33411,33412,33415,33417,33418,33422,33425,33428,33430,33432,33434,33435,33440,33441,33443,33444,33447,33448,33449,33450,33454,33456,33458,33460,33463,33466,33468,33470,33471,33478,33488,33493,33498,33504,33506,33508,33512,33514,33517,33519,33526,33527,33533,33534,33536,33537,33543,33544,33546,33547,33620,33563,33565,33566,33567,33569,33570,33580,33581,33582,33584,33587,33591,33594,33596,33597,33602,33603,33604,33607,33613,33614,33617,33621,33622,33623,33648,33656,33661,33663,33664,33666,33668,33670,33677,33682,33684,33685,33688,33689,33691,33692,33693,33702,33703,33705,33708,33726,33727,33728,33735,33737,33743,33744,33745,33748,33757,33619,33768,33770,33782,33784,33785,33788,33793,33798,33802,33807,33809,33813,33817,33709,33839,33849,33861,33863,33864,33866,33869,33871,33873,33874,33878,33880,33881,33882,33884,33888,33892,33893,33895,33898,33904,33907,33908,33910,33912,33916,33917,33921,33925,33938,33939,33941,33950,33958,33960,33961,33962,33967,33969,33972,33978,33981,33982,33984,33986,33991,33992,33996,33999,34003,34012,34023,34026,34031,34032,34033,34034,34039,34098,34042,34043,34045,34050,34051,34055,34060,34062,34064,34076,34078,34082,34083,34084,34085,34087,34090,34091,34095,34099,34100,34102,34111,34118,34127,34128,34129,34130,34131,34134,34137,34140,34141,34142,34143,34144,34145,34146,34148,34155,34159,34169,34170,34171,34173,34175,34177,34181,34182,34185,34187,34188,34191,34195,34200,34205,34207,34208,34210,34213,34215,34228,34230,34231,34232,34236,34237,34238,34239,34242,34247,34250,34251,34254,34221,34264,34266,34271,34272,34278,34280,34285,34291,34294,34300,34303,34304,34308,34309,34317,34318,34320,34321,34322,34328,34329,34331,34334,34337,34343,34345,34358,34360,34362,34364,34365,34368,34370,34374,34386,34387,34390,34391,34392,34393,34397,34400,34401,34402,34403,34404,34409,34412,34415,34421,34422,34423,34426,34445,34449,34454,34456,34458,34460,34465,34470,34471,34472,34477,34481,34483,34484,34485,34487,34488,34489,34495,34496,34497,34499,34501,34513,34514,34517,34519,34522,34524,34528,34531,34533,34535,34440,34554,34556,34557,34564,34565,34567,34571,34574,34575,34576,34579,34580,34585,34590,34591,34593,34595,34600,34606,34607,34609,34610,34617,34618,34620,34621,34622,34624,34627,34629,34637,34648,34653,34657,34660,34661,34671,34673,34674,34683,34691,34692,34693,34694,34695,34696,34697,34699,34700,34704,34707,34709,34711,34712,34713,34718,34720,34723,34727,34732,34733,34734,34737,34741,34750,34751,34753,34760,34761,34762,34766,34773,34774,34777,34778,34780,34783,34786,34787,34788,34794,34795,34797,34801,34803,34808,34810,34815,34817,34819,34822,34825,34826,34827,34832,34841,34834,34835,34836,34840,34842,34843,34844,34846,34847,34856,34861,34862,34864,34866,34869,34874,34876,34881,34883,34885,34888,34889,34890,34891,34894,34897,34901,34902,34904,34906,34908,34911,34912,34916,34921,34929,34937,34939,34944,34968,34970,34971,34972,34975,34976,34984,34986,35002,35005,35006,35008,35018,35019,35020,35021,35022,35025,35026,35027,35035,35038,35047,35055,35056,35057,35061,35063,35073,35078,35085,35086,35087,35093,35094,35096,35097,35098,35100,35104,35110,35111,35112,35120,35121,35122,35125,35129,35130,35134,35136,35138,35141,35142,35145,35151,35154,35159,35162,35163,35164,35169,35170,35171,35179,35182,35184,35187,35189,35194,35195,35196,35197,35209,35213,35216,35220,35221,35227,35228,35231,35232,35237,35248,35252,35253,35254,35255,35260,35284,35285,35286,35287,35288,35301,35305,35307,35309,35313,35315,35318,35321,35325,35327,35332,35333,35335,35343,35345,35346,35348,35349,35358,35360,35362,35364,35366,35371,35372,35375,35381,35383,35389,35390,35392,35395,35397,35399,35401,35405,35406,35411,35414,35415,35416,35420,35421,35425,35429,35431,35445,35446,35447,35449,35450,35451,35454,35455,35456,35459,35462,35467,35471,35472,35474,35478,35479,35481,35487,35495,35497,35502,35503,35507,35510,35511,35515,35518,35523,35526,35528,35529,35530,35537,35539,35540,35541,35543,35549,35551,35564,35568,35572,35573,35574,35580,35583,35589,35590,35595,35601,35612,35614,35615,35594,35629,35632,35639,35644,35650,35651,35652,35653,35654,35656,35666,35667,35668,35673,35661,35678,35683,35693,35702,35704,35705,35708,35710,35713,35716,35717,35723,35725,35727,35732,35733,35740,35742,35743,35896,35897,35901,35902,35909,35911,35913,35915,35919,35921,35923,35924,35927,35928,35931,35933,35929,35939,35940,35942,35944,35945,35949,35955,35957,35958,35963,35966,35974,35975,35979,35984,35986,35987,35993,35995,35996,36004,36025,36026,36037,36038,36041,36043,36047,36054,36053,36057,36061,36065,36072,36076,36079,36080,36082,36085,36087,36088,36094,36095,36097,36099,36105,36114,36119,36123,36197,36201,36204,36206,36223,36226,36228,36232,36237,36240,36241,36245,36254,36255,36256,36262,36267,36268,36271,36274,36277,36279,36281,36283,36288,36293,36294,36295,36296,36298,36302,36305,36308,36309,36311,36313,36324,36325,36327,36332,36336,36284,36337,36338,36340,36349,36353,36356,36357,36358,36363,36369,36372,36374,36384,36385,36386,36387,36390,36391,36401,36403,36406,36407,36408,36409,36413,36416,36417,36427,36429,36430,36431,36436,36443,36444,36445,36446,36449,36450,36457,36460,36461,36463,36464,36465,36473,36474,36475,36482,36483,36489,36496,36498,36501,36506,36507,36509,36510,36514,36519,36521,36525,36526,36531,36533,36538,36539,36544,36545,36547,36548,36551,36559,36561,36564,36572,36584,36590,36592,36593,36599,36601,36602,36589,36608,36610,36615,36616,36623,36624,36630,36631,36632,36638,36640,36641,36643,36645,36647,36648,36652,36653,36654,36660,36661,36662,36663,36666,36672,36673,36675,36679,36687,36689,36690,36691,36692,36693,36696,36701,36702,36709,36765,36768,36769,36772,36773,36774,36789,36790,36792,36798,36800,36801,36806,36810,36811,36813,36816,36818,36819,36821,36832,36835,36836,36840,36846,36849,36853,36854,36859,36862,36866,36868,36872,36876,36888,36891,36904,36905,36911,36906,36908,36909,36915,36916,36919,36927,36931,36932,36940,36955,36957,36962,36966,36967,36972,36976,36980,36985,36997,37000,37003,37004,37006,37008,37013,37015,37016,37017,37019,37024,37025,37026,37029,37040,37042,37043,37044,37046,37053,37068,37054,37059,37060,37061,37063,37064,37077,37079,37080,37081,37084,37085,37087,37093,37074,37110,37099,37103,37104,37108,37118,37119,37120,37124,37125,37126,37128,37133,37136,37140,37142,37143,37144,37146,37148,37150,37152,37157,37154,37155,37159,37161,37166,37167,37169,37172,37174,37175,37177,37178,37180,37181,37187,37191,37192,37199,37203,37207,37209,37210,37211,37217,37220,37223,37229,37236,37241,37242,37243,37249,37251,37253,37254,37258,37262,37265,37267,37268,37269,37272,37278,37281,37286,37288,37292,37293,37294,37296,37297,37298,37299,37302,37307,37308,37309,37311,37314,37315,37317,37331,37332,37335,37337,37338,37342,37348,37349,37353,37354,37356,37357,37358,37359,37360,37361,37367,37369,37371,37373,37376,37377,37380,37381,37382,37383,37385,37386,37388,37392,37394,37395,37398,37400,37404,37405,37411,37412,37413,37414,37416,37422,37423,37424,37427,37429,37430,37432,37433,37434,37436,37438,37440,37442,37443,37446,37447,37450,37453,37454,37455,37457,37464,37465,37468,37469,37472,37473,37477,37479,37480,37481,37486,37487,37488,37493,37494,37495,37496,37497,37499,37500,37501,37503,37512,37513,37514,37517,37518,37522,37527,37529,37535,37536,37540,37541,37543,37544,37547,37551,37554,37558,37560,37562,37563,37564,37565,37567,37568,37569,37570,37571,37573,37574,37575,37576,37579,37580,37581,37582,37584,37587,37589,37591,37592,37593,37596,37597,37599,37600,37601,37603,37605,37607,37608,37612,37614,37616,37625,37627,37631,37632,37634,37640,37645,37649,37652,37653,37660,37661,37662,37663,37665,37668,37669,37671,37673,37674,37683,37684,37686,37687,37703,37704,37705,37712,37713,37714,37717,37719,37720,37722,37726,37732,37733,37735,37737,37738,37741,37743,37744,37745,37747,37748,37750,37754,37757,37759,37760,37761,37762,37768,37770,37771,37773,37775,37778,37781,37784,37787,37790,37793,37795,37796,37798,37800,37803,37812,37813,37814,37818,37801,37825,37828,37829,37830,37831,37833,37834,37835,37836,37837,37843,37849,37852,37854,37855,37858,37862,37863,37881,37879,37880,37882,37883,37885,37889,37890,37892,37896,37897,37901,37902,37903,37909,37910,37911,37919,37934,37935,37937,37938,37939,37940,37947,37951,37949,37955,37957,37960,37962,37964,37973,37977,37980,37983,37985,37987,37992,37995,37997,37998,37999,38001,38002,38020,38019,38264,38265,38270,38276,38280,38284,38285,38286,38301,38302,38303,38305,38310,38313,38315,38316,38324,38326,38330,38333,38335,38342,38344,38345,38347,38352,38353,38354,38355,38361,38362,38365,38366,38367,38368,38372,38374,38429,38430,38434,38436,38437,38438,38444,38449,38451,38455,38456,38457,38458,38460,38461,38465,38482,38484,38486,38487,38488,38497,38510,38516,38523,38524,38526,38527,38529,38530,38531,38532,38537,38545,38550,38554,38557,38559,38564,38565,38566,38569,38574,38575,38579,38586,38602,38610,23986,38616,38618,38621,38622,38623,38633,38639,38641,38650,38658,38659,38661,38665,38682,38683,38685,38689,38690,38691,38696,38705,38707,38721,38723,38730,38734,38735,38741,38743,38744,38746,38747,38755,38759,38762,38766,38771,38774,38775,38776,38779,38781,38783,38784,38793,38805,38806,38807,38809,38810,38814,38815,38818,38828,38830,38833,38834,38837,38838,38840,38841,38842,38844,38846,38847,38849,38852,38853,38855,38857,38858,38860,38861,38862,38864,38865,38868,38871,38872,38873,38877,38878,38880,38875,38881,38884,38895,38897,38900,38903,38904,38906,38919,38922,38937,38925,38926,38932,38934,38940,38942,38944,38947,38950,38955,38958,38959,38960,38962,38963,38965,38949,38974,38980,38983,38986,38993,38994,38995,38998,38999,39001,39002,39010,39011,39013,39014,39018,39020,39083,39085,39086,39088,39092,39095,39096,39098,39099,39103,39106,39109,39112,39116,39137,39139,39141,39142,39143,39146,39155,39158,39170,39175,39176,39185,39189,39190,39191,39194,39195,39196,39199,39202,39206,39207,39211,39217,39218,39219,39220,39221,39225,39226,39227,39228,39232,39233,39238,39239,39240,39245,39246,39252,39256,39257,39259,39260,39262,39263,39264,39323,39325,39327,39334,39344,39345,39346,39349,39353,39354,39357,39359,39363,39369,39379,39380,39385,39386,39388,39390,39399,39402,39403,39404,39408,39412,39413,39417,39421,39422,39426,39427,39428,39435,39436,39440,39441,39446,39454,39456,39458,39459,39460,39463,39469,39470,39475,39477,39478,39480,39495,39489,39492,39498,39499,39500,39502,39505,39508,39510,39517,39594,39596,39598,39599,39602,39604,39605,39606,39609,39611,39614,39615,39617,39619,39622,39624,39630,39632,39634,39637,39638,39639,39643,39644,39648,39652,39653,39655,39657,39660,39666,39667,39669,39673,39674,39677,39679,39680,39681,39682,39683,39684,39685,39688,39689,39691,39692,39693,39694,39696,39698,39702,39705,39707,39708,39712,39718,39723,39725,39731,39732,39733,39735,39737,39738,39741,39752,39755,39756,39765,39766,39767,39771,39774,39777,39779,39781,39782,39784,39786,39787,39788,39789,39790,39795,39797,39799,39800,39801,39807,39808,39812,39813,39814,39815,39817,39818,39819,39821,39823,39824,39828,39834,39837,39838,39846,39847,39849,39852,39856,39857,39858,39863,39864,39867,39868,39870,39871,39873,39879,39880,39886,39888,39895,39896,39901,39903,39909,39911,39914,39915,39919,39923,39927,39928,39929,39930,39933,39935,39936,39938,39947,39951,39953,39958,39960,39961,39962,39964,39966,39970,39971,39974,39975,39976,39977,39978,39985,39989,39990,39991,39997,40001,40003,40004,40005,40009,40010,40014,40015,40016,40019,40020,40022,40024,40027,40029,40030,40031,40035,40041,40042,40028,40043,40040,40046,40048,40050,40053,40055,40059,40166,40178,40183,40185,40203,40194,40209,40215,40216,40220,40221,40222,40239,40240,40242,40243,40244,40250,40252,40261,40253,40258,40259,40263,40266,40275,40276,40287,40291,40290,40293,40297,40298,40299,40304,40310,40311,40315,40316,40318,40323,40324,40326,40330,40333,40334,40338,40339,40341,40342,40343,40344,40353,40362,40364,40366,40369,40373,40377,40380,40383,40387,40391,40393,40394,40404,40405,40406,40407,40410,40414,40415,40416,40421,40423,40425,40427,40430,40432,40435,40436,40446,40458,40450,40455,40462,40464,40465,40466,40469,40470,40473,40476,40477,40570,40571,40572,40576,40578,40579,40580,40581,40583,40590,40591,40598,40600,40603,40606,40612,40616,40620,40622,40623,40624,40627,40628,40629,40646,40648,40651,40661,40671,40676,40679,40684,40685,40686,40688,40689,40690,40693,40696,40703,40706,40707,40713,40719,40720,40721,40722,40724,40726,40727,40729,40730,40731,40735,40738,40742,40746,40747,40751,40753,40754,40756,40759,40761,40762,40764,40765,40767,40769,40771,40772,40773,40774,40775,40787,40789,40790,40791,40792,40794,40797,40798,40808,40809,40813,40814,40815,40816,40817,40819,40821,40826,40829,40847,40848,40849,40850,40852,40854,40855,40862,40865,40866,40867,40869,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null], + "ibm866":[1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,9617,9618,9619,9474,9508,9569,9570,9558,9557,9571,9553,9559,9565,9564,9563,9488,9492,9524,9516,9500,9472,9532,9566,9567,9562,9556,9577,9574,9568,9552,9580,9575,9576,9572,9573,9561,9560,9554,9555,9579,9578,9496,9484,9608,9604,9612,9616,9600,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1025,1105,1028,1108,1031,1111,1038,1118,176,8729,183,8730,8470,164,9632,160], + "iso-8859-2":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,260,728,321,164,317,346,167,168,352,350,356,377,173,381,379,176,261,731,322,180,318,347,711,184,353,351,357,378,733,382,380,340,193,194,258,196,313,262,199,268,201,280,203,282,205,206,270,272,323,327,211,212,336,214,215,344,366,218,368,220,221,354,223,341,225,226,259,228,314,263,231,269,233,281,235,283,237,238,271,273,324,328,243,244,337,246,247,345,367,250,369,252,253,355,729], + "iso-8859-3":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,294,728,163,164,null,292,167,168,304,350,286,308,173,null,379,176,295,178,179,180,181,293,183,184,305,351,287,309,189,null,380,192,193,194,null,196,266,264,199,200,201,202,203,204,205,206,207,null,209,210,211,212,288,214,215,284,217,218,219,220,364,348,223,224,225,226,null,228,267,265,231,232,233,234,235,236,237,238,239,null,241,242,243,244,289,246,247,285,249,250,251,252,365,349,729], + "iso-8859-4":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,260,312,342,164,296,315,167,168,352,274,290,358,173,381,175,176,261,731,343,180,297,316,711,184,353,275,291,359,330,382,331,256,193,194,195,196,197,198,302,268,201,280,203,278,205,206,298,272,325,332,310,212,213,214,215,216,370,218,219,220,360,362,223,257,225,226,227,228,229,230,303,269,233,281,235,279,237,238,299,273,326,333,311,244,245,246,247,248,371,250,251,252,361,363,729], + "iso-8859-5":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,173,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,8470,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,167,1118,1119], + "iso-8859-6":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,null,null,null,164,null,null,null,null,null,null,null,1548,173,null,null,null,null,null,null,null,null,null,null,null,null,null,1563,null,null,null,1567,null,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,null,null,null,null,null,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,null,null,null,null,null,null,null,null,null,null,null,null,null], + "iso-8859-7":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,8216,8217,163,8364,8367,166,167,168,169,890,171,172,173,null,8213,176,177,178,179,900,901,902,183,904,905,906,187,908,189,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,null,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,null], + "iso-8859-8":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,null,162,163,164,165,166,167,168,169,215,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,247,187,188,189,190,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,8215,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,null,null,8206,8207,null], + "iso-8859-10":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,260,274,290,298,296,310,167,315,272,352,358,381,173,362,330,176,261,275,291,299,297,311,183,316,273,353,359,382,8213,363,331,256,193,194,195,196,197,198,302,268,201,280,203,278,205,206,207,208,325,332,211,212,213,214,360,216,370,218,219,220,221,222,223,257,225,226,227,228,229,230,303,269,233,281,235,279,237,238,239,240,326,333,243,244,245,246,361,248,371,250,251,252,253,254,312], + "iso-8859-13":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,8221,162,163,164,8222,166,167,216,169,342,171,172,173,174,198,176,177,178,179,8220,181,182,183,248,185,343,187,188,189,190,230,260,302,256,262,196,197,280,274,268,201,377,278,290,310,298,315,352,323,325,211,332,213,214,215,370,321,346,362,220,379,381,223,261,303,257,263,228,229,281,275,269,233,378,279,291,311,299,316,353,324,326,243,333,245,246,247,371,322,347,363,252,380,382,8217], + "iso-8859-14":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,7682,7683,163,266,267,7690,167,7808,169,7810,7691,7922,173,174,376,7710,7711,288,289,7744,7745,182,7766,7809,7767,7811,7776,7923,7812,7813,7777,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,372,209,210,211,212,213,214,7786,216,217,218,219,220,221,374,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,373,241,242,243,244,245,246,7787,248,249,250,251,252,253,375,255], + "iso-8859-15":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,8364,165,352,167,353,169,170,171,172,173,174,175,176,177,178,179,381,181,182,183,382,185,186,187,338,339,376,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255], + "iso-8859-16":[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,260,261,321,8364,8222,352,167,353,169,536,171,377,173,378,379,176,177,268,322,381,8221,182,183,382,269,537,187,338,339,376,380,192,193,194,258,196,262,198,199,200,201,202,203,204,205,206,207,272,323,210,211,212,336,214,346,368,217,218,219,220,280,538,223,224,225,226,259,228,263,230,231,232,233,234,235,236,237,238,239,273,324,242,243,244,337,246,347,369,249,250,251,252,281,539,255], + "koi8-r":[9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9600,9604,9608,9612,9616,9617,9618,9619,8992,9632,8729,8730,8776,8804,8805,160,8993,176,178,183,247,9552,9553,9554,1105,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,1025,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,169,1102,1072,1073,1094,1076,1077,1092,1075,1093,1080,1081,1082,1083,1084,1085,1086,1087,1103,1088,1089,1090,1091,1078,1074,1100,1099,1079,1096,1101,1097,1095,1098,1070,1040,1041,1062,1044,1045,1060,1043,1061,1048,1049,1050,1051,1052,1053,1054,1055,1071,1056,1057,1058,1059,1046,1042,1068,1067,1047,1064,1069,1065,1063,1066], + "koi8-u":[9472,9474,9484,9488,9492,9496,9500,9508,9516,9524,9532,9600,9604,9608,9612,9616,9617,9618,9619,8992,9632,8729,8730,8776,8804,8805,160,8993,176,178,183,247,9552,9553,9554,1105,1108,9556,1110,1111,9559,9560,9561,9562,9563,1169,1118,9566,9567,9568,9569,1025,1028,9571,1030,1031,9574,9575,9576,9577,9578,1168,1038,169,1102,1072,1073,1094,1076,1077,1092,1075,1093,1080,1081,1082,1083,1084,1085,1086,1087,1103,1088,1089,1090,1091,1078,1074,1100,1099,1079,1096,1101,1097,1095,1098,1070,1040,1041,1062,1044,1045,1060,1043,1061,1048,1049,1050,1051,1052,1053,1054,1055,1071,1056,1057,1058,1059,1046,1042,1068,1067,1047,1064,1069,1065,1063,1066], + "macintosh":[196,197,199,201,209,214,220,225,224,226,228,227,229,231,233,232,234,235,237,236,238,239,241,243,242,244,246,245,250,249,251,252,8224,176,162,163,167,8226,182,223,174,169,8482,180,168,8800,198,216,8734,177,8804,8805,165,181,8706,8721,8719,960,8747,170,186,937,230,248,191,161,172,8730,402,8776,8710,171,187,8230,160,192,195,213,338,339,8211,8212,8220,8221,8216,8217,247,9674,255,376,8260,8364,8249,8250,64257,64258,8225,183,8218,8222,8240,194,202,193,203,200,205,206,207,204,211,212,63743,210,218,219,217,305,710,732,175,728,729,730,184,733,731,711], + "windows-874":[8364,129,130,131,132,8230,134,135,136,137,138,139,140,141,142,143,144,8216,8217,8220,8221,8226,8211,8212,152,153,154,155,156,157,158,159,160,3585,3586,3587,3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603,3604,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618,3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,3630,3631,3632,3633,3634,3635,3636,3637,3638,3639,3640,3641,3642,null,null,null,null,3647,3648,3649,3650,3651,3652,3653,3654,3655,3656,3657,3658,3659,3660,3661,3662,3663,3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3674,3675,null,null,null,null], + "windows-1250":[8364,129,8218,131,8222,8230,8224,8225,136,8240,352,8249,346,356,381,377,144,8216,8217,8220,8221,8226,8211,8212,152,8482,353,8250,347,357,382,378,160,711,728,321,164,260,166,167,168,169,350,171,172,173,174,379,176,177,731,322,180,181,182,183,184,261,351,187,317,733,318,380,340,193,194,258,196,313,262,199,268,201,280,203,282,205,206,270,272,323,327,211,212,336,214,215,344,366,218,368,220,221,354,223,341,225,226,259,228,314,263,231,269,233,281,235,283,237,238,271,273,324,328,243,244,337,246,247,345,367,250,369,252,253,355,729], + "windows-1251":[1026,1027,8218,1107,8222,8230,8224,8225,8364,8240,1033,8249,1034,1036,1035,1039,1106,8216,8217,8220,8221,8226,8211,8212,152,8482,1113,8250,1114,1116,1115,1119,160,1038,1118,1032,164,1168,166,167,1025,169,1028,171,172,173,174,1031,176,177,1030,1110,1169,181,182,183,1105,8470,1108,187,1112,1029,1109,1111,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103], + "windows-1252":[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255], + "windows-1253":[8364,129,8218,402,8222,8230,8224,8225,136,8240,138,8249,140,141,142,143,144,8216,8217,8220,8221,8226,8211,8212,152,8482,154,8250,156,157,158,159,160,901,902,163,164,165,166,167,168,169,null,171,172,173,174,8213,176,177,178,179,900,181,182,183,904,905,906,187,908,189,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,null,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,null], + "windows-1254":[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,142,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,158,376,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,286,209,210,211,212,213,214,215,216,217,218,219,220,304,350,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,287,241,242,243,244,245,246,247,248,249,250,251,252,305,351,255], + "windows-1255":[8364,129,8218,402,8222,8230,8224,8225,710,8240,138,8249,140,141,142,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,154,8250,156,157,158,159,160,161,162,163,8362,165,166,167,168,169,215,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,247,187,188,189,190,191,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1520,1521,1522,1523,1524,null,null,null,null,null,null,null,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,null,null,8206,8207,null], + "windows-1256":[8364,1662,8218,402,8222,8230,8224,8225,710,8240,1657,8249,338,1670,1688,1672,1711,8216,8217,8220,8221,8226,8211,8212,1705,8482,1681,8250,339,8204,8205,1722,160,1548,162,163,164,165,166,167,168,169,1726,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,1563,187,188,189,190,1567,1729,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,215,1591,1592,1593,1594,1600,1601,1602,1603,224,1604,226,1605,1606,1607,1608,231,232,233,234,235,1609,1610,238,239,1611,1612,1613,1614,244,1615,1616,247,1617,249,1618,251,252,8206,8207,1746], + "windows-1257":[8364,129,8218,131,8222,8230,8224,8225,136,8240,138,8249,140,168,711,184,144,8216,8217,8220,8221,8226,8211,8212,152,8482,154,8250,156,175,731,159,160,null,162,163,164,null,166,167,216,169,342,171,172,173,174,198,176,177,178,179,180,181,182,183,248,185,343,187,188,189,190,230,260,302,256,262,196,197,280,274,268,201,377,278,290,310,298,315,352,323,325,211,332,213,214,215,370,321,346,362,220,379,381,223,261,303,257,263,228,229,281,275,269,233,378,279,291,311,299,316,353,324,326,243,333,245,246,247,371,322,347,363,252,380,382,729], + "windows-1258":[8364,129,8218,402,8222,8230,8224,8225,710,8240,138,8249,338,141,142,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,154,8250,339,157,158,376,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,258,196,197,198,199,200,201,202,203,768,205,206,207,272,209,777,211,212,416,214,215,216,217,218,219,220,431,771,223,224,225,226,259,228,229,230,231,232,233,234,235,769,237,238,239,273,241,803,243,244,417,246,247,248,249,250,251,252,432,8363,255], + "x-mac-cyrillic":[1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,8224,176,1168,163,167,8226,182,1030,174,169,8482,1026,1106,8800,1027,1107,8734,177,8804,8805,1110,181,1169,1032,1028,1108,1031,1111,1033,1113,1034,1114,1112,1029,172,8730,402,8776,8710,171,187,8230,160,1035,1115,1036,1116,1109,8211,8212,8220,8221,8216,8217,247,8222,1038,1118,1039,1119,8470,1025,1105,1103,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,8364] +}; + +// For strict environments where `this` inside the global scope +// is `undefined`, take a pure object instead +}(this || {})); \ No newline at end of file diff --git a/nodejs/node_modules/bson/vendor/text-encoding/lib/encoding.js b/nodejs/node_modules/bson/vendor/text-encoding/lib/encoding.js new file mode 100644 index 00000000..f01991a8 --- /dev/null +++ b/nodejs/node_modules/bson/vendor/text-encoding/lib/encoding.js @@ -0,0 +1,3301 @@ +// This is free and unencumbered software released into the public domain. +// See LICENSE.md for more information. + +/** + * @fileoverview Global |this| required for resolving indexes in node. + * @suppress {globalThis} + */ +(function(global) { + 'use strict'; + + // + // Utilities + // + + /** + * @param {number} a The number to test. + * @param {number} min The minimum value in the range, inclusive. + * @param {number} max The maximum value in the range, inclusive. + * @return {boolean} True if a >= min and a <= max. + */ + function inRange(a, min, max) { + return min <= a && a <= max; + } + + /** + * @param {!Array.<*>} array The array to check. + * @param {*} item The item to look for in the array. + * @return {boolean} True if the item appears in the array. + */ + function includes(array, item) { + return array.indexOf(item) !== -1; + } + + var floor = Math.floor; + + /** + * @param {*} o + * @return {Object} + */ + function ToDictionary(o) { + if (o === undefined) return {}; + if (o === Object(o)) return o; + throw TypeError('Could not convert argument to dictionary'); + } + + /** + * @param {string} string Input string of UTF-16 code units. + * @return {!Array.} Code points. + */ + function stringToCodePoints(string) { + // https://heycam.github.io/webidl/#dfn-obtain-unicode + + // 1. Let S be the DOMString value. + var s = String(string); + + // 2. Let n be the length of S. + var n = s.length; + + // 3. Initialize i to 0. + var i = 0; + + // 4. Initialize U to be an empty sequence of Unicode characters. + var u = []; + + // 5. While i < n: + while (i < n) { + + // 1. Let c be the code unit in S at index i. + var c = s.charCodeAt(i); + + // 2. Depending on the value of c: + + // c < 0xD800 or c > 0xDFFF + if (c < 0xD800 || c > 0xDFFF) { + // Append to U the Unicode character with code point c. + u.push(c); + } + + // 0xDC00 ≤ c ≤ 0xDFFF + else if (0xDC00 <= c && c <= 0xDFFF) { + // Append to U a U+FFFD REPLACEMENT CHARACTER. + u.push(0xFFFD); + } + + // 0xD800 ≤ c ≤ 0xDBFF + else if (0xD800 <= c && c <= 0xDBFF) { + // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT + // CHARACTER. + if (i === n - 1) { + u.push(0xFFFD); + } + // 2. Otherwise, i < n−1: + else { + // 1. Let d be the code unit in S at index i+1. + var d = s.charCodeAt(i + 1); + + // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then: + if (0xDC00 <= d && d <= 0xDFFF) { + // 1. Let a be c & 0x3FF. + var a = c & 0x3FF; + + // 2. Let b be d & 0x3FF. + var b = d & 0x3FF; + + // 3. Append to U the Unicode character with code point + // 2^16+2^10*a+b. + u.push(0x10000 + (a << 10) + b); + + // 4. Set i to i+1. + i += 1; + } + + // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a + // U+FFFD REPLACEMENT CHARACTER. + else { + u.push(0xFFFD); + } + } + } + + // 3. Set i to i+1. + i += 1; + } + + // 6. Return U. + return u; + } + + /** + * @param {!Array.} code_points Array of code points. + * @return {string} string String of UTF-16 code units. + */ + function codePointsToString(code_points) { + var s = ''; + for (var i = 0; i < code_points.length; ++i) { + var cp = code_points[i]; + if (cp <= 0xFFFF) { + s += String.fromCharCode(cp); + } else { + cp -= 0x10000; + s += String.fromCharCode((cp >> 10) + 0xD800, + (cp & 0x3FF) + 0xDC00); + } + } + return s; + } + + + // + // Implementation of Encoding specification + // https://encoding.spec.whatwg.org/ + // + + // + // 4. Terminology + // + + /** + * An ASCII byte is a byte in the range 0x00 to 0x7F, inclusive. + * @param {number} a The number to test. + * @return {boolean} True if a is in the range 0x00 to 0x7F, inclusive. + */ + function isASCIIByte(a) { + return 0x00 <= a && a <= 0x7F; + } + + /** + * An ASCII code point is a code point in the range U+0000 to + * U+007F, inclusive. + */ + var isASCIICodePoint = isASCIIByte; + + + /** + * End-of-stream is a special token that signifies no more tokens + * are in the stream. + * @const + */ var end_of_stream = -1; + + /** + * A stream represents an ordered sequence of tokens. + * + * @constructor + * @param {!(Array.|Uint8Array)} tokens Array of tokens that provide + * the stream. + */ + function Stream(tokens) { + /** @type {!Array.} */ + this.tokens = [].slice.call(tokens); + // Reversed as push/pop is more efficient than shift/unshift. + this.tokens.reverse(); + } + + Stream.prototype = { + /** + * @return {boolean} True if end-of-stream has been hit. + */ + endOfStream: function() { + return !this.tokens.length; + }, + + /** + * When a token is read from a stream, the first token in the + * stream must be returned and subsequently removed, and + * end-of-stream must be returned otherwise. + * + * @return {number} Get the next token from the stream, or + * end_of_stream. + */ + read: function() { + if (!this.tokens.length) + return end_of_stream; + return this.tokens.pop(); + }, + + /** + * When one or more tokens are prepended to a stream, those tokens + * must be inserted, in given order, before the first token in the + * stream. + * + * @param {(number|!Array.)} token The token(s) to prepend to the + * stream. + */ + prepend: function(token) { + if (Array.isArray(token)) { + var tokens = /**@type {!Array.}*/(token); + while (tokens.length) + this.tokens.push(tokens.pop()); + } else { + this.tokens.push(token); + } + }, + + /** + * When one or more tokens are pushed to a stream, those tokens + * must be inserted, in given order, after the last token in the + * stream. + * + * @param {(number|!Array.)} token The tokens(s) to push to the + * stream. + */ + push: function(token) { + if (Array.isArray(token)) { + var tokens = /**@type {!Array.}*/(token); + while (tokens.length) + this.tokens.unshift(tokens.shift()); + } else { + this.tokens.unshift(token); + } + } + }; + + // + // 5. Encodings + // + + // 5.1 Encoders and decoders + + /** @const */ + var finished = -1; + + /** + * @param {boolean} fatal If true, decoding errors raise an exception. + * @param {number=} opt_code_point Override the standard fallback code point. + * @return {number} The code point to insert on a decoding error. + */ + function decoderError(fatal, opt_code_point) { + if (fatal) + throw TypeError('Decoder error'); + return opt_code_point || 0xFFFD; + } + + /** + * @param {number} code_point The code point that could not be encoded. + * @return {number} Always throws, no value is actually returned. + */ + function encoderError(code_point) { + throw TypeError('The code point ' + code_point + ' could not be encoded.'); + } + + /** @interface */ + function Decoder() {} + Decoder.prototype = { + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point, or |finished|. + */ + handler: function(stream, bite) {} + }; + + /** @interface */ + function Encoder() {} + Encoder.prototype = { + /** + * @param {Stream} stream The stream of code points being encoded. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit, or |finished|. + */ + handler: function(stream, code_point) {} + }; + + // 5.2 Names and labels + + // TODO: Define @typedef for Encoding: {name:string,labels:Array.} + // https://github.com/google/closure-compiler/issues/247 + + /** + * @param {string} label The encoding label. + * @return {?{name:string,labels:Array.}} + */ + function getEncoding(label) { + // 1. Remove any leading and trailing ASCII whitespace from label. + label = String(label).trim().toLowerCase(); + + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, return the corresponding + // encoding, and failure otherwise. + if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) { + return label_to_encoding[label]; + } + return null; + } + + /** + * Encodings table: https://encoding.spec.whatwg.org/encodings.json + * @const + * @type {!Array.<{ + * heading: string, + * encodings: Array.<{name:string,labels:Array.}> + * }>} + */ + var encodings = [ + { + "encodings": [ + { + "labels": [ + "unicode-1-1-utf-8", + "utf-8", + "utf8" + ], + "name": "UTF-8" + } + ], + "heading": "The Encoding" + }, + { + "encodings": [ + { + "labels": [ + "866", + "cp866", + "csibm866", + "ibm866" + ], + "name": "IBM866" + }, + { + "labels": [ + "csisolatin2", + "iso-8859-2", + "iso-ir-101", + "iso8859-2", + "iso88592", + "iso_8859-2", + "iso_8859-2:1987", + "l2", + "latin2" + ], + "name": "ISO-8859-2" + }, + { + "labels": [ + "csisolatin3", + "iso-8859-3", + "iso-ir-109", + "iso8859-3", + "iso88593", + "iso_8859-3", + "iso_8859-3:1988", + "l3", + "latin3" + ], + "name": "ISO-8859-3" + }, + { + "labels": [ + "csisolatin4", + "iso-8859-4", + "iso-ir-110", + "iso8859-4", + "iso88594", + "iso_8859-4", + "iso_8859-4:1988", + "l4", + "latin4" + ], + "name": "ISO-8859-4" + }, + { + "labels": [ + "csisolatincyrillic", + "cyrillic", + "iso-8859-5", + "iso-ir-144", + "iso8859-5", + "iso88595", + "iso_8859-5", + "iso_8859-5:1988" + ], + "name": "ISO-8859-5" + }, + { + "labels": [ + "arabic", + "asmo-708", + "csiso88596e", + "csiso88596i", + "csisolatinarabic", + "ecma-114", + "iso-8859-6", + "iso-8859-6-e", + "iso-8859-6-i", + "iso-ir-127", + "iso8859-6", + "iso88596", + "iso_8859-6", + "iso_8859-6:1987" + ], + "name": "ISO-8859-6" + }, + { + "labels": [ + "csisolatingreek", + "ecma-118", + "elot_928", + "greek", + "greek8", + "iso-8859-7", + "iso-ir-126", + "iso8859-7", + "iso88597", + "iso_8859-7", + "iso_8859-7:1987", + "sun_eu_greek" + ], + "name": "ISO-8859-7" + }, + { + "labels": [ + "csiso88598e", + "csisolatinhebrew", + "hebrew", + "iso-8859-8", + "iso-8859-8-e", + "iso-ir-138", + "iso8859-8", + "iso88598", + "iso_8859-8", + "iso_8859-8:1988", + "visual" + ], + "name": "ISO-8859-8" + }, + { + "labels": [ + "csiso88598i", + "iso-8859-8-i", + "logical" + ], + "name": "ISO-8859-8-I" + }, + { + "labels": [ + "csisolatin6", + "iso-8859-10", + "iso-ir-157", + "iso8859-10", + "iso885910", + "l6", + "latin6" + ], + "name": "ISO-8859-10" + }, + { + "labels": [ + "iso-8859-13", + "iso8859-13", + "iso885913" + ], + "name": "ISO-8859-13" + }, + { + "labels": [ + "iso-8859-14", + "iso8859-14", + "iso885914" + ], + "name": "ISO-8859-14" + }, + { + "labels": [ + "csisolatin9", + "iso-8859-15", + "iso8859-15", + "iso885915", + "iso_8859-15", + "l9" + ], + "name": "ISO-8859-15" + }, + { + "labels": [ + "iso-8859-16" + ], + "name": "ISO-8859-16" + }, + { + "labels": [ + "cskoi8r", + "koi", + "koi8", + "koi8-r", + "koi8_r" + ], + "name": "KOI8-R" + }, + { + "labels": [ + "koi8-ru", + "koi8-u" + ], + "name": "KOI8-U" + }, + { + "labels": [ + "csmacintosh", + "mac", + "macintosh", + "x-mac-roman" + ], + "name": "macintosh" + }, + { + "labels": [ + "dos-874", + "iso-8859-11", + "iso8859-11", + "iso885911", + "tis-620", + "windows-874" + ], + "name": "windows-874" + }, + { + "labels": [ + "cp1250", + "windows-1250", + "x-cp1250" + ], + "name": "windows-1250" + }, + { + "labels": [ + "cp1251", + "windows-1251", + "x-cp1251" + ], + "name": "windows-1251" + }, + { + "labels": [ + "ansi_x3.4-1968", + "ascii", + "cp1252", + "cp819", + "csisolatin1", + "ibm819", + "iso-8859-1", + "iso-ir-100", + "iso8859-1", + "iso88591", + "iso_8859-1", + "iso_8859-1:1987", + "l1", + "latin1", + "us-ascii", + "windows-1252", + "x-cp1252" + ], + "name": "windows-1252" + }, + { + "labels": [ + "cp1253", + "windows-1253", + "x-cp1253" + ], + "name": "windows-1253" + }, + { + "labels": [ + "cp1254", + "csisolatin5", + "iso-8859-9", + "iso-ir-148", + "iso8859-9", + "iso88599", + "iso_8859-9", + "iso_8859-9:1989", + "l5", + "latin5", + "windows-1254", + "x-cp1254" + ], + "name": "windows-1254" + }, + { + "labels": [ + "cp1255", + "windows-1255", + "x-cp1255" + ], + "name": "windows-1255" + }, + { + "labels": [ + "cp1256", + "windows-1256", + "x-cp1256" + ], + "name": "windows-1256" + }, + { + "labels": [ + "cp1257", + "windows-1257", + "x-cp1257" + ], + "name": "windows-1257" + }, + { + "labels": [ + "cp1258", + "windows-1258", + "x-cp1258" + ], + "name": "windows-1258" + }, + { + "labels": [ + "x-mac-cyrillic", + "x-mac-ukrainian" + ], + "name": "x-mac-cyrillic" + } + ], + "heading": "Legacy single-byte encodings" + }, + { + "encodings": [ + { + "labels": [ + "chinese", + "csgb2312", + "csiso58gb231280", + "gb2312", + "gb_2312", + "gb_2312-80", + "gbk", + "iso-ir-58", + "x-gbk" + ], + "name": "GBK" + }, + { + "labels": [ + "gb18030" + ], + "name": "gb18030" + } + ], + "heading": "Legacy multi-byte Chinese (simplified) encodings" + }, + { + "encodings": [ + { + "labels": [ + "big5", + "big5-hkscs", + "cn-big5", + "csbig5", + "x-x-big5" + ], + "name": "Big5" + } + ], + "heading": "Legacy multi-byte Chinese (traditional) encodings" + }, + { + "encodings": [ + { + "labels": [ + "cseucpkdfmtjapanese", + "euc-jp", + "x-euc-jp" + ], + "name": "EUC-JP" + }, + { + "labels": [ + "csiso2022jp", + "iso-2022-jp" + ], + "name": "ISO-2022-JP" + }, + { + "labels": [ + "csshiftjis", + "ms932", + "ms_kanji", + "shift-jis", + "shift_jis", + "sjis", + "windows-31j", + "x-sjis" + ], + "name": "Shift_JIS" + } + ], + "heading": "Legacy multi-byte Japanese encodings" + }, + { + "encodings": [ + { + "labels": [ + "cseuckr", + "csksc56011987", + "euc-kr", + "iso-ir-149", + "korean", + "ks_c_5601-1987", + "ks_c_5601-1989", + "ksc5601", + "ksc_5601", + "windows-949" + ], + "name": "EUC-KR" + } + ], + "heading": "Legacy multi-byte Korean encodings" + }, + { + "encodings": [ + { + "labels": [ + "csiso2022kr", + "hz-gb-2312", + "iso-2022-cn", + "iso-2022-cn-ext", + "iso-2022-kr" + ], + "name": "replacement" + }, + { + "labels": [ + "utf-16be" + ], + "name": "UTF-16BE" + }, + { + "labels": [ + "utf-16", + "utf-16le" + ], + "name": "UTF-16LE" + }, + { + "labels": [ + "x-user-defined" + ], + "name": "x-user-defined" + } + ], + "heading": "Legacy miscellaneous encodings" + } + ]; + + // Label to encoding registry. + /** @type {Object.}>} */ + var label_to_encoding = {}; + encodings.forEach(function(category) { + category.encodings.forEach(function(encoding) { + encoding.labels.forEach(function(label) { + label_to_encoding[label] = encoding; + }); + }); + }); + + // Registry of of encoder/decoder factories, by encoding name. + /** @type {Object.} */ + var encoders = {}; + /** @type {Object.} */ + var decoders = {}; + + // + // 6. Indexes + // + + /** + * @param {number} pointer The |pointer| to search for. + * @param {(!Array.|undefined)} index The |index| to search within. + * @return {?number} The code point corresponding to |pointer| in |index|, + * or null if |code point| is not in |index|. + */ + function indexCodePointFor(pointer, index) { + if (!index) return null; + return index[pointer] || null; + } + + /** + * @param {number} code_point The |code point| to search for. + * @param {!Array.} index The |index| to search within. + * @return {?number} The first pointer corresponding to |code point| in + * |index|, or null if |code point| is not in |index|. + */ + function indexPointerFor(code_point, index) { + var pointer = index.indexOf(code_point); + return pointer === -1 ? null : pointer; + } + + /** + * @param {string} name Name of the index. + * @return {(!Array.|!Array.>)} + * */ + function index(name) { + if (!('encoding-indexes' in global)) { + throw Error("Indexes missing." + + " Did you forget to include encoding-indexes.js first?"); + } + return global['encoding-indexes'][name]; + } + + /** + * @param {number} pointer The |pointer| to search for in the gb18030 index. + * @return {?number} The code point corresponding to |pointer| in |index|, + * or null if |code point| is not in the gb18030 index. + */ + function indexGB18030RangesCodePointFor(pointer) { + // 1. If pointer is greater than 39419 and less than 189000, or + // pointer is greater than 1237575, return null. + if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575)) + return null; + + // 2. If pointer is 7457, return code point U+E7C7. + if (pointer === 7457) return 0xE7C7; + + // 3. Let offset be the last pointer in index gb18030 ranges that + // is equal to or less than pointer and let code point offset be + // its corresponding code point. + var offset = 0; + var code_point_offset = 0; + var idx = index('gb18030-ranges'); + var i; + for (i = 0; i < idx.length; ++i) { + /** @type {!Array.} */ + var entry = idx[i]; + if (entry[0] <= pointer) { + offset = entry[0]; + code_point_offset = entry[1]; + } else { + break; + } + } + + // 4. Return a code point whose value is code point offset + + // pointer − offset. + return code_point_offset + pointer - offset; + } + + /** + * @param {number} code_point The |code point| to locate in the gb18030 index. + * @return {number} The first pointer corresponding to |code point| in the + * gb18030 index. + */ + function indexGB18030RangesPointerFor(code_point) { + // 1. If code point is U+E7C7, return pointer 7457. + if (code_point === 0xE7C7) return 7457; + + // 2. Let offset be the last code point in index gb18030 ranges + // that is equal to or less than code point and let pointer offset + // be its corresponding pointer. + var offset = 0; + var pointer_offset = 0; + var idx = index('gb18030-ranges'); + var i; + for (i = 0; i < idx.length; ++i) { + /** @type {!Array.} */ + var entry = idx[i]; + if (entry[1] <= code_point) { + offset = entry[1]; + pointer_offset = entry[0]; + } else { + break; + } + } + + // 3. Return a pointer whose value is pointer offset + code point + // − offset. + return pointer_offset + code_point - offset; + } + + /** + * @param {number} code_point The |code_point| to search for in the Shift_JIS + * index. + * @return {?number} The code point corresponding to |pointer| in |index|, + * or null if |code point| is not in the Shift_JIS index. + */ + function indexShiftJISPointerFor(code_point) { + // 1. Let index be index jis0208 excluding all entries whose + // pointer is in the range 8272 to 8835, inclusive. + shift_jis_index = shift_jis_index || + index('jis0208').map(function(code_point, pointer) { + return inRange(pointer, 8272, 8835) ? null : code_point; + }); + var index_ = shift_jis_index; + + // 2. Return the index pointer for code point in index. + return index_.indexOf(code_point); + } + var shift_jis_index; + + /** + * @param {number} code_point The |code_point| to search for in the big5 + * index. + * @return {?number} The code point corresponding to |pointer| in |index|, + * or null if |code point| is not in the big5 index. + */ + function indexBig5PointerFor(code_point) { + // 1. Let index be index Big5 excluding all entries whose pointer + big5_index_no_hkscs = big5_index_no_hkscs || + index('big5').map(function(code_point, pointer) { + return (pointer < (0xA1 - 0x81) * 157) ? null : code_point; + }); + var index_ = big5_index_no_hkscs; + + // 2. If code point is U+2550, U+255E, U+2561, U+256A, U+5341, or + // U+5345, return the last pointer corresponding to code point in + // index. + if (code_point === 0x2550 || code_point === 0x255E || + code_point === 0x2561 || code_point === 0x256A || + code_point === 0x5341 || code_point === 0x5345) { + return index_.lastIndexOf(code_point); + } + + // 3. Return the index pointer for code point in index. + return indexPointerFor(code_point, index_); + } + var big5_index_no_hkscs; + + // + // 8. API + // + + /** @const */ var DEFAULT_ENCODING = 'utf-8'; + + // 8.1 Interface TextDecoder + + /** + * @constructor + * @param {string=} label The label of the encoding; + * defaults to 'utf-8'. + * @param {Object=} options + */ + function TextDecoder(label, options) { + // Web IDL conventions + if (!(this instanceof TextDecoder)) + throw TypeError('Called as a function. Did you forget \'new\'?'); + label = label !== undefined ? String(label) : DEFAULT_ENCODING; + options = ToDictionary(options); + + // A TextDecoder object has an associated encoding, decoder, + // stream, ignore BOM flag (initially unset), BOM seen flag + // (initially unset), error mode (initially replacement), and do + // not flush flag (initially unset). + + /** @private */ + this._encoding = null; + /** @private @type {?Decoder} */ + this._decoder = null; + /** @private @type {boolean} */ + this._ignoreBOM = false; + /** @private @type {boolean} */ + this._BOMseen = false; + /** @private @type {string} */ + this._error_mode = 'replacement'; + /** @private @type {boolean} */ + this._do_not_flush = false; + + + // 1. Let encoding be the result of getting an encoding from + // label. + var encoding = getEncoding(label); + + // 2. If encoding is failure or replacement, throw a RangeError. + if (encoding === null || encoding.name === 'replacement') + throw RangeError('Unknown encoding: ' + label); + if (!decoders[encoding.name]) { + throw Error('Decoder not present.' + + ' Did you forget to include encoding-indexes.js first?'); + } + + // 3. Let dec be a new TextDecoder object. + var dec = this; + + // 4. Set dec's encoding to encoding. + dec._encoding = encoding; + + // 5. If options's fatal member is true, set dec's error mode to + // fatal. + if (Boolean(options['fatal'])) + dec._error_mode = 'fatal'; + + // 6. If options's ignoreBOM member is true, set dec's ignore BOM + // flag. + if (Boolean(options['ignoreBOM'])) + dec._ignoreBOM = true; + + // For pre-ES5 runtimes: + if (!Object.defineProperty) { + this.encoding = dec._encoding.name.toLowerCase(); + this.fatal = dec._error_mode === 'fatal'; + this.ignoreBOM = dec._ignoreBOM; + } + + // 7. Return dec. + return dec; + } + + if (Object.defineProperty) { + // The encoding attribute's getter must return encoding's name. + Object.defineProperty(TextDecoder.prototype, 'encoding', { + /** @this {TextDecoder} */ + get: function() { return this._encoding.name.toLowerCase(); } + }); + + // The fatal attribute's getter must return true if error mode + // is fatal, and false otherwise. + Object.defineProperty(TextDecoder.prototype, 'fatal', { + /** @this {TextDecoder} */ + get: function() { return this._error_mode === 'fatal'; } + }); + + // The ignoreBOM attribute's getter must return true if ignore + // BOM flag is set, and false otherwise. + Object.defineProperty(TextDecoder.prototype, 'ignoreBOM', { + /** @this {TextDecoder} */ + get: function() { return this._ignoreBOM; } + }); + } + + /** + * @param {BufferSource=} input The buffer of bytes to decode. + * @param {Object=} options + * @return {string} The decoded string. + */ + TextDecoder.prototype.decode = function decode(input, options) { + var bytes; + if (typeof input === 'object' && input instanceof ArrayBuffer) { + bytes = new Uint8Array(input); + } else if (typeof input === 'object' && 'buffer' in input && + input.buffer instanceof ArrayBuffer) { + bytes = new Uint8Array(input.buffer, + input.byteOffset, + input.byteLength); + } else { + bytes = new Uint8Array(0); + } + + options = ToDictionary(options); + + // 1. If the do not flush flag is unset, set decoder to a new + // encoding's decoder, set stream to a new stream, and unset the + // BOM seen flag. + if (!this._do_not_flush) { + this._decoder = decoders[this._encoding.name]({ + fatal: this._error_mode === 'fatal'}); + this._BOMseen = false; + } + + // 2. If options's stream is true, set the do not flush flag, and + // unset the do not flush flag otherwise. + this._do_not_flush = Boolean(options['stream']); + + // 3. If input is given, push a copy of input to stream. + // TODO: Align with spec algorithm - maintain stream on instance. + var input_stream = new Stream(bytes); + + // 4. Let output be a new stream. + var output = []; + + /** @type {?(number|!Array.)} */ + var result; + + // 5. While true: + while (true) { + // 1. Let token be the result of reading from stream. + var token = input_stream.read(); + + // 2. If token is end-of-stream and the do not flush flag is + // set, return output, serialized. + // TODO: Align with spec algorithm. + if (token === end_of_stream) + break; + + // 3. Otherwise, run these subsubsteps: + + // 1. Let result be the result of processing token for decoder, + // stream, output, and error mode. + result = this._decoder.handler(input_stream, token); + + // 2. If result is finished, return output, serialized. + if (result === finished) + break; + + if (result !== null) { + if (Array.isArray(result)) + output.push.apply(output, /**@type {!Array.}*/(result)); + else + output.push(result); + } + + // 3. Otherwise, if result is error, throw a TypeError. + // (Thrown in handler) + + // 4. Otherwise, do nothing. + } + // TODO: Align with spec algorithm. + if (!this._do_not_flush) { + do { + result = this._decoder.handler(input_stream, input_stream.read()); + if (result === finished) + break; + if (result === null) + continue; + if (Array.isArray(result)) + output.push.apply(output, /**@type {!Array.}*/(result)); + else + output.push(result); + } while (!input_stream.endOfStream()); + this._decoder = null; + } + + // A TextDecoder object also has an associated serialize stream + // algorithm... + /** + * @param {!Array.} stream + * @return {string} + * @this {TextDecoder} + */ + function serializeStream(stream) { + // 1. Let token be the result of reading from stream. + // (Done in-place on array, rather than as a stream) + + // 2. If encoding is UTF-8, UTF-16BE, or UTF-16LE, and ignore + // BOM flag and BOM seen flag are unset, run these subsubsteps: + if (includes(['UTF-8', 'UTF-16LE', 'UTF-16BE'], this._encoding.name) && + !this._ignoreBOM && !this._BOMseen) { + if (stream.length > 0 && stream[0] === 0xFEFF) { + // 1. If token is U+FEFF, set BOM seen flag. + this._BOMseen = true; + stream.shift(); + } else if (stream.length > 0) { + // 2. Otherwise, if token is not end-of-stream, set BOM seen + // flag and append token to stream. + this._BOMseen = true; + } else { + // 3. Otherwise, if token is not end-of-stream, append token + // to output. + // (no-op) + } + } + // 4. Otherwise, return output. + return codePointsToString(stream); + } + + return serializeStream.call(this, output); + }; + + // 8.2 Interface TextEncoder + + /** + * @constructor + * @param {string=} label The label of the encoding. NONSTANDARD. + * @param {Object=} options NONSTANDARD. + */ + function TextEncoder(label, options) { + // Web IDL conventions + if (!(this instanceof TextEncoder)) + throw TypeError('Called as a function. Did you forget \'new\'?'); + options = ToDictionary(options); + + // A TextEncoder object has an associated encoding and encoder. + + /** @private */ + this._encoding = null; + /** @private @type {?Encoder} */ + this._encoder = null; + + // Non-standard + /** @private @type {boolean} */ + this._do_not_flush = false; + /** @private @type {string} */ + this._fatal = Boolean(options['fatal']) ? 'fatal' : 'replacement'; + + // 1. Let enc be a new TextEncoder object. + var enc = this; + + // 2. Set enc's encoding to UTF-8's encoder. + if (Boolean(options['NONSTANDARD_allowLegacyEncoding'])) { + // NONSTANDARD behavior. + label = label !== undefined ? String(label) : DEFAULT_ENCODING; + var encoding = getEncoding(label); + if (encoding === null || encoding.name === 'replacement') + throw RangeError('Unknown encoding: ' + label); + if (!encoders[encoding.name]) { + throw Error('Encoder not present.' + + ' Did you forget to include encoding-indexes.js first?'); + } + enc._encoding = encoding; + } else { + // Standard behavior. + enc._encoding = getEncoding('utf-8'); + + if (label !== undefined && 'console' in global) { + console.warn('TextEncoder constructor called with encoding label, ' + + 'which is ignored.'); + } + } + + // For pre-ES5 runtimes: + if (!Object.defineProperty) + this.encoding = enc._encoding.name.toLowerCase(); + + // 3. Return enc. + return enc; + } + + if (Object.defineProperty) { + // The encoding attribute's getter must return encoding's name. + Object.defineProperty(TextEncoder.prototype, 'encoding', { + /** @this {TextEncoder} */ + get: function() { return this._encoding.name.toLowerCase(); } + }); + } + + /** + * @param {string=} opt_string The string to encode. + * @param {Object=} options + * @return {!Uint8Array} Encoded bytes, as a Uint8Array. + */ + TextEncoder.prototype.encode = function encode(opt_string, options) { + opt_string = opt_string === undefined ? '' : String(opt_string); + options = ToDictionary(options); + + // NOTE: This option is nonstandard. None of the encodings + // permitted for encoding (i.e. UTF-8, UTF-16) are stateful when + // the input is a USVString so streaming is not necessary. + if (!this._do_not_flush) + this._encoder = encoders[this._encoding.name]({ + fatal: this._fatal === 'fatal'}); + this._do_not_flush = Boolean(options['stream']); + + // 1. Convert input to a stream. + var input = new Stream(stringToCodePoints(opt_string)); + + // 2. Let output be a new stream + var output = []; + + /** @type {?(number|!Array.)} */ + var result; + // 3. While true, run these substeps: + while (true) { + // 1. Let token be the result of reading from input. + var token = input.read(); + if (token === end_of_stream) + break; + // 2. Let result be the result of processing token for encoder, + // input, output. + result = this._encoder.handler(input, token); + if (result === finished) + break; + if (Array.isArray(result)) + output.push.apply(output, /**@type {!Array.}*/(result)); + else + output.push(result); + } + // TODO: Align with spec algorithm. + if (!this._do_not_flush) { + while (true) { + result = this._encoder.handler(input, input.read()); + if (result === finished) + break; + if (Array.isArray(result)) + output.push.apply(output, /**@type {!Array.}*/(result)); + else + output.push(result); + } + this._encoder = null; + } + // 3. If result is finished, convert output into a byte sequence, + // and then return a Uint8Array object wrapping an ArrayBuffer + // containing output. + return new Uint8Array(output); + }; + + + // + // 9. The encoding + // + + // 9.1 utf-8 + + // 9.1.1 utf-8 decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function UTF8Decoder(options) { + var fatal = options.fatal; + + // utf-8's decoder's has an associated utf-8 code point, utf-8 + // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8 + // lower boundary (initially 0x80), and a utf-8 upper boundary + // (initially 0xBF). + var /** @type {number} */ utf8_code_point = 0, + /** @type {number} */ utf8_bytes_seen = 0, + /** @type {number} */ utf8_bytes_needed = 0, + /** @type {number} */ utf8_lower_boundary = 0x80, + /** @type {number} */ utf8_upper_boundary = 0xBF; + + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and utf-8 bytes needed is not 0, + // set utf-8 bytes needed to 0 and return error. + if (bite === end_of_stream && utf8_bytes_needed !== 0) { + utf8_bytes_needed = 0; + return decoderError(fatal); + } + + // 2. If byte is end-of-stream, return finished. + if (bite === end_of_stream) + return finished; + + // 3. If utf-8 bytes needed is 0, based on byte: + if (utf8_bytes_needed === 0) { + + // 0x00 to 0x7F + if (inRange(bite, 0x00, 0x7F)) { + // Return a code point whose value is byte. + return bite; + } + + // 0xC2 to 0xDF + else if (inRange(bite, 0xC2, 0xDF)) { + // 1. Set utf-8 bytes needed to 1. + utf8_bytes_needed = 1; + + // 2. Set UTF-8 code point to byte & 0x1F. + utf8_code_point = bite & 0x1F; + } + + // 0xE0 to 0xEF + else if (inRange(bite, 0xE0, 0xEF)) { + // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0. + if (bite === 0xE0) + utf8_lower_boundary = 0xA0; + // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F. + if (bite === 0xED) + utf8_upper_boundary = 0x9F; + // 3. Set utf-8 bytes needed to 2. + utf8_bytes_needed = 2; + // 4. Set UTF-8 code point to byte & 0xF. + utf8_code_point = bite & 0xF; + } + + // 0xF0 to 0xF4 + else if (inRange(bite, 0xF0, 0xF4)) { + // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90. + if (bite === 0xF0) + utf8_lower_boundary = 0x90; + // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F. + if (bite === 0xF4) + utf8_upper_boundary = 0x8F; + // 3. Set utf-8 bytes needed to 3. + utf8_bytes_needed = 3; + // 4. Set UTF-8 code point to byte & 0x7. + utf8_code_point = bite & 0x7; + } + + // Otherwise + else { + // Return error. + return decoderError(fatal); + } + + // Return continue. + return null; + } + + // 4. If byte is not in the range utf-8 lower boundary to utf-8 + // upper boundary, inclusive, run these substeps: + if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) { + + // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8 + // bytes seen to 0, set utf-8 lower boundary to 0x80, and set + // utf-8 upper boundary to 0xBF. + utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0; + utf8_lower_boundary = 0x80; + utf8_upper_boundary = 0xBF; + + // 2. Prepend byte to stream. + stream.prepend(bite); + + // 3. Return error. + return decoderError(fatal); + } + + // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary + // to 0xBF. + utf8_lower_boundary = 0x80; + utf8_upper_boundary = 0xBF; + + // 6. Set UTF-8 code point to (UTF-8 code point << 6) | (byte & + // 0x3F) + utf8_code_point = (utf8_code_point << 6) | (bite & 0x3F); + + // 7. Increase utf-8 bytes seen by one. + utf8_bytes_seen += 1; + + // 8. If utf-8 bytes seen is not equal to utf-8 bytes needed, + // continue. + if (utf8_bytes_seen !== utf8_bytes_needed) + return null; + + // 9. Let code point be utf-8 code point. + var code_point = utf8_code_point; + + // 10. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes + // seen to 0. + utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0; + + // 11. Return a code point whose value is code point. + return code_point; + }; + } + + // 9.1.2 utf-8 encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function UTF8Encoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. Set count and offset based on the range code point is in: + var count, offset; + // U+0080 to U+07FF, inclusive: + if (inRange(code_point, 0x0080, 0x07FF)) { + // 1 and 0xC0 + count = 1; + offset = 0xC0; + } + // U+0800 to U+FFFF, inclusive: + else if (inRange(code_point, 0x0800, 0xFFFF)) { + // 2 and 0xE0 + count = 2; + offset = 0xE0; + } + // U+10000 to U+10FFFF, inclusive: + else if (inRange(code_point, 0x10000, 0x10FFFF)) { + // 3 and 0xF0 + count = 3; + offset = 0xF0; + } + + // 4. Let bytes be a byte sequence whose first byte is (code + // point >> (6 × count)) + offset. + var bytes = [(code_point >> (6 * count)) + offset]; + + // 5. Run these substeps while count is greater than 0: + while (count > 0) { + + // 1. Set temp to code point >> (6 × (count − 1)). + var temp = code_point >> (6 * (count - 1)); + + // 2. Append to bytes 0x80 | (temp & 0x3F). + bytes.push(0x80 | (temp & 0x3F)); + + // 3. Decrease count by one. + count -= 1; + } + + // 6. Return bytes bytes, in order. + return bytes; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['UTF-8'] = function(options) { + return new UTF8Encoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['UTF-8'] = function(options) { + return new UTF8Decoder(options); + }; + + // + // 10. Legacy single-byte encodings + // + + // 10.1 single-byte decoder + /** + * @constructor + * @implements {Decoder} + * @param {!Array.} index The encoding index. + * @param {{fatal: boolean}} options + */ + function SingleByteDecoder(index, options) { + var fatal = options.fatal; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream, return finished. + if (bite === end_of_stream) + return finished; + + // 2. If byte is an ASCII byte, return a code point whose value + // is byte. + if (isASCIIByte(bite)) + return bite; + + // 3. Let code point be the index code point for byte − 0x80 in + // index single-byte. + var code_point = index[bite - 0x80]; + + // 4. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 5. Return a code point whose value is code point. + return code_point; + }; + } + + // 10.2 single-byte encoder + /** + * @constructor + * @implements {Encoder} + * @param {!Array.} index The encoding index. + * @param {{fatal: boolean}} options + */ + function SingleByteEncoder(index, options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. Let pointer be the index pointer for code point in index + // single-byte. + var pointer = indexPointerFor(code_point, index); + + // 4. If pointer is null, return error with code point. + if (pointer === null) + encoderError(code_point); + + // 5. Return a byte whose value is pointer + 0x80. + return pointer + 0x80; + }; + } + + (function() { + if (!('encoding-indexes' in global)) + return; + encodings.forEach(function(category) { + if (category.heading !== 'Legacy single-byte encodings') + return; + category.encodings.forEach(function(encoding) { + var name = encoding.name; + var idx = index(name.toLowerCase()); + /** @param {{fatal: boolean}} options */ + decoders[name] = function(options) { + return new SingleByteDecoder(idx, options); + }; + /** @param {{fatal: boolean}} options */ + encoders[name] = function(options) { + return new SingleByteEncoder(idx, options); + }; + }); + }); + }()); + + // + // 11. Legacy multi-byte Chinese (simplified) encodings + // + + // 11.1 gbk + + // 11.1.1 gbk decoder + // gbk's decoder is gb18030's decoder. + /** @param {{fatal: boolean}} options */ + decoders['GBK'] = function(options) { + return new GB18030Decoder(options); + }; + + // 11.1.2 gbk encoder + // gbk's encoder is gb18030's encoder with its gbk flag set. + /** @param {{fatal: boolean}} options */ + encoders['GBK'] = function(options) { + return new GB18030Encoder(options, true); + }; + + // 11.2 gb18030 + + // 11.2.1 gb18030 decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function GB18030Decoder(options) { + var fatal = options.fatal; + // gb18030's decoder has an associated gb18030 first, gb18030 + // second, and gb18030 third (all initially 0x00). + var /** @type {number} */ gb18030_first = 0x00, + /** @type {number} */ gb18030_second = 0x00, + /** @type {number} */ gb18030_third = 0x00; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and gb18030 first, gb18030 + // second, and gb18030 third are 0x00, return finished. + if (bite === end_of_stream && gb18030_first === 0x00 && + gb18030_second === 0x00 && gb18030_third === 0x00) { + return finished; + } + // 2. If byte is end-of-stream, and gb18030 first, gb18030 + // second, or gb18030 third is not 0x00, set gb18030 first, + // gb18030 second, and gb18030 third to 0x00, and return error. + if (bite === end_of_stream && + (gb18030_first !== 0x00 || gb18030_second !== 0x00 || + gb18030_third !== 0x00)) { + gb18030_first = 0x00; + gb18030_second = 0x00; + gb18030_third = 0x00; + decoderError(fatal); + } + var code_point; + // 3. If gb18030 third is not 0x00, run these substeps: + if (gb18030_third !== 0x00) { + // 1. Let code point be null. + code_point = null; + // 2. If byte is in the range 0x30 to 0x39, inclusive, set + // code point to the index gb18030 ranges code point for + // (((gb18030 first − 0x81) × 10 + gb18030 second − 0x30) × + // 126 + gb18030 third − 0x81) × 10 + byte − 0x30. + if (inRange(bite, 0x30, 0x39)) { + code_point = indexGB18030RangesCodePointFor( + (((gb18030_first - 0x81) * 10 + gb18030_second - 0x30) * 126 + + gb18030_third - 0x81) * 10 + bite - 0x30); + } + + // 3. Let buffer be a byte sequence consisting of gb18030 + // second, gb18030 third, and byte, in order. + var buffer = [gb18030_second, gb18030_third, bite]; + + // 4. Set gb18030 first, gb18030 second, and gb18030 third to + // 0x00. + gb18030_first = 0x00; + gb18030_second = 0x00; + gb18030_third = 0x00; + + // 5. If code point is null, prepend buffer to stream and + // return error. + if (code_point === null) { + stream.prepend(buffer); + return decoderError(fatal); + } + + // 6. Return a code point whose value is code point. + return code_point; + } + + // 4. If gb18030 second is not 0x00, run these substeps: + if (gb18030_second !== 0x00) { + + // 1. If byte is in the range 0x81 to 0xFE, inclusive, set + // gb18030 third to byte and return continue. + if (inRange(bite, 0x81, 0xFE)) { + gb18030_third = bite; + return null; + } + + // 2. Prepend gb18030 second followed by byte to stream, set + // gb18030 first and gb18030 second to 0x00, and return error. + stream.prepend([gb18030_second, bite]); + gb18030_first = 0x00; + gb18030_second = 0x00; + return decoderError(fatal); + } + + // 5. If gb18030 first is not 0x00, run these substeps: + if (gb18030_first !== 0x00) { + + // 1. If byte is in the range 0x30 to 0x39, inclusive, set + // gb18030 second to byte and return continue. + if (inRange(bite, 0x30, 0x39)) { + gb18030_second = bite; + return null; + } + + // 2. Let lead be gb18030 first, let pointer be null, and set + // gb18030 first to 0x00. + var lead = gb18030_first; + var pointer = null; + gb18030_first = 0x00; + + // 3. Let offset be 0x40 if byte is less than 0x7F and 0x41 + // otherwise. + var offset = bite < 0x7F ? 0x40 : 0x41; + + // 4. If byte is in the range 0x40 to 0x7E, inclusive, or 0x80 + // to 0xFE, inclusive, set pointer to (lead − 0x81) × 190 + + // (byte − offset). + if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) + pointer = (lead - 0x81) * 190 + (bite - offset); + + // 5. Let code point be null if pointer is null and the index + // code point for pointer in index gb18030 otherwise. + code_point = pointer === null ? null : + indexCodePointFor(pointer, index('gb18030')); + + // 6. If code point is null and byte is an ASCII byte, prepend + // byte to stream. + if (code_point === null && isASCIIByte(bite)) + stream.prepend(bite); + + // 7. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 8. Return a code point whose value is code point. + return code_point; + } + + // 6. If byte is an ASCII byte, return a code point whose value + // is byte. + if (isASCIIByte(bite)) + return bite; + + // 7. If byte is 0x80, return code point U+20AC. + if (bite === 0x80) + return 0x20AC; + + // 8. If byte is in the range 0x81 to 0xFE, inclusive, set + // gb18030 first to byte and return continue. + if (inRange(bite, 0x81, 0xFE)) { + gb18030_first = bite; + return null; + } + + // 9. Return error. + return decoderError(fatal); + }; + } + + // 11.2.2 gb18030 encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + * @param {boolean=} gbk_flag + */ + function GB18030Encoder(options, gbk_flag) { + var fatal = options.fatal; + // gb18030's decoder has an associated gbk flag (initially unset). + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. If code point is U+E5E5, return error with code point. + if (code_point === 0xE5E5) + return encoderError(code_point); + + // 4. If the gbk flag is set and code point is U+20AC, return + // byte 0x80. + if (gbk_flag && code_point === 0x20AC) + return 0x80; + + // 5. Let pointer be the index pointer for code point in index + // gb18030. + var pointer = indexPointerFor(code_point, index('gb18030')); + + // 6. If pointer is not null, run these substeps: + if (pointer !== null) { + + // 1. Let lead be floor(pointer / 190) + 0x81. + var lead = floor(pointer / 190) + 0x81; + + // 2. Let trail be pointer % 190. + var trail = pointer % 190; + + // 3. Let offset be 0x40 if trail is less than 0x3F and 0x41 otherwise. + var offset = trail < 0x3F ? 0x40 : 0x41; + + // 4. Return two bytes whose values are lead and trail + offset. + return [lead, trail + offset]; + } + + // 7. If gbk flag is set, return error with code point. + if (gbk_flag) + return encoderError(code_point); + + // 8. Set pointer to the index gb18030 ranges pointer for code + // point. + pointer = indexGB18030RangesPointerFor(code_point); + + // 9. Let byte1 be floor(pointer / 10 / 126 / 10). + var byte1 = floor(pointer / 10 / 126 / 10); + + // 10. Set pointer to pointer − byte1 × 10 × 126 × 10. + pointer = pointer - byte1 * 10 * 126 * 10; + + // 11. Let byte2 be floor(pointer / 10 / 126). + var byte2 = floor(pointer / 10 / 126); + + // 12. Set pointer to pointer − byte2 × 10 × 126. + pointer = pointer - byte2 * 10 * 126; + + // 13. Let byte3 be floor(pointer / 10). + var byte3 = floor(pointer / 10); + + // 14. Let byte4 be pointer − byte3 × 10. + var byte4 = pointer - byte3 * 10; + + // 15. Return four bytes whose values are byte1 + 0x81, byte2 + + // 0x30, byte3 + 0x81, byte4 + 0x30. + return [byte1 + 0x81, + byte2 + 0x30, + byte3 + 0x81, + byte4 + 0x30]; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['gb18030'] = function(options) { + return new GB18030Encoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['gb18030'] = function(options) { + return new GB18030Decoder(options); + }; + + + // + // 12. Legacy multi-byte Chinese (traditional) encodings + // + + // 12.1 Big5 + + // 12.1.1 Big5 decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function Big5Decoder(options) { + var fatal = options.fatal; + // Big5's decoder has an associated Big5 lead (initially 0x00). + var /** @type {number} */ Big5_lead = 0x00; + + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and Big5 lead is not 0x00, set + // Big5 lead to 0x00 and return error. + if (bite === end_of_stream && Big5_lead !== 0x00) { + Big5_lead = 0x00; + return decoderError(fatal); + } + + // 2. If byte is end-of-stream and Big5 lead is 0x00, return + // finished. + if (bite === end_of_stream && Big5_lead === 0x00) + return finished; + + // 3. If Big5 lead is not 0x00, let lead be Big5 lead, let + // pointer be null, set Big5 lead to 0x00, and then run these + // substeps: + if (Big5_lead !== 0x00) { + var lead = Big5_lead; + var pointer = null; + Big5_lead = 0x00; + + // 1. Let offset be 0x40 if byte is less than 0x7F and 0x62 + // otherwise. + var offset = bite < 0x7F ? 0x40 : 0x62; + + // 2. If byte is in the range 0x40 to 0x7E, inclusive, or 0xA1 + // to 0xFE, inclusive, set pointer to (lead − 0x81) × 157 + + // (byte − offset). + if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) + pointer = (lead - 0x81) * 157 + (bite - offset); + + // 3. If there is a row in the table below whose first column + // is pointer, return the two code points listed in its second + // column + // Pointer | Code points + // --------+-------------- + // 1133 | U+00CA U+0304 + // 1135 | U+00CA U+030C + // 1164 | U+00EA U+0304 + // 1166 | U+00EA U+030C + switch (pointer) { + case 1133: return [0x00CA, 0x0304]; + case 1135: return [0x00CA, 0x030C]; + case 1164: return [0x00EA, 0x0304]; + case 1166: return [0x00EA, 0x030C]; + } + + // 4. Let code point be null if pointer is null and the index + // code point for pointer in index Big5 otherwise. + var code_point = (pointer === null) ? null : + indexCodePointFor(pointer, index('big5')); + + // 5. If code point is null and byte is an ASCII byte, prepend + // byte to stream. + if (code_point === null && isASCIIByte(bite)) + stream.prepend(bite); + + // 6. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 7. Return a code point whose value is code point. + return code_point; + } + + // 4. If byte is an ASCII byte, return a code point whose value + // is byte. + if (isASCIIByte(bite)) + return bite; + + // 5. If byte is in the range 0x81 to 0xFE, inclusive, set Big5 + // lead to byte and return continue. + if (inRange(bite, 0x81, 0xFE)) { + Big5_lead = bite; + return null; + } + + // 6. Return error. + return decoderError(fatal); + }; + } + + // 12.1.2 Big5 encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function Big5Encoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. Let pointer be the index Big5 pointer for code point. + var pointer = indexBig5PointerFor(code_point); + + // 4. If pointer is null, return error with code point. + if (pointer === null) + return encoderError(code_point); + + // 5. Let lead be floor(pointer / 157) + 0x81. + var lead = floor(pointer / 157) + 0x81; + + // 6. If lead is less than 0xA1, return error with code point. + if (lead < 0xA1) + return encoderError(code_point); + + // 7. Let trail be pointer % 157. + var trail = pointer % 157; + + // 8. Let offset be 0x40 if trail is less than 0x3F and 0x62 + // otherwise. + var offset = trail < 0x3F ? 0x40 : 0x62; + + // Return two bytes whose values are lead and trail + offset. + return [lead, trail + offset]; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['Big5'] = function(options) { + return new Big5Encoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['Big5'] = function(options) { + return new Big5Decoder(options); + }; + + + // + // 13. Legacy multi-byte Japanese encodings + // + + // 13.1 euc-jp + + // 13.1.1 euc-jp decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function EUCJPDecoder(options) { + var fatal = options.fatal; + + // euc-jp's decoder has an associated euc-jp jis0212 flag + // (initially unset) and euc-jp lead (initially 0x00). + var /** @type {boolean} */ eucjp_jis0212_flag = false, + /** @type {number} */ eucjp_lead = 0x00; + + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and euc-jp lead is not 0x00, set + // euc-jp lead to 0x00, and return error. + if (bite === end_of_stream && eucjp_lead !== 0x00) { + eucjp_lead = 0x00; + return decoderError(fatal); + } + + // 2. If byte is end-of-stream and euc-jp lead is 0x00, return + // finished. + if (bite === end_of_stream && eucjp_lead === 0x00) + return finished; + + // 3. If euc-jp lead is 0x8E and byte is in the range 0xA1 to + // 0xDF, inclusive, set euc-jp lead to 0x00 and return a code + // point whose value is 0xFF61 − 0xA1 + byte. + if (eucjp_lead === 0x8E && inRange(bite, 0xA1, 0xDF)) { + eucjp_lead = 0x00; + return 0xFF61 - 0xA1 + bite; + } + + // 4. If euc-jp lead is 0x8F and byte is in the range 0xA1 to + // 0xFE, inclusive, set the euc-jp jis0212 flag, set euc-jp lead + // to byte, and return continue. + if (eucjp_lead === 0x8F && inRange(bite, 0xA1, 0xFE)) { + eucjp_jis0212_flag = true; + eucjp_lead = bite; + return null; + } + + // 5. If euc-jp lead is not 0x00, let lead be euc-jp lead, set + // euc-jp lead to 0x00, and run these substeps: + if (eucjp_lead !== 0x00) { + var lead = eucjp_lead; + eucjp_lead = 0x00; + + // 1. Let code point be null. + var code_point = null; + + // 2. If lead and byte are both in the range 0xA1 to 0xFE, + // inclusive, set code point to the index code point for (lead + // − 0xA1) × 94 + byte − 0xA1 in index jis0208 if the euc-jp + // jis0212 flag is unset and in index jis0212 otherwise. + if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { + code_point = indexCodePointFor( + (lead - 0xA1) * 94 + (bite - 0xA1), + index(!eucjp_jis0212_flag ? 'jis0208' : 'jis0212')); + } + + // 3. Unset the euc-jp jis0212 flag. + eucjp_jis0212_flag = false; + + // 4. If byte is not in the range 0xA1 to 0xFE, inclusive, + // prepend byte to stream. + if (!inRange(bite, 0xA1, 0xFE)) + stream.prepend(bite); + + // 5. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 6. Return a code point whose value is code point. + return code_point; + } + + // 6. If byte is an ASCII byte, return a code point whose value + // is byte. + if (isASCIIByte(bite)) + return bite; + + // 7. If byte is 0x8E, 0x8F, or in the range 0xA1 to 0xFE, + // inclusive, set euc-jp lead to byte and return continue. + if (bite === 0x8E || bite === 0x8F || inRange(bite, 0xA1, 0xFE)) { + eucjp_lead = bite; + return null; + } + + // 8. Return error. + return decoderError(fatal); + }; + } + + // 13.1.2 euc-jp encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function EUCJPEncoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. If code point is U+00A5, return byte 0x5C. + if (code_point === 0x00A5) + return 0x5C; + + // 4. If code point is U+203E, return byte 0x7E. + if (code_point === 0x203E) + return 0x7E; + + // 5. If code point is in the range U+FF61 to U+FF9F, inclusive, + // return two bytes whose values are 0x8E and code point − + // 0xFF61 + 0xA1. + if (inRange(code_point, 0xFF61, 0xFF9F)) + return [0x8E, code_point - 0xFF61 + 0xA1]; + + // 6. If code point is U+2212, set it to U+FF0D. + if (code_point === 0x2212) + code_point = 0xFF0D; + + // 7. Let pointer be the index pointer for code point in index + // jis0208. + var pointer = indexPointerFor(code_point, index('jis0208')); + + // 8. If pointer is null, return error with code point. + if (pointer === null) + return encoderError(code_point); + + // 9. Let lead be floor(pointer / 94) + 0xA1. + var lead = floor(pointer / 94) + 0xA1; + + // 10. Let trail be pointer % 94 + 0xA1. + var trail = pointer % 94 + 0xA1; + + // 11. Return two bytes whose values are lead and trail. + return [lead, trail]; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['EUC-JP'] = function(options) { + return new EUCJPEncoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['EUC-JP'] = function(options) { + return new EUCJPDecoder(options); + }; + + // 13.2 iso-2022-jp + + // 13.2.1 iso-2022-jp decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function ISO2022JPDecoder(options) { + var fatal = options.fatal; + /** @enum */ + var states = { + ASCII: 0, + Roman: 1, + Katakana: 2, + LeadByte: 3, + TrailByte: 4, + EscapeStart: 5, + Escape: 6 + }; + // iso-2022-jp's decoder has an associated iso-2022-jp decoder + // state (initially ASCII), iso-2022-jp decoder output state + // (initially ASCII), iso-2022-jp lead (initially 0x00), and + // iso-2022-jp output flag (initially unset). + var /** @type {number} */ iso2022jp_decoder_state = states.ASCII, + /** @type {number} */ iso2022jp_decoder_output_state = states.ASCII, + /** @type {number} */ iso2022jp_lead = 0x00, + /** @type {boolean} */ iso2022jp_output_flag = false; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // switching on iso-2022-jp decoder state: + switch (iso2022jp_decoder_state) { + default: + case states.ASCII: + // ASCII + // Based on byte: + + // 0x1B + if (bite === 0x1B) { + // Set iso-2022-jp decoder state to escape start and return + // continue. + iso2022jp_decoder_state = states.EscapeStart; + return null; + } + + // 0x00 to 0x7F, excluding 0x0E, 0x0F, and 0x1B + if (inRange(bite, 0x00, 0x7F) && bite !== 0x0E + && bite !== 0x0F && bite !== 0x1B) { + // Unset the iso-2022-jp output flag and return a code point + // whose value is byte. + iso2022jp_output_flag = false; + return bite; + } + + // end-of-stream + if (bite === end_of_stream) { + // Return finished. + return finished; + } + + // Otherwise + // Unset the iso-2022-jp output flag and return error. + iso2022jp_output_flag = false; + return decoderError(fatal); + + case states.Roman: + // Roman + // Based on byte: + + // 0x1B + if (bite === 0x1B) { + // Set iso-2022-jp decoder state to escape start and return + // continue. + iso2022jp_decoder_state = states.EscapeStart; + return null; + } + + // 0x5C + if (bite === 0x5C) { + // Unset the iso-2022-jp output flag and return code point + // U+00A5. + iso2022jp_output_flag = false; + return 0x00A5; + } + + // 0x7E + if (bite === 0x7E) { + // Unset the iso-2022-jp output flag and return code point + // U+203E. + iso2022jp_output_flag = false; + return 0x203E; + } + + // 0x00 to 0x7F, excluding 0x0E, 0x0F, 0x1B, 0x5C, and 0x7E + if (inRange(bite, 0x00, 0x7F) && bite !== 0x0E && bite !== 0x0F + && bite !== 0x1B && bite !== 0x5C && bite !== 0x7E) { + // Unset the iso-2022-jp output flag and return a code point + // whose value is byte. + iso2022jp_output_flag = false; + return bite; + } + + // end-of-stream + if (bite === end_of_stream) { + // Return finished. + return finished; + } + + // Otherwise + // Unset the iso-2022-jp output flag and return error. + iso2022jp_output_flag = false; + return decoderError(fatal); + + case states.Katakana: + // Katakana + // Based on byte: + + // 0x1B + if (bite === 0x1B) { + // Set iso-2022-jp decoder state to escape start and return + // continue. + iso2022jp_decoder_state = states.EscapeStart; + return null; + } + + // 0x21 to 0x5F + if (inRange(bite, 0x21, 0x5F)) { + // Unset the iso-2022-jp output flag and return a code point + // whose value is 0xFF61 − 0x21 + byte. + iso2022jp_output_flag = false; + return 0xFF61 - 0x21 + bite; + } + + // end-of-stream + if (bite === end_of_stream) { + // Return finished. + return finished; + } + + // Otherwise + // Unset the iso-2022-jp output flag and return error. + iso2022jp_output_flag = false; + return decoderError(fatal); + + case states.LeadByte: + // Lead byte + // Based on byte: + + // 0x1B + if (bite === 0x1B) { + // Set iso-2022-jp decoder state to escape start and return + // continue. + iso2022jp_decoder_state = states.EscapeStart; + return null; + } + + // 0x21 to 0x7E + if (inRange(bite, 0x21, 0x7E)) { + // Unset the iso-2022-jp output flag, set iso-2022-jp lead + // to byte, iso-2022-jp decoder state to trail byte, and + // return continue. + iso2022jp_output_flag = false; + iso2022jp_lead = bite; + iso2022jp_decoder_state = states.TrailByte; + return null; + } + + // end-of-stream + if (bite === end_of_stream) { + // Return finished. + return finished; + } + + // Otherwise + // Unset the iso-2022-jp output flag and return error. + iso2022jp_output_flag = false; + return decoderError(fatal); + + case states.TrailByte: + // Trail byte + // Based on byte: + + // 0x1B + if (bite === 0x1B) { + // Set iso-2022-jp decoder state to escape start and return + // continue. + iso2022jp_decoder_state = states.EscapeStart; + return decoderError(fatal); + } + + // 0x21 to 0x7E + if (inRange(bite, 0x21, 0x7E)) { + // 1. Set the iso-2022-jp decoder state to lead byte. + iso2022jp_decoder_state = states.LeadByte; + + // 2. Let pointer be (iso-2022-jp lead − 0x21) × 94 + byte − 0x21. + var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21; + + // 3. Let code point be the index code point for pointer in + // index jis0208. + var code_point = indexCodePointFor(pointer, index('jis0208')); + + // 4. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 5. Return a code point whose value is code point. + return code_point; + } + + // end-of-stream + if (bite === end_of_stream) { + // Set the iso-2022-jp decoder state to lead byte, prepend + // byte to stream, and return error. + iso2022jp_decoder_state = states.LeadByte; + stream.prepend(bite); + return decoderError(fatal); + } + + // Otherwise + // Set iso-2022-jp decoder state to lead byte and return + // error. + iso2022jp_decoder_state = states.LeadByte; + return decoderError(fatal); + + case states.EscapeStart: + // Escape start + + // 1. If byte is either 0x24 or 0x28, set iso-2022-jp lead to + // byte, iso-2022-jp decoder state to escape, and return + // continue. + if (bite === 0x24 || bite === 0x28) { + iso2022jp_lead = bite; + iso2022jp_decoder_state = states.Escape; + return null; + } + + // 2. Prepend byte to stream. + stream.prepend(bite); + + // 3. Unset the iso-2022-jp output flag, set iso-2022-jp + // decoder state to iso-2022-jp decoder output state, and + // return error. + iso2022jp_output_flag = false; + iso2022jp_decoder_state = iso2022jp_decoder_output_state; + return decoderError(fatal); + + case states.Escape: + // Escape + + // 1. Let lead be iso-2022-jp lead and set iso-2022-jp lead to + // 0x00. + var lead = iso2022jp_lead; + iso2022jp_lead = 0x00; + + // 2. Let state be null. + var state = null; + + // 3. If lead is 0x28 and byte is 0x42, set state to ASCII. + if (lead === 0x28 && bite === 0x42) + state = states.ASCII; + + // 4. If lead is 0x28 and byte is 0x4A, set state to Roman. + if (lead === 0x28 && bite === 0x4A) + state = states.Roman; + + // 5. If lead is 0x28 and byte is 0x49, set state to Katakana. + if (lead === 0x28 && bite === 0x49) + state = states.Katakana; + + // 6. If lead is 0x24 and byte is either 0x40 or 0x42, set + // state to lead byte. + if (lead === 0x24 && (bite === 0x40 || bite === 0x42)) + state = states.LeadByte; + + // 7. If state is non-null, run these substeps: + if (state !== null) { + // 1. Set iso-2022-jp decoder state and iso-2022-jp decoder + // output state to states. + iso2022jp_decoder_state = iso2022jp_decoder_state = state; + + // 2. Let output flag be the iso-2022-jp output flag. + var output_flag = iso2022jp_output_flag; + + // 3. Set the iso-2022-jp output flag. + iso2022jp_output_flag = true; + + // 4. Return continue, if output flag is unset, and error + // otherwise. + return !output_flag ? null : decoderError(fatal); + } + + // 8. Prepend lead and byte to stream. + stream.prepend([lead, bite]); + + // 9. Unset the iso-2022-jp output flag, set iso-2022-jp + // decoder state to iso-2022-jp decoder output state and + // return error. + iso2022jp_output_flag = false; + iso2022jp_decoder_state = iso2022jp_decoder_output_state; + return decoderError(fatal); + } + }; + } + + // 13.2.2 iso-2022-jp encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function ISO2022JPEncoder(options) { + var fatal = options.fatal; + // iso-2022-jp's encoder has an associated iso-2022-jp encoder + // state which is one of ASCII, Roman, and jis0208 (initially + // ASCII). + /** @enum */ + var states = { + ASCII: 0, + Roman: 1, + jis0208: 2 + }; + var /** @type {number} */ iso2022jp_state = states.ASCII; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream and iso-2022-jp encoder + // state is not ASCII, prepend code point to stream, set + // iso-2022-jp encoder state to ASCII, and return three bytes + // 0x1B 0x28 0x42. + if (code_point === end_of_stream && + iso2022jp_state !== states.ASCII) { + stream.prepend(code_point); + iso2022jp_state = states.ASCII; + return [0x1B, 0x28, 0x42]; + } + + // 2. If code point is end-of-stream and iso-2022-jp encoder + // state is ASCII, return finished. + if (code_point === end_of_stream && iso2022jp_state === states.ASCII) + return finished; + + // 3. If ISO-2022-JP encoder state is ASCII or Roman, and code + // point is U+000E, U+000F, or U+001B, return error with U+FFFD. + if ((iso2022jp_state === states.ASCII || + iso2022jp_state === states.Roman) && + (code_point === 0x000E || code_point === 0x000F || + code_point === 0x001B)) { + return encoderError(0xFFFD); + } + + // 4. If iso-2022-jp encoder state is ASCII and code point is an + // ASCII code point, return a byte whose value is code point. + if (iso2022jp_state === states.ASCII && + isASCIICodePoint(code_point)) + return code_point; + + // 5. If iso-2022-jp encoder state is Roman and code point is an + // ASCII code point, excluding U+005C and U+007E, or is U+00A5 + // or U+203E, run these substeps: + if (iso2022jp_state === states.Roman && + ((isASCIICodePoint(code_point) && + code_point !== 0x005C && code_point !== 0x007E) || + (code_point == 0x00A5 || code_point == 0x203E))) { + + // 1. If code point is an ASCII code point, return a byte + // whose value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 2. If code point is U+00A5, return byte 0x5C. + if (code_point === 0x00A5) + return 0x5C; + + // 3. If code point is U+203E, return byte 0x7E. + if (code_point === 0x203E) + return 0x7E; + } + + // 6. If code point is an ASCII code point, and iso-2022-jp + // encoder state is not ASCII, prepend code point to stream, set + // iso-2022-jp encoder state to ASCII, and return three bytes + // 0x1B 0x28 0x42. + if (isASCIICodePoint(code_point) && + iso2022jp_state !== states.ASCII) { + stream.prepend(code_point); + iso2022jp_state = states.ASCII; + return [0x1B, 0x28, 0x42]; + } + + // 7. If code point is either U+00A5 or U+203E, and iso-2022-jp + // encoder state is not Roman, prepend code point to stream, set + // iso-2022-jp encoder state to Roman, and return three bytes + // 0x1B 0x28 0x4A. + if ((code_point === 0x00A5 || code_point === 0x203E) && + iso2022jp_state !== states.Roman) { + stream.prepend(code_point); + iso2022jp_state = states.Roman; + return [0x1B, 0x28, 0x4A]; + } + + // 8. If code point is U+2212, set it to U+FF0D. + if (code_point === 0x2212) + code_point = 0xFF0D; + + // 9. Let pointer be the index pointer for code point in index + // jis0208. + var pointer = indexPointerFor(code_point, index('jis0208')); + + // 10. If pointer is null, return error with code point. + if (pointer === null) + return encoderError(code_point); + + // 11. If iso-2022-jp encoder state is not jis0208, prepend code + // point to stream, set iso-2022-jp encoder state to jis0208, + // and return three bytes 0x1B 0x24 0x42. + if (iso2022jp_state !== states.jis0208) { + stream.prepend(code_point); + iso2022jp_state = states.jis0208; + return [0x1B, 0x24, 0x42]; + } + + // 12. Let lead be floor(pointer / 94) + 0x21. + var lead = floor(pointer / 94) + 0x21; + + // 13. Let trail be pointer % 94 + 0x21. + var trail = pointer % 94 + 0x21; + + // 14. Return two bytes whose values are lead and trail. + return [lead, trail]; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['ISO-2022-JP'] = function(options) { + return new ISO2022JPEncoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['ISO-2022-JP'] = function(options) { + return new ISO2022JPDecoder(options); + }; + + // 13.3 Shift_JIS + + // 13.3.1 Shift_JIS decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function ShiftJISDecoder(options) { + var fatal = options.fatal; + // Shift_JIS's decoder has an associated Shift_JIS lead (initially + // 0x00). + var /** @type {number} */ Shift_JIS_lead = 0x00; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and Shift_JIS lead is not 0x00, + // set Shift_JIS lead to 0x00 and return error. + if (bite === end_of_stream && Shift_JIS_lead !== 0x00) { + Shift_JIS_lead = 0x00; + return decoderError(fatal); + } + + // 2. If byte is end-of-stream and Shift_JIS lead is 0x00, + // return finished. + if (bite === end_of_stream && Shift_JIS_lead === 0x00) + return finished; + + // 3. If Shift_JIS lead is not 0x00, let lead be Shift_JIS lead, + // let pointer be null, set Shift_JIS lead to 0x00, and then run + // these substeps: + if (Shift_JIS_lead !== 0x00) { + var lead = Shift_JIS_lead; + var pointer = null; + Shift_JIS_lead = 0x00; + + // 1. Let offset be 0x40, if byte is less than 0x7F, and 0x41 + // otherwise. + var offset = (bite < 0x7F) ? 0x40 : 0x41; + + // 2. Let lead offset be 0x81, if lead is less than 0xA0, and + // 0xC1 otherwise. + var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1; + + // 3. If byte is in the range 0x40 to 0x7E, inclusive, or 0x80 + // to 0xFC, inclusive, set pointer to (lead − lead offset) × + // 188 + byte − offset. + if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) + pointer = (lead - lead_offset) * 188 + bite - offset; + + // 4. If pointer is in the range 8836 to 10715, inclusive, + // return a code point whose value is 0xE000 − 8836 + pointer. + if (inRange(pointer, 8836, 10715)) + return 0xE000 - 8836 + pointer; + + // 5. Let code point be null, if pointer is null, and the + // index code point for pointer in index jis0208 otherwise. + var code_point = (pointer === null) ? null : + indexCodePointFor(pointer, index('jis0208')); + + // 6. If code point is null and byte is an ASCII byte, prepend + // byte to stream. + if (code_point === null && isASCIIByte(bite)) + stream.prepend(bite); + + // 7. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 8. Return a code point whose value is code point. + return code_point; + } + + // 4. If byte is an ASCII byte or 0x80, return a code point + // whose value is byte. + if (isASCIIByte(bite) || bite === 0x80) + return bite; + + // 5. If byte is in the range 0xA1 to 0xDF, inclusive, return a + // code point whose value is 0xFF61 − 0xA1 + byte. + if (inRange(bite, 0xA1, 0xDF)) + return 0xFF61 - 0xA1 + bite; + + // 6. If byte is in the range 0x81 to 0x9F, inclusive, or 0xE0 + // to 0xFC, inclusive, set Shift_JIS lead to byte and return + // continue. + if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) { + Shift_JIS_lead = bite; + return null; + } + + // 7. Return error. + return decoderError(fatal); + }; + } + + // 13.3.2 Shift_JIS encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function ShiftJISEncoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point or U+0080, return a + // byte whose value is code point. + if (isASCIICodePoint(code_point) || code_point === 0x0080) + return code_point; + + // 3. If code point is U+00A5, return byte 0x5C. + if (code_point === 0x00A5) + return 0x5C; + + // 4. If code point is U+203E, return byte 0x7E. + if (code_point === 0x203E) + return 0x7E; + + // 5. If code point is in the range U+FF61 to U+FF9F, inclusive, + // return a byte whose value is code point − 0xFF61 + 0xA1. + if (inRange(code_point, 0xFF61, 0xFF9F)) + return code_point - 0xFF61 + 0xA1; + + // 6. If code point is U+2212, set it to U+FF0D. + if (code_point === 0x2212) + code_point = 0xFF0D; + + // 7. Let pointer be the index Shift_JIS pointer for code point. + var pointer = indexShiftJISPointerFor(code_point); + + // 8. If pointer is null, return error with code point. + if (pointer === null) + return encoderError(code_point); + + // 9. Let lead be floor(pointer / 188). + var lead = floor(pointer / 188); + + // 10. Let lead offset be 0x81, if lead is less than 0x1F, and + // 0xC1 otherwise. + var lead_offset = (lead < 0x1F) ? 0x81 : 0xC1; + + // 11. Let trail be pointer % 188. + var trail = pointer % 188; + + // 12. Let offset be 0x40, if trail is less than 0x3F, and 0x41 + // otherwise. + var offset = (trail < 0x3F) ? 0x40 : 0x41; + + // 13. Return two bytes whose values are lead + lead offset and + // trail + offset. + return [lead + lead_offset, trail + offset]; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['Shift_JIS'] = function(options) { + return new ShiftJISEncoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['Shift_JIS'] = function(options) { + return new ShiftJISDecoder(options); + }; + + // + // 14. Legacy multi-byte Korean encodings + // + + // 14.1 euc-kr + + // 14.1.1 euc-kr decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function EUCKRDecoder(options) { + var fatal = options.fatal; + + // euc-kr's decoder has an associated euc-kr lead (initially 0x00). + var /** @type {number} */ euckr_lead = 0x00; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and euc-kr lead is not 0x00, set + // euc-kr lead to 0x00 and return error. + if (bite === end_of_stream && euckr_lead !== 0) { + euckr_lead = 0x00; + return decoderError(fatal); + } + + // 2. If byte is end-of-stream and euc-kr lead is 0x00, return + // finished. + if (bite === end_of_stream && euckr_lead === 0) + return finished; + + // 3. If euc-kr lead is not 0x00, let lead be euc-kr lead, let + // pointer be null, set euc-kr lead to 0x00, and then run these + // substeps: + if (euckr_lead !== 0x00) { + var lead = euckr_lead; + var pointer = null; + euckr_lead = 0x00; + + // 1. If byte is in the range 0x41 to 0xFE, inclusive, set + // pointer to (lead − 0x81) × 190 + (byte − 0x41). + if (inRange(bite, 0x41, 0xFE)) + pointer = (lead - 0x81) * 190 + (bite - 0x41); + + // 2. Let code point be null, if pointer is null, and the + // index code point for pointer in index euc-kr otherwise. + var code_point = (pointer === null) + ? null : indexCodePointFor(pointer, index('euc-kr')); + + // 3. If code point is null and byte is an ASCII byte, prepend + // byte to stream. + if (pointer === null && isASCIIByte(bite)) + stream.prepend(bite); + + // 4. If code point is null, return error. + if (code_point === null) + return decoderError(fatal); + + // 5. Return a code point whose value is code point. + return code_point; + } + + // 4. If byte is an ASCII byte, return a code point whose value + // is byte. + if (isASCIIByte(bite)) + return bite; + + // 5. If byte is in the range 0x81 to 0xFE, inclusive, set + // euc-kr lead to byte and return continue. + if (inRange(bite, 0x81, 0xFE)) { + euckr_lead = bite; + return null; + } + + // 6. Return error. + return decoderError(fatal); + }; + } + + // 14.1.2 euc-kr encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function EUCKREncoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. Let pointer be the index pointer for code point in index + // euc-kr. + var pointer = indexPointerFor(code_point, index('euc-kr')); + + // 4. If pointer is null, return error with code point. + if (pointer === null) + return encoderError(code_point); + + // 5. Let lead be floor(pointer / 190) + 0x81. + var lead = floor(pointer / 190) + 0x81; + + // 6. Let trail be pointer % 190 + 0x41. + var trail = (pointer % 190) + 0x41; + + // 7. Return two bytes whose values are lead and trail. + return [lead, trail]; + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['EUC-KR'] = function(options) { + return new EUCKREncoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['EUC-KR'] = function(options) { + return new EUCKRDecoder(options); + }; + + + // + // 15. Legacy miscellaneous encodings + // + + // 15.1 replacement + + // Not needed - API throws RangeError + + // 15.2 Common infrastructure for utf-16be and utf-16le + + /** + * @param {number} code_unit + * @param {boolean} utf16be + * @return {!Array.} bytes + */ + function convertCodeUnitToBytes(code_unit, utf16be) { + // 1. Let byte1 be code unit >> 8. + var byte1 = code_unit >> 8; + + // 2. Let byte2 be code unit & 0x00FF. + var byte2 = code_unit & 0x00FF; + + // 3. Then return the bytes in order: + // utf-16be flag is set: byte1, then byte2. + if (utf16be) + return [byte1, byte2]; + // utf-16be flag is unset: byte2, then byte1. + return [byte2, byte1]; + } + + // 15.2.1 shared utf-16 decoder + /** + * @constructor + * @implements {Decoder} + * @param {boolean} utf16_be True if big-endian, false if little-endian. + * @param {{fatal: boolean}} options + */ + function UTF16Decoder(utf16_be, options) { + var fatal = options.fatal; + var /** @type {?number} */ utf16_lead_byte = null, + /** @type {?number} */ utf16_lead_surrogate = null; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream and either utf-16 lead byte or + // utf-16 lead surrogate is not null, set utf-16 lead byte and + // utf-16 lead surrogate to null, and return error. + if (bite === end_of_stream && (utf16_lead_byte !== null || + utf16_lead_surrogate !== null)) { + return decoderError(fatal); + } + + // 2. If byte is end-of-stream and utf-16 lead byte and utf-16 + // lead surrogate are null, return finished. + if (bite === end_of_stream && utf16_lead_byte === null && + utf16_lead_surrogate === null) { + return finished; + } + + // 3. If utf-16 lead byte is null, set utf-16 lead byte to byte + // and return continue. + if (utf16_lead_byte === null) { + utf16_lead_byte = bite; + return null; + } + + // 4. Let code unit be the result of: + var code_unit; + if (utf16_be) { + // utf-16be decoder flag is set + // (utf-16 lead byte << 8) + byte. + code_unit = (utf16_lead_byte << 8) + bite; + } else { + // utf-16be decoder flag is unset + // (byte << 8) + utf-16 lead byte. + code_unit = (bite << 8) + utf16_lead_byte; + } + // Then set utf-16 lead byte to null. + utf16_lead_byte = null; + + // 5. If utf-16 lead surrogate is not null, let lead surrogate + // be utf-16 lead surrogate, set utf-16 lead surrogate to null, + // and then run these substeps: + if (utf16_lead_surrogate !== null) { + var lead_surrogate = utf16_lead_surrogate; + utf16_lead_surrogate = null; + + // 1. If code unit is in the range U+DC00 to U+DFFF, + // inclusive, return a code point whose value is 0x10000 + + // ((lead surrogate − 0xD800) << 10) + (code unit − 0xDC00). + if (inRange(code_unit, 0xDC00, 0xDFFF)) { + return 0x10000 + (lead_surrogate - 0xD800) * 0x400 + + (code_unit - 0xDC00); + } + + // 2. Prepend the sequence resulting of converting code unit + // to bytes using utf-16be decoder flag to stream and return + // error. + stream.prepend(convertCodeUnitToBytes(code_unit, utf16_be)); + return decoderError(fatal); + } + + // 6. If code unit is in the range U+D800 to U+DBFF, inclusive, + // set utf-16 lead surrogate to code unit and return continue. + if (inRange(code_unit, 0xD800, 0xDBFF)) { + utf16_lead_surrogate = code_unit; + return null; + } + + // 7. If code unit is in the range U+DC00 to U+DFFF, inclusive, + // return error. + if (inRange(code_unit, 0xDC00, 0xDFFF)) + return decoderError(fatal); + + // 8. Return code point code unit. + return code_unit; + }; + } + + // 15.2.2 shared utf-16 encoder + /** + * @constructor + * @implements {Encoder} + * @param {boolean} utf16_be True if big-endian, false if little-endian. + * @param {{fatal: boolean}} options + */ + function UTF16Encoder(utf16_be, options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1. If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is in the range U+0000 to U+FFFF, inclusive, + // return the sequence resulting of converting code point to + // bytes using utf-16be encoder flag. + if (inRange(code_point, 0x0000, 0xFFFF)) + return convertCodeUnitToBytes(code_point, utf16_be); + + // 3. Let lead be ((code point − 0x10000) >> 10) + 0xD800, + // converted to bytes using utf-16be encoder flag. + var lead = convertCodeUnitToBytes( + ((code_point - 0x10000) >> 10) + 0xD800, utf16_be); + + // 4. Let trail be ((code point − 0x10000) & 0x3FF) + 0xDC00, + // converted to bytes using utf-16be encoder flag. + var trail = convertCodeUnitToBytes( + ((code_point - 0x10000) & 0x3FF) + 0xDC00, utf16_be); + + // 5. Return a byte sequence of lead followed by trail. + return lead.concat(trail); + }; + } + + // 15.3 utf-16be + // 15.3.1 utf-16be decoder + /** @param {{fatal: boolean}} options */ + encoders['UTF-16BE'] = function(options) { + return new UTF16Encoder(true, options); + }; + // 15.3.2 utf-16be encoder + /** @param {{fatal: boolean}} options */ + decoders['UTF-16BE'] = function(options) { + return new UTF16Decoder(true, options); + }; + + // 15.4 utf-16le + // 15.4.1 utf-16le decoder + /** @param {{fatal: boolean}} options */ + encoders['UTF-16LE'] = function(options) { + return new UTF16Encoder(false, options); + }; + // 15.4.2 utf-16le encoder + /** @param {{fatal: boolean}} options */ + decoders['UTF-16LE'] = function(options) { + return new UTF16Decoder(false, options); + }; + + // 15.5 x-user-defined + + // 15.5.1 x-user-defined decoder + /** + * @constructor + * @implements {Decoder} + * @param {{fatal: boolean}} options + */ + function XUserDefinedDecoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream The stream of bytes being decoded. + * @param {number} bite The next byte read from the stream. + * @return {?(number|!Array.)} The next code point(s) + * decoded, or null if not enough data exists in the input + * stream to decode a complete code point. + */ + this.handler = function(stream, bite) { + // 1. If byte is end-of-stream, return finished. + if (bite === end_of_stream) + return finished; + + // 2. If byte is an ASCII byte, return a code point whose value + // is byte. + if (isASCIIByte(bite)) + return bite; + + // 3. Return a code point whose value is 0xF780 + byte − 0x80. + return 0xF780 + bite - 0x80; + }; + } + + // 15.5.2 x-user-defined encoder + /** + * @constructor + * @implements {Encoder} + * @param {{fatal: boolean}} options + */ + function XUserDefinedEncoder(options) { + var fatal = options.fatal; + /** + * @param {Stream} stream Input stream. + * @param {number} code_point Next code point read from the stream. + * @return {(number|!Array.)} Byte(s) to emit. + */ + this.handler = function(stream, code_point) { + // 1.If code point is end-of-stream, return finished. + if (code_point === end_of_stream) + return finished; + + // 2. If code point is an ASCII code point, return a byte whose + // value is code point. + if (isASCIICodePoint(code_point)) + return code_point; + + // 3. If code point is in the range U+F780 to U+F7FF, inclusive, + // return a byte whose value is code point − 0xF780 + 0x80. + if (inRange(code_point, 0xF780, 0xF7FF)) + return code_point - 0xF780 + 0x80; + + // 4. Return error with code point. + return encoderError(code_point); + }; + } + + /** @param {{fatal: boolean}} options */ + encoders['x-user-defined'] = function(options) { + return new XUserDefinedEncoder(options); + }; + /** @param {{fatal: boolean}} options */ + decoders['x-user-defined'] = function(options) { + return new XUserDefinedDecoder(options); + }; + + if (typeof module !== "undefined" && module.exports) { + module.exports = { + TextEncoder: TextEncoder, + TextDecoder: TextDecoder, + EncodingIndexes: require("./encoding-indexes.js")["encoding-indexes"] + }; + } + +// For strict environments where `this` inside the global scope +// is `undefined`, take a pure object instead +}(this || {})); diff --git a/nodejs/node_modules/bson/vendor/text-encoding/package.json b/nodejs/node_modules/bson/vendor/text-encoding/package.json new file mode 100644 index 00000000..ffc3155a --- /dev/null +++ b/nodejs/node_modules/bson/vendor/text-encoding/package.json @@ -0,0 +1,37 @@ +{ + "name": "text-encoding", + "author": "Joshua Bell ", + "contributors": [ + "Joshua Bell ", + "Rick Eyre ", + "Eugen Podaru ", + "Filip Dupanović ", + "Anne van Kesteren ", + "Author: Francis Avila ", + "Michael J. Ryan ", + "Pierre Queinnec ", + "Zack Weinberg " + ], + "version": "0.7.0", + "description": "Polyfill for the Encoding Living Standard's API.", + "main": "index.js", + "files": [ + "index.js", + "lib/encoding.js", + "lib/encoding-indexes.js" + ], + "repository": { + "type": "git", + "url": "https://github.com/inexorabletash/text-encoding.git" + }, + "keywords": [ + "encoding", + "decoding", + "living standard" + ], + "bugs": { + "url": "https://github.com/inexorabletash/text-encoding/issues" + }, + "homepage": "https://github.com/inexorabletash/text-encoding", + "license": "(Unlicense OR Apache-2.0)" +} diff --git a/nodejs/node_modules/buffer/AUTHORS.md b/nodejs/node_modules/buffer/AUTHORS.md new file mode 100644 index 00000000..22eb1712 --- /dev/null +++ b/nodejs/node_modules/buffer/AUTHORS.md @@ -0,0 +1,70 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- Renée Kooi (renee@kooi.me) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) +- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) +- kumavis (aaron@kumavis.me) +- Sergey Ukustov (sergey.ukustov@machinomy.com) +- Fei Liu (liu.feiwood@gmail.com) +- Blaine Bublitz (blaine.bublitz@gmail.com) +- clement (clement@seald.io) +- Koushik Dutta (koushd@gmail.com) +- Jordan Harband (ljharb@gmail.com) +- Niklas Mischkulnig (mischnic@users.noreply.github.com) +- Nikolai Vavilov (vvnicholas@gmail.com) +- Fedor Nezhivoi (gyzerok@users.noreply.github.com) +- Peter Newman (peternewman@users.noreply.github.com) +- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) +- jkkang (jkkang@smartauth.kr) + +#### Generated by bin/update-authors.sh. diff --git a/nodejs/node_modules/buffer/LICENSE b/nodejs/node_modules/buffer/LICENSE new file mode 100644 index 00000000..d6bf75dc --- /dev/null +++ b/nodejs/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/buffer/README.md b/nodejs/node_modules/buffer/README.md new file mode 100644 index 00000000..9a23d7cf --- /dev/null +++ b/nodejs/node_modules/buffer/README.md @@ -0,0 +1,410 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + +## Security Policies and Procedures + +The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/nodejs/node_modules/buffer/index.d.ts b/nodejs/node_modules/buffer/index.d.ts new file mode 100644 index 00000000..5d1a804e --- /dev/null +++ b/nodejs/node_modules/buffer/index.d.ts @@ -0,0 +1,186 @@ +export class Buffer extends Uint8Array { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer | Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initializing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; +} diff --git a/nodejs/node_modules/buffer/index.js b/nodejs/node_modules/buffer/index.js new file mode 100644 index 00000000..609cf311 --- /dev/null +++ b/nodejs/node_modules/buffer/index.js @@ -0,0 +1,1817 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + var proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef' + var table = new Array(256) + for (var i = 0; i < 16; ++i) { + var i16 = i * 16 + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() diff --git a/nodejs/node_modules/buffer/package.json b/nodejs/node_modules/buffer/package.json new file mode 100644 index 00000000..3b1b4986 --- /dev/null +++ b/nodejs/node_modules/buffer/package.json @@ -0,0 +1,96 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "5.7.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + }, + "devDependencies": { + "airtap": "^3.0.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "concat-stream": "^2.0.0", + "hyperquest": "^2.1.3", + "is-buffer": "^2.0.4", + "is-nan": "^1.3.0", + "split": "^1.0.1", + "standard": "*", + "tape": "^5.0.1", + "through2": "^4.0.2", + "uglify-js": "^3.11.3" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-es5": "airtap -- test/*.js", + "test-browser-es5-local": "airtap --local -- test/*.js", + "test-browser-es6": "airtap -- test/*.js test/node/*.js", + "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.js" + ], + "globals": [ + "SharedArrayBuffer" + ] + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/nodejs/node_modules/color-convert/CHANGELOG.md b/nodejs/node_modules/color-convert/CHANGELOG.md new file mode 100644 index 00000000..0a7bce4f --- /dev/null +++ b/nodejs/node_modules/color-convert/CHANGELOG.md @@ -0,0 +1,54 @@ +# 1.0.0 - 2016-01-07 + +- Removed: unused speed test +- Added: Automatic routing between previously unsupported conversions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `convert()` class +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: all functions to lookup dictionary +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: `ansi` to `ansi256` +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Fixed: argument grouping for functions requiring only one argument +([#27](https://github.com/Qix-/color-convert/pull/27)) + +# 0.6.0 - 2015-07-23 + +- Added: methods to handle +[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: + - rgb2ansi16 + - rgb2ansi + - hsl2ansi16 + - hsl2ansi + - hsv2ansi16 + - hsv2ansi + - hwb2ansi16 + - hwb2ansi + - cmyk2ansi16 + - cmyk2ansi + - keyword2ansi16 + - keyword2ansi + - ansi162rgb + - ansi162hsl + - ansi162hsv + - ansi162hwb + - ansi162cmyk + - ansi162keyword + - ansi2rgb + - ansi2hsl + - ansi2hsv + - ansi2hwb + - ansi2cmyk + - ansi2keyword +([#18](https://github.com/harthur/color-convert/pull/18)) + +# 0.5.3 - 2015-06-02 + +- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` +([#15](https://github.com/harthur/color-convert/issues/15)) + +--- + +Check out commit logs for older releases diff --git a/nodejs/node_modules/color-convert/LICENSE b/nodejs/node_modules/color-convert/LICENSE new file mode 100644 index 00000000..5b4c386f --- /dev/null +++ b/nodejs/node_modules/color-convert/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011-2016 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/nodejs/node_modules/color-convert/README.md b/nodejs/node_modules/color-convert/README.md new file mode 100644 index 00000000..d4b08fc3 --- /dev/null +++ b/nodejs/node_modules/color-convert/README.md @@ -0,0 +1,68 @@ +# color-convert + +[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) + +Color-convert is a color conversion library for JavaScript and node. +It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): + +```js +var convert = require('color-convert'); + +convert.rgb.hsl(140, 200, 100); // [96, 48, 59] +convert.keyword.rgb('blue'); // [0, 0, 255] + +var rgbChannels = convert.rgb.channels; // 3 +var cmykChannels = convert.cmyk.channels; // 4 +var ansiChannels = convert.ansi16.channels; // 1 +``` + +# Install + +```console +$ npm install color-convert +``` + +# API + +Simply get the property of the _from_ and _to_ conversion that you're looking for. + +All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. + +All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). + +```js +var convert = require('color-convert'); + +// Hex to LAB +convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] +convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] + +// RGB to CMYK +convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] +convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] +``` + +### Arrays +All functions that accept multiple arguments also support passing an array. + +Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) + +```js +var convert = require('color-convert'); + +convert.rgb.hex(123, 45, 67); // '7B2D43' +convert.rgb.hex([123, 45, 67]); // '7B2D43' +``` + +## Routing + +Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). + +Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). + +# Contribute + +If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. + +# License +Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). diff --git a/nodejs/node_modules/color-convert/conversions.js b/nodejs/node_modules/color-convert/conversions.js new file mode 100644 index 00000000..32172007 --- /dev/null +++ b/nodejs/node_modules/color-convert/conversions.js @@ -0,0 +1,868 @@ +/* MIT license */ +var cssKeywords = require('color-name'); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; diff --git a/nodejs/node_modules/color-convert/index.js b/nodejs/node_modules/color-convert/index.js new file mode 100644 index 00000000..e65b5d77 --- /dev/null +++ b/nodejs/node_modules/color-convert/index.js @@ -0,0 +1,78 @@ +var conversions = require('./conversions'); +var route = require('./route'); + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; diff --git a/nodejs/node_modules/color-convert/package.json b/nodejs/node_modules/color-convert/package.json new file mode 100644 index 00000000..dfbc4714 --- /dev/null +++ b/nodejs/node_modules/color-convert/package.json @@ -0,0 +1,46 @@ +{ + "name": "color-convert", + "description": "Plain color conversion functions", + "version": "1.9.3", + "author": "Heather Arthur ", + "license": "MIT", + "repository": "Qix-/color-convert", + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "keywords": [ + "color", + "colour", + "convert", + "converter", + "conversion", + "rgb", + "hsl", + "hsv", + "hwb", + "cmyk", + "ansi", + "ansi16" + ], + "files": [ + "index.js", + "conversions.js", + "css-keywords.js", + "route.js" + ], + "xo": { + "rules": { + "default-case": 0, + "no-inline-comments": 0, + "operator-linebreak": 0 + } + }, + "devDependencies": { + "chalk": "1.1.1", + "xo": "0.11.2" + }, + "dependencies": { + "color-name": "1.1.3" + } +} diff --git a/nodejs/node_modules/color-convert/route.js b/nodejs/node_modules/color-convert/route.js new file mode 100644 index 00000000..0a1fdea6 --- /dev/null +++ b/nodejs/node_modules/color-convert/route.js @@ -0,0 +1,97 @@ +var conversions = require('./conversions'); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + diff --git a/nodejs/node_modules/color-name/.eslintrc.json b/nodejs/node_modules/color-name/.eslintrc.json new file mode 100644 index 00000000..c50c2504 --- /dev/null +++ b/nodejs/node_modules/color-name/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/nodejs/node_modules/color-name/.npmignore b/nodejs/node_modules/color-name/.npmignore new file mode 100644 index 00000000..f9f28164 --- /dev/null +++ b/nodejs/node_modules/color-name/.npmignore @@ -0,0 +1,107 @@ +//this will affect all the git repos +git config --global core.excludesfile ~/.gitignore + + +//update files since .ignore won't if already tracked +git rm --cached + +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +# Icon? +ehthumbs.db +Thumbs.db +.cache +.project +.settings +.tmproj +*.esproj +nbproject + +# Numerous always-ignore extensions # +##################################### +*.diff +*.err +*.orig +*.rej +*.swn +*.swo +*.swp +*.vi +*~ +*.sass-cache +*.grunt +*.tmp + +# Dreamweaver added files # +########################### +_notes +dwsync.xml + +# Komodo # +########################### +*.komodoproject +.komodotools + +# Node # +##################### +node_modules + +# Bower # +##################### +bower_components + +# Folders to ignore # +##################### +.hg +.svn +.CVS +intermediate +publish +.idea +.graphics +_test +_archive +uploads +tmp + +# Vim files to ignore # +####################### +.VimballRecord +.netrwhist + +bundle.* + +_demo \ No newline at end of file diff --git a/nodejs/node_modules/color-name/LICENSE b/nodejs/node_modules/color-name/LICENSE new file mode 100644 index 00000000..c6b10012 --- /dev/null +++ b/nodejs/node_modules/color-name/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/nodejs/node_modules/color-name/README.md b/nodejs/node_modules/color-name/README.md new file mode 100644 index 00000000..932b9791 --- /dev/null +++ b/nodejs/node_modules/color-name/README.md @@ -0,0 +1,11 @@ +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. + +[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) + + +```js +var colors = require('color-name'); +colors.red //[255,0,0] +``` + + diff --git a/nodejs/node_modules/color-name/index.js b/nodejs/node_modules/color-name/index.js new file mode 100644 index 00000000..b7c198a6 --- /dev/null +++ b/nodejs/node_modules/color-name/index.js @@ -0,0 +1,152 @@ +'use strict' + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; diff --git a/nodejs/node_modules/color-name/package.json b/nodejs/node_modules/color-name/package.json new file mode 100644 index 00000000..d061123e --- /dev/null +++ b/nodejs/node_modules/color-name/package.json @@ -0,0 +1,25 @@ +{ + "name": "color-name", + "version": "1.1.3", + "description": "A list of color names and its values", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:dfcreative/color-name.git" + }, + "keywords": [ + "color-name", + "color", + "color-keyword", + "keyword" + ], + "author": "DY ", + "license": "MIT", + "bugs": { + "url": "https://github.com/dfcreative/color-name/issues" + }, + "homepage": "https://github.com/dfcreative/color-name" +} diff --git a/nodejs/node_modules/color-name/test.js b/nodejs/node_modules/color-name/test.js new file mode 100644 index 00000000..6e6bf30b --- /dev/null +++ b/nodejs/node_modules/color-name/test.js @@ -0,0 +1,7 @@ +'use strict' + +var names = require('./'); +var assert = require('assert'); + +assert.deepEqual(names.red, [255,0,0]); +assert.deepEqual(names.aliceblue, [240,248,255]); diff --git a/nodejs/node_modules/color-string/LICENSE b/nodejs/node_modules/color-string/LICENSE new file mode 100644 index 00000000..a8b08d4f --- /dev/null +++ b/nodejs/node_modules/color-string/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/nodejs/node_modules/color-string/README.md b/nodejs/node_modules/color-string/README.md new file mode 100644 index 00000000..e58670c6 --- /dev/null +++ b/nodejs/node_modules/color-string/README.md @@ -0,0 +1,62 @@ +# color-string + +> library for parsing and generating CSS color strings. + +## Install + +With [npm](http://npmjs.org/): + +```console +$ npm install color-string +``` + +## Usage + +### Parsing + +```js +colorString.get('#FFF') // {model: 'rgb', value: [255, 255, 255, 1]} +colorString.get('#FFFA') // {model: 'rgb', value: [255, 255, 255, 0.67]} +colorString.get('#FFFFFFAA') // {model: 'rgb', value: [255, 255, 255, 0.67]} +colorString.get('hsl(360, 100%, 50%)') // {model: 'hsl', value: [0, 100, 50, 1]} +colorString.get('hsl(360 100% 50%)') // {model: 'hsl', value: [0, 100, 50, 1]} +colorString.get('hwb(60, 3%, 60%)') // {model: 'hwb', value: [60, 3, 60, 1]} + +colorString.get.rgb('#FFF') // [255, 255, 255, 1] +colorString.get.rgb('blue') // [0, 0, 255, 1] +colorString.get.rgb('rgba(200, 60, 60, 0.3)') // [200, 60, 60, 0.3] +colorString.get.rgb('rgba(200 60 60 / 0.3)') // [200, 60, 60, 0.3] +colorString.get.rgb('rgba(200 60 60 / 30%)') // [200, 60, 60, 0.3] +colorString.get.rgb('rgb(200, 200, 200)') // [200, 200, 200, 1] +colorString.get.rgb('rgb(200 200 200)') // [200, 200, 200, 1] + +colorString.get.hsl('hsl(360, 100%, 50%)') // [0, 100, 50, 1] +colorString.get.hsl('hsl(360 100% 50%)') // [0, 100, 50, 1] +colorString.get.hsl('hsla(360, 60%, 50%, 0.4)') // [0, 60, 50, 0.4] +colorString.get.hsl('hsl(360 60% 50% / 0.4)') // [0, 60, 50, 0.4] + +colorString.get.hwb('hwb(60, 3%, 60%)') // [60, 3, 60, 1] +colorString.get.hwb('hwb(60, 3%, 60%, 0.6)') // [60, 3, 60, 0.6] + +colorString.get.rgb('invalid color string') // null +``` + +### Generation + +```js +colorString.to.hex([255, 255, 255]) // "#FFFFFF" +colorString.to.hex([0, 0, 255, 0.4]) // "#0000FF66" +colorString.to.hex([0, 0, 255], 0.4) // "#0000FF66" +colorString.to.rgb([255, 255, 255]) // "rgb(255, 255, 255)" +colorString.to.rgb([0, 0, 255, 0.4]) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb([0, 0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb.percent([0, 0, 255]) // "rgb(0%, 0%, 100%)" +colorString.to.keyword([255, 255, 0]) // "yellow" +colorString.to.hsl([360, 100, 100]) // "hsl(360, 100%, 100%)" +colorString.to.hwb([50, 3, 15]) // "hwb(50, 3%, 15%)" + +// all functions also support swizzling +colorString.to.rgb(0, [0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb([0, 0], [255], 0.4) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb([0], 0, [255, 0.4]) // "rgba(0, 0, 255, 0.4)" +``` diff --git a/nodejs/node_modules/color-string/index.js b/nodejs/node_modules/color-string/index.js new file mode 100644 index 00000000..dd5d2b7b --- /dev/null +++ b/nodejs/node_modules/color-string/index.js @@ -0,0 +1,242 @@ +/* MIT license */ +var colorNames = require('color-name'); +var swizzle = require('simple-swizzle'); +var hasOwnProperty = Object.hasOwnProperty; + +var reverseNames = Object.create(null); + +// create a list of reverse color names +for (var name in colorNames) { + if (hasOwnProperty.call(colorNames, name)) { + reverseNames[colorNames[name]] = name; + } +} + +var cs = module.exports = { + to: {}, + get: {} +}; + +cs.get = function (string) { + var prefix = string.substring(0, 3).toLowerCase(); + var val; + var model; + switch (prefix) { + case 'hsl': + val = cs.get.hsl(string); + model = 'hsl'; + break; + case 'hwb': + val = cs.get.hwb(string); + model = 'hwb'; + break; + default: + val = cs.get.rgb(string); + model = 'rgb'; + break; + } + + if (!val) { + return null; + } + + return {model: model, value: val}; +}; + +cs.get.rgb = function (string) { + if (!string) { + return null; + } + + var abbr = /^#([a-f0-9]{3,4})$/i; + var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; + var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var keyword = /^(\w+)$/; + + var rgb = [0, 0, 0, 1]; + var match; + var i; + var hexAlpha; + + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + + for (i = 0; i < 3; i++) { + // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 + var i2 = i * 2; + rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); + } + + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i] + match[i], 16); + } + + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i + 1], 0); + } + + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); + } + + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(keyword)) { + if (match[1] === 'transparent') { + return [0, 0, 0, 0]; + } + + if (!hasOwnProperty.call(colorNames, match[1])) { + return null; + } + + rgb = colorNames[match[1]]; + rgb[3] = 1; + + return rgb; + } else { + return null; + } + + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); + } + rgb[3] = clamp(rgb[3], 0, 1); + + return rgb; +}; + +cs.get.hsl = function (string) { + if (!string) { + return null; + } + + var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hsl); + + if (match) { + var alpha = parseFloat(match[4]); + var h = ((parseFloat(match[1]) % 360) + 360) % 360; + var s = clamp(parseFloat(match[2]), 0, 100); + var l = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + + return [h, s, l, a]; + } + + return null; +}; + +cs.get.hwb = function (string) { + if (!string) { + return null; + } + + var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hwb); + + if (match) { + var alpha = parseFloat(match[4]); + var h = ((parseFloat(match[1]) % 360) + 360) % 360; + var w = clamp(parseFloat(match[2]), 0, 100); + var b = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w, b, a]; + } + + return null; +}; + +cs.to.hex = function () { + var rgba = swizzle(arguments); + + return ( + '#' + + hexDouble(rgba[0]) + + hexDouble(rgba[1]) + + hexDouble(rgba[2]) + + (rgba[3] < 1 + ? (hexDouble(Math.round(rgba[3] * 255))) + : '') + ); +}; + +cs.to.rgb = function () { + var rgba = swizzle(arguments); + + return rgba.length < 4 || rgba[3] === 1 + ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')' + : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')'; +}; + +cs.to.rgb.percent = function () { + var rgba = swizzle(arguments); + + var r = Math.round(rgba[0] / 255 * 100); + var g = Math.round(rgba[1] / 255 * 100); + var b = Math.round(rgba[2] / 255 * 100); + + return rgba.length < 4 || rgba[3] === 1 + ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)' + : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')'; +}; + +cs.to.hsl = function () { + var hsla = swizzle(arguments); + return hsla.length < 4 || hsla[3] === 1 + ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)' + : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')'; +}; + +// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax +// (hwb have alpha optional & 1 is default value) +cs.to.hwb = function () { + var hwba = swizzle(arguments); + + var a = ''; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ', ' + hwba[3]; + } + + return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')'; +}; + +cs.to.keyword = function (rgb) { + return reverseNames[rgb.slice(0, 3)]; +}; + +// helpers +function clamp(num, min, max) { + return Math.min(Math.max(min, num), max); +} + +function hexDouble(num) { + var str = Math.round(num).toString(16).toUpperCase(); + return (str.length < 2) ? '0' + str : str; +} diff --git a/nodejs/node_modules/color-string/package.json b/nodejs/node_modules/color-string/package.json new file mode 100644 index 00000000..f34ee980 --- /dev/null +++ b/nodejs/node_modules/color-string/package.json @@ -0,0 +1,39 @@ +{ + "name": "color-string", + "description": "Parser and generator for CSS color strings", + "version": "1.9.1", + "author": "Heather Arthur ", + "contributors": [ + "Maxime Thirouin", + "Dyma Ywanov ", + "Josh Junon" + ], + "repository": "Qix-/color-string", + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "xo": { + "rules": { + "no-cond-assign": 0, + "operator-linebreak": 0 + } + }, + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + }, + "devDependencies": { + "xo": "^0.12.1" + }, + "keywords": [ + "color", + "colour", + "rgb", + "css" + ] +} diff --git a/nodejs/node_modules/color/LICENSE b/nodejs/node_modules/color/LICENSE new file mode 100644 index 00000000..68c864ee --- /dev/null +++ b/nodejs/node_modules/color/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2012 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/nodejs/node_modules/color/README.md b/nodejs/node_modules/color/README.md new file mode 100644 index 00000000..7d48f73e --- /dev/null +++ b/nodejs/node_modules/color/README.md @@ -0,0 +1,123 @@ +# color [![Build Status](https://travis-ci.org/Qix-/color.svg?branch=master)](https://travis-ci.org/Qix-/color) + +> JavaScript library for immutable color conversion and manipulation with support for CSS color strings. + +```js +var color = Color('#7743CE').alpha(0.5).lighten(0.5); +console.log(color.hsl().string()); // 'hsla(262, 59%, 81%, 0.5)' + +console.log(color.cmyk().round().array()); // [ 16, 25, 0, 8, 0.5 ] + +console.log(color.ansi256().object()); // { ansi256: 183, alpha: 0.5 } +``` + +## Install +```console +$ npm install color +``` + +## Usage +```js +var Color = require('color'); +``` + +### Constructors +```js +var color = Color('rgb(255, 255, 255)') +var color = Color({r: 255, g: 255, b: 255}) +var color = Color.rgb(255, 255, 255) +var color = Color.rgb([255, 255, 255]) +``` + +Set the values for individual channels with `alpha`, `red`, `green`, `blue`, `hue`, `saturationl` (hsl), `saturationv` (hsv), `lightness`, `whiteness`, `blackness`, `cyan`, `magenta`, `yellow`, `black` + +String constructors are handled by [color-string](https://www.npmjs.com/package/color-string) + +### Getters +```js +color.hsl(); +``` +Convert a color to a different space (`hsl()`, `cmyk()`, etc.). + +```js +color.object(); // {r: 255, g: 255, b: 255} +``` +Get a hash of the color value. Reflects the color's current model (see above). + +```js +color.rgb().array() // [255, 255, 255] +``` +Get an array of the values with `array()`. Reflects the color's current model (see above). + +```js +color.rgbNumber() // 16777215 (0xffffff) +``` +Get the rgb number value. + +```js +color.hex() // #ffffff +``` +Get the hex value. + +```js +color.red() // 255 +``` +Get the value for an individual channel. + +### CSS Strings +```js +color.hsl().string() // 'hsl(320, 50%, 100%)' +``` + +Calling `.string()` with a number rounds the numbers to that decimal place. It defaults to 1. + +### Luminosity +```js +color.luminosity(); // 0.412 +``` +The [WCAG luminosity](http://www.w3.org/TR/WCAG20/#relativeluminancedef) of the color. 0 is black, 1 is white. + +```js +color.contrast(Color("blue")) // 12 +``` +The [WCAG contrast ratio](http://www.w3.org/TR/WCAG20/#contrast-ratiodef) to another color, from 1 (same color) to 21 (contrast b/w white and black). + +```js +color.isLight(); // true +color.isDark(); // false +``` +Get whether the color is "light" or "dark", useful for deciding text color. + +### Manipulation +```js +color.negate() // rgb(0, 100, 255) -> rgb(255, 155, 0) + +color.lighten(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%) +color.lighten(0.5) // hsl(100, 50%, 0) -> hsl(100, 50%, 0) +color.darken(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%) +color.darken(0.5) // hsl(100, 50%, 0) -> hsl(100, 50%, 0) + +color.lightness(50) // hsl(100, 50%, 10%) -> hsl(100, 50%, 50%) + +color.saturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%) +color.desaturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%) +color.grayscale() // #5CBF54 -> #969696 + +color.whiten(0.5) // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%) +color.blacken(0.5) // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%) + +color.fade(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4) +color.opaquer(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0) + +color.rotate(180) // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%) +color.rotate(-90) // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%) + +color.mix(Color("yellow")) // cyan -> rgb(128, 255, 128) +color.mix(Color("yellow"), 0.3) // cyan -> rgb(77, 255, 179) + +// chaining +color.green(100).grayscale().lighten(0.6) +``` + +## Propers +The API was inspired by [color-js](https://github.com/brehaut/color-js). Manipulation functions by CSS tools like Sass, LESS, and Stylus. diff --git a/nodejs/node_modules/color/index.js b/nodejs/node_modules/color/index.js new file mode 100644 index 00000000..c756588b --- /dev/null +++ b/nodejs/node_modules/color/index.js @@ -0,0 +1,482 @@ +'use strict'; + +var colorString = require('color-string'); +var convert = require('color-convert'); + +var _slice = [].slice; + +var skippedModels = [ + // to be honest, I don't really feel like keyword belongs in color convert, but eh. + 'keyword', + + // gray conflicts with some method names, and has its own method defined. + 'gray', + + // shouldn't really be in color-convert either... + 'hex' +]; + +var hashedModelKeys = {}; +Object.keys(convert).forEach(function (model) { + hashedModelKeys[_slice.call(convert[model].labels).sort().join('')] = model; +}); + +var limiters = {}; + +function Color(obj, model) { + if (!(this instanceof Color)) { + return new Color(obj, model); + } + + if (model && model in skippedModels) { + model = null; + } + + if (model && !(model in convert)) { + throw new Error('Unknown model: ' + model); + } + + var i; + var channels; + + if (obj == null) { // eslint-disable-line no-eq-null,eqeqeq + this.model = 'rgb'; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (obj instanceof Color) { + this.model = obj.model; + this.color = obj.color.slice(); + this.valpha = obj.valpha; + } else if (typeof obj === 'string') { + var result = colorString.get(obj); + if (result === null) { + throw new Error('Unable to parse color from string: ' + obj); + } + + this.model = result.model; + channels = convert[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1; + } else if (obj.length) { + this.model = model || 'rgb'; + channels = convert[this.model].channels; + var newArr = _slice.call(obj, 0, channels); + this.color = zeroArray(newArr, channels); + this.valpha = typeof obj[channels] === 'number' ? obj[channels] : 1; + } else if (typeof obj === 'number') { + // this is always RGB - can be converted later on. + obj &= 0xFFFFFF; + this.model = 'rgb'; + this.color = [ + (obj >> 16) & 0xFF, + (obj >> 8) & 0xFF, + obj & 0xFF + ]; + this.valpha = 1; + } else { + this.valpha = 1; + + var keys = Object.keys(obj); + if ('alpha' in obj) { + keys.splice(keys.indexOf('alpha'), 1); + this.valpha = typeof obj.alpha === 'number' ? obj.alpha : 0; + } + + var hashedKeys = keys.sort().join(''); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error('Unable to parse color from object: ' + JSON.stringify(obj)); + } + + this.model = hashedModelKeys[hashedKeys]; + + var labels = convert[this.model].labels; + var color = []; + for (i = 0; i < labels.length; i++) { + color.push(obj[labels[i]]); + } + + this.color = zeroArray(color); + } + + // perform limitations (clamping, etc.) + if (limiters[this.model]) { + channels = convert[this.model].channels; + for (i = 0; i < channels; i++) { + var limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } + } + } + + this.valpha = Math.max(0, Math.min(1, this.valpha)); + + if (Object.freeze) { + Object.freeze(this); + } +} + +Color.prototype = { + toString: function () { + return this.string(); + }, + + toJSON: function () { + return this[this.model](); + }, + + string: function (places) { + var self = this.model in colorString.to ? this : this.rgb(); + self = self.round(typeof places === 'number' ? places : 1); + var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha); + return colorString.to[self.model](args); + }, + + percentString: function (places) { + var self = this.rgb().round(typeof places === 'number' ? places : 1); + var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha); + return colorString.to.rgb.percent(args); + }, + + array: function () { + return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha); + }, + + object: function () { + var result = {}; + var channels = convert[this.model].channels; + var labels = convert[this.model].labels; + + for (var i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; + } + + if (this.valpha !== 1) { + result.alpha = this.valpha; + } + + return result; + }, + + unitArray: function () { + var rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + + if (this.valpha !== 1) { + rgb.push(this.valpha); + } + + return rgb; + }, + + unitObject: function () { + var rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + + if (this.valpha !== 1) { + rgb.alpha = this.valpha; + } + + return rgb; + }, + + round: function (places) { + places = Math.max(places || 0, 0); + return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model); + }, + + alpha: function (val) { + if (arguments.length) { + return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model); + } + + return this.valpha; + }, + + // rgb + red: getset('rgb', 0, maxfn(255)), + green: getset('rgb', 1, maxfn(255)), + blue: getset('rgb', 2, maxfn(255)), + + hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, function (val) { return ((val % 360) + 360) % 360; }), // eslint-disable-line brace-style + + saturationl: getset('hsl', 1, maxfn(100)), + lightness: getset('hsl', 2, maxfn(100)), + + saturationv: getset('hsv', 1, maxfn(100)), + value: getset('hsv', 2, maxfn(100)), + + chroma: getset('hcg', 1, maxfn(100)), + gray: getset('hcg', 2, maxfn(100)), + + white: getset('hwb', 1, maxfn(100)), + wblack: getset('hwb', 2, maxfn(100)), + + cyan: getset('cmyk', 0, maxfn(100)), + magenta: getset('cmyk', 1, maxfn(100)), + yellow: getset('cmyk', 2, maxfn(100)), + black: getset('cmyk', 3, maxfn(100)), + + x: getset('xyz', 0, maxfn(100)), + y: getset('xyz', 1, maxfn(100)), + z: getset('xyz', 2, maxfn(100)), + + l: getset('lab', 0, maxfn(100)), + a: getset('lab', 1), + b: getset('lab', 2), + + keyword: function (val) { + if (arguments.length) { + return new Color(val); + } + + return convert[this.model].keyword(this.color); + }, + + hex: function (val) { + if (arguments.length) { + return new Color(val); + } + + return colorString.to.hex(this.rgb().round().color); + }, + + rgbNumber: function () { + var rgb = this.rgb().color; + return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF); + }, + + luminosity: function () { + // http://www.w3.org/TR/WCAG20/#relativeluminancedef + var rgb = this.rgb().color; + + var lum = []; + for (var i = 0; i < rgb.length; i++) { + var chan = rgb[i] / 255; + lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4); + } + + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + + contrast: function (color2) { + // http://www.w3.org/TR/WCAG20/#contrast-ratiodef + var lum1 = this.luminosity(); + var lum2 = color2.luminosity(); + + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + + return (lum2 + 0.05) / (lum1 + 0.05); + }, + + level: function (color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return 'AAA'; + } + + return (contrastRatio >= 4.5) ? 'AA' : ''; + }, + + isDark: function () { + // YIQ equation from http://24ways.org/2010/calculating-color-contrast + var rgb = this.rgb().color; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000; + return yiq < 128; + }, + + isLight: function () { + return !this.isDark(); + }, + + negate: function () { + var rgb = this.rgb(); + for (var i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; + } + return rgb; + }, + + lighten: function (ratio) { + var hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + + darken: function (ratio) { + var hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + + saturate: function (ratio) { + var hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + + desaturate: function (ratio) { + var hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + + whiten: function (ratio) { + var hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + + blacken: function (ratio) { + var hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + + grayscale: function () { + // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale + var rgb = this.rgb().color; + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(val, val, val); + }, + + fade: function (ratio) { + return this.alpha(this.valpha - (this.valpha * ratio)); + }, + + opaquer: function (ratio) { + return this.alpha(this.valpha + (this.valpha * ratio)); + }, + + rotate: function (degrees) { + var hsl = this.hsl(); + var hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + + mix: function (mixinColor, weight) { + // ported from sass implementation in C + // https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + if (!mixinColor || !mixinColor.rgb) { + throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); + } + var color1 = mixinColor.rgb(); + var color2 = this.rgb(); + var p = weight === undefined ? 0.5 : weight; + + var w = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + + var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + return Color.rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p)); + } +}; + +// model conversion methods and static constructors +Object.keys(convert).forEach(function (model) { + if (skippedModels.indexOf(model) !== -1) { + return; + } + + var channels = convert[model].channels; + + // conversion methods + Color.prototype[model] = function () { + if (this.model === model) { + return new Color(this); + } + + if (arguments.length) { + return new Color(arguments, model); + } + + var newAlpha = typeof arguments[channels] === 'number' ? channels : this.valpha; + return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model); + }; + + // 'static' construction methods + Color[model] = function (color) { + if (typeof color === 'number') { + color = zeroArray(_slice.call(arguments), channels); + } + return new Color(color, model); + }; +}); + +function roundTo(num, places) { + return Number(num.toFixed(places)); +} + +function roundToPlace(places) { + return function (num) { + return roundTo(num, places); + }; +} + +function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + + model.forEach(function (m) { + (limiters[m] || (limiters[m] = []))[channel] = modifier; + }); + + model = model[0]; + + return function (val) { + var result; + + if (arguments.length) { + if (modifier) { + val = modifier(val); + } + + result = this[model](); + result.color[channel] = val; + return result; + } + + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + + return result; + }; +} + +function maxfn(max) { + return function (v) { + return Math.max(0, Math.min(max, v)); + }; +} + +function assertArray(val) { + return Array.isArray(val) ? val : [val]; +} + +function zeroArray(arr, length) { + for (var i = 0; i < length; i++) { + if (typeof arr[i] !== 'number') { + arr[i] = 0; + } + } + + return arr; +} + +module.exports = Color; diff --git a/nodejs/node_modules/color/package.json b/nodejs/node_modules/color/package.json new file mode 100644 index 00000000..8e6ca3f3 --- /dev/null +++ b/nodejs/node_modules/color/package.json @@ -0,0 +1,40 @@ +{ + "name": "color", + "version": "3.2.1", + "description": "Color conversion and manipulation with CSS string support", + "keywords": [ + "color", + "colour", + "css" + ], + "authors": [ + "Josh Junon ", + "Heather Arthur ", + "Maxime Thirouin" + ], + "license": "MIT", + "repository": "Qix-/color", + "xo": { + "rules": { + "no-cond-assign": 0, + "new-cap": 0 + } + }, + "files": [ + "CHANGELOG.md", + "LICENSE", + "index.js" + ], + "scripts": { + "pretest": "xo", + "test": "mocha" + }, + "dependencies": { + "color-convert": "^1.9.3", + "color-string": "^1.6.0" + }, + "devDependencies": { + "mocha": "9.0.2", + "xo": "0.12.1" + } +} diff --git a/nodejs/node_modules/colorspace/LICENSE.md b/nodejs/node_modules/colorspace/LICENSE.md new file mode 100644 index 00000000..9beaab11 --- /dev/null +++ b/nodejs/node_modules/colorspace/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the Contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/colorspace/README.md b/nodejs/node_modules/colorspace/README.md new file mode 100644 index 00000000..c26690f8 --- /dev/null +++ b/nodejs/node_modules/colorspace/README.md @@ -0,0 +1,43 @@ +# colorspace + +Colorspace is a simple module which generates HEX color codes for namespaces. +The base color is decided by the first part of the namespace. All other parts of +the namespace alters the color tone. This way you can visually see which +namespaces belong together and which does not. + +## Installation + +The module is released in the public npm registry and can be installed by +running: + +``` +npm install --save colorspace +``` + +## Usage + +We assume that you've already required the module using the following code: + +```js +'use strict'; + +var colorspace = require('colorspace'); +``` + +The returned function accepts 2 arguments: + +1. `namespace` **string**, The namespace that needs to have a HEX color + generated. +2. `delimiter`, **string**, **optional**, Delimiter to find the different + sections of the namespace. Defaults to `:` + +#### Example + +```js +console.log(colorspace('color')) // #6b4b3a +console.log(colorspace('color:space')) // #796B67 +``` + +## License + +MIT diff --git a/nodejs/node_modules/colorspace/index.js b/nodejs/node_modules/colorspace/index.js new file mode 100644 index 00000000..cb56eb6d --- /dev/null +++ b/nodejs/node_modules/colorspace/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var color = require('color') + , hex = require('text-hex'); + +/** + * Generate a color for a given name. But be reasonably smart about it by + * understanding name spaces and coloring each namespace a bit lighter so they + * still have the same base color as the root. + * + * @param {string} namespace The namespace + * @param {string} [delimiter] The delimiter + * @returns {string} color + */ +module.exports = function colorspace(namespace, delimiter) { + var split = namespace.split(delimiter || ':'); + var base = hex(split[0]); + + if (!split.length) return base; + + for (var i = 0, l = split.length - 1; i < l; i++) { + base = color(base) + .mix(color(hex(split[i + 1]))) + .saturate(1) + .hex(); + } + + return base; +}; diff --git a/nodejs/node_modules/colorspace/package.json b/nodejs/node_modules/colorspace/package.json new file mode 100644 index 00000000..ede6f4b9 --- /dev/null +++ b/nodejs/node_modules/colorspace/package.json @@ -0,0 +1,37 @@ +{ + "name": "colorspace", + "version": "1.1.4", + "description": "Generate HEX colors for a given namespace.", + "main": "index.js", + "scripts": { + "test": "mocha test.js" + }, + "keywords": [ + "namespace", + "color", + "hex", + "colorize", + "name", + "space", + "colorspace" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "bugs": { + "url": "https://github.com/3rd-Eden/colorspace/issues" + }, + "homepage": "https://github.com/3rd-Eden/colorspace", + "repository": { + "type": "git", + "url": "https://github.com/3rd-Eden/colorspace" + }, + "dependencies": { + "color": "^3.1.3", + "text-hex": "1.0.x" + }, + "devDependencies": { + "assume": "2.1.x", + "mocha": "5.2.x", + "pre-commit": "1.2.x" + } +} diff --git a/nodejs/node_modules/console/LICENSE b/nodejs/node_modules/console/LICENSE new file mode 100644 index 00000000..36a73cf7 --- /dev/null +++ b/nodejs/node_modules/console/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013-present Matthew Hudson + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/console/README.markdown b/nodejs/node_modules/console/README.markdown new file mode 100644 index 00000000..9d3f20c0 --- /dev/null +++ b/nodejs/node_modules/console/README.markdown @@ -0,0 +1,38 @@ +# Console + +[![NPM version](https://badge.fury.io/js/console.svg)](http://badge.fury.io/js/console) +[![NPM downloads](https://img.shields.io/npm/dm/console.svg)](https://www.npmjs.com/package/console) + +> Drop-in replacement for `console` - a cross-environment fix for missing +methods. + +## Installation + +``` sh +npm install console --save +``` + +And then import it: + +``` js +// using es modules +import console from 'console' + +// common.js +const console = require('console').default + +// AMD +// I've forgotten but it should work. +``` + +Or use script tags and globals. + +``` html + +``` + +And then grab it off the global like so: + +``` js +const console = console.default +``` diff --git a/nodejs/node_modules/console/es/index.js b/nodejs/node_modules/console/es/index.js new file mode 100644 index 00000000..d806091b --- /dev/null +++ b/nodejs/node_modules/console/es/index.js @@ -0,0 +1,16 @@ +// Avoid `console` errors in environments that lack a console. +var method = void 0; +var noop = function noop() {}; +var methods = ["assert", "clear", "count", "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time", "timeEnd", "timeStamp", "trace", "warn"]; +var length = methods.length; + +while (length--) { + method = methods[length]; + + // Only stub undefined methods. + if (!console[method]) { + console[method] = noop; + } +} + +export default console; \ No newline at end of file diff --git a/nodejs/node_modules/console/lib/index.js b/nodejs/node_modules/console/lib/index.js new file mode 100644 index 00000000..67384155 --- /dev/null +++ b/nodejs/node_modules/console/lib/index.js @@ -0,0 +1,20 @@ +"use strict"; + +exports.__esModule = true; +// Avoid `console` errors in environments that lack a console. +var method = void 0; +var noop = function noop() {}; +var methods = ["assert", "clear", "count", "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time", "timeEnd", "timeStamp", "trace", "warn"]; +var length = methods.length; + +while (length--) { + method = methods[length]; + + // Only stub undefined methods. + if (!console[method]) { + console[method] = noop; + } +} + +exports.default = console; +module.exports = exports["default"]; \ No newline at end of file diff --git a/nodejs/node_modules/console/package.json b/nodejs/node_modules/console/package.json new file mode 100644 index 00000000..7cf2e9f0 --- /dev/null +++ b/nodejs/node_modules/console/package.json @@ -0,0 +1,27 @@ +{ + "name": "console", + "version": "0.7.2", + "homepage": "https://github.com/matthewhudson/console", + "description": "Returns `console` if present, otherwise returns a `noop`.", + "main": "lib/index.js", + "module": "es/index.js", + "files": [ + "es", + "lib", + "umd" + ], + "keywords": [ + "console" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/matthewhudson/console.git" + }, + "bugs": { + "url": "https://github.com/matthewhudson/console/issues" + }, + "devDependencies": { + "nwb": "0.21.5" + } +} diff --git a/nodejs/node_modules/console/umd/console.js b/nodejs/node_modules/console/umd/console.js new file mode 100644 index 00000000..b60986aa --- /dev/null +++ b/nodejs/node_modules/console/umd/console.js @@ -0,0 +1,112 @@ +/*! + * console v0.7.1 - https://github.com/matthewhudson/console + * MIT Licensed + */ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["console"] = factory(); + else + root["console"] = factory(); +})(typeof self !== 'undefined' ? self : this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = __webpack_require__(1); + + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +// Avoid `console` errors in environments that lack a console. +var method = void 0; +var noop = function noop() {}; +var methods = ["assert", "clear", "count", "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time", "timeEnd", "timeStamp", "trace", "warn"]; +var length = methods.length; + +while (length--) { + method = methods[length]; + + // Only stub undefined methods. + if (!console[method]) { + console[method] = noop; + } +} + +/* harmony default export */ __webpack_exports__["default"] = (console); + +/***/ }) +/******/ ])["default"]; +}); \ No newline at end of file diff --git a/nodejs/node_modules/console/umd/console.min.js b/nodejs/node_modules/console/umd/console.min.js new file mode 100644 index 00000000..137498a3 --- /dev/null +++ b/nodejs/node_modules/console/umd/console.min.js @@ -0,0 +1,6 @@ +/*! + * console v0.7.1 - https://github.com/matthewhudson/console + * MIT Licensed + */ +!function(e,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.console=o():e.console=o()}("undefined"!=typeof self?self:this,function(){return function(e){var o={};function t(n){if(o[n])return o[n].exports;var r=o[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,t),r.l=!0,r.exports}return t.m=e,t.c=o,t.d=function(e,o,n){t.o(e,o)||Object.defineProperty(e,o,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var o=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(o,"a",o),o},t.o=function(e,o){return Object.prototype.hasOwnProperty.call(e,o)},t.p="",t(t.s=0)}([function(e,o,t){e.exports=t(1)},function(e,o,t){"use strict";Object.defineProperty(o,"__esModule",{value:!0});for(var n=void 0,r=function(){},u=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","table","time","timeEnd","timeStamp","trace","warn"],i=u.length;i--;)n=u[i],console[n]||(console[n]=r);o.default=console}]).default}); +//# sourceMappingURL=console.min.js.map \ No newline at end of file diff --git a/nodejs/node_modules/console/umd/console.min.js.map b/nodejs/node_modules/console/umd/console.min.js.map new file mode 100644 index 00000000..1df0d99a --- /dev/null +++ b/nodejs/node_modules/console/umd/console.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 5746502fe9160877c39b","webpack:///./src/index.js"],"names":["root","factory","exports","module","define","amd","self","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","n","__esModule","object","property","prototype","hasOwnProperty","p","s","__webpack_exports__","value","method","noop","methods","length","console"],"mappings":";;;;CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,IACA,mBAAAG,eAAAC,IACAD,UAAAH,GACA,iBAAAC,QACAA,QAAA,QAAAD,IAEAD,EAAA,QAAAC,IARA,CASC,oBAAAK,UAAAC,KAAA,WACD,mBCTA,IAAAC,KAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAR,QAGA,IAAAC,EAAAK,EAAAE,IACAC,EAAAD,EACAE,GAAA,EACAV,YAUA,OANAW,EAAAH,GAAAI,KAAAX,EAAAD,QAAAC,IAAAD,QAAAO,GAGAN,EAAAS,GAAA,EAGAT,EAAAD,QAqCA,OAhCAO,EAAAM,EAAAF,EAGAJ,EAAAO,EAAAR,EAGAC,EAAAQ,EAAA,SAAAf,EAAAgB,EAAAC,GACAV,EAAAW,EAAAlB,EAAAgB,IACAG,OAAAC,eAAApB,EAAAgB,GACAK,cAAA,EACAC,YAAA,EACAC,IAAAN,KAMAV,EAAAiB,EAAA,SAAAvB,GACA,IAAAgB,EAAAhB,KAAAwB,WACA,WAA2B,OAAAxB,EAAA,SAC3B,WAAiC,OAAAA,GAEjC,OADAM,EAAAQ,EAAAE,EAAA,IAAAA,GACAA,GAIAV,EAAAW,EAAA,SAAAQ,EAAAC,GAAsD,OAAAR,OAAAS,UAAAC,eAAAjB,KAAAc,EAAAC,IAGtDpB,EAAAuB,EAAA,GAGAvB,IAAAwB,EAAA,kEC7DAZ,OAAAC,eAAAY,EAAA,cAAAC,OAAA,IA6BA,IA5BA,IAAIC,SACEC,EAAO,aACPC,GACJ,SACA,QACA,QACA,QACA,MACA,SACA,QACA,YACA,QACA,iBACA,WACA,OACA,MACA,eACA,UACA,aACA,QACA,OACA,UACA,YACA,QACA,QAEEC,EAASD,EAAQC,OAEdA,KACLH,EAASE,EAAQC,GAGZC,QAAQJ,KACXI,QAAQJ,GAAUC,GAItBH,EAAA","file":"console.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"console\"] = factory();\n\telse\n\t\troot[\"console\"] = factory();\n})(typeof self !== 'undefined' ? self : this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 5746502fe9160877c39b","// Avoid `console` errors in environments that lack a console.\nlet method;\nconst noop = function() {};\nconst methods = [\n \"assert\",\n \"clear\",\n \"count\",\n \"debug\",\n \"dir\",\n \"dirxml\",\n \"error\",\n \"exception\",\n \"group\",\n \"groupCollapsed\",\n \"groupEnd\",\n \"info\",\n \"log\",\n \"markTimeline\",\n \"profile\",\n \"profileEnd\",\n \"table\",\n \"time\",\n \"timeEnd\",\n \"timeStamp\",\n \"trace\",\n \"warn\"\n];\nlet length = methods.length;\n\nwhile (length--) {\n method = methods[length];\n\n // Only stub undefined methods.\n if (!console[method]) {\n console[method] = noop;\n }\n}\n\nexport default console;\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js"],"sourceRoot":""} \ No newline at end of file diff --git a/nodejs/node_modules/deferred-leveldown/.travis.yml b/nodejs/node_modules/deferred-leveldown/.travis.yml new file mode 100644 index 00000000..29d0b065 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/.travis.yml @@ -0,0 +1,13 @@ +language: node_js + +node_js: + - 6 + - 8 + - 10 + +notifications: + email: false + +before_script: git fetch --tags + +after_success: npm run coverage diff --git a/nodejs/node_modules/deferred-leveldown/CHANGELOG.md b/nodejs/node_modules/deferred-leveldown/CHANGELOG.md new file mode 100644 index 00000000..3cc14825 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/CHANGELOG.md @@ -0,0 +1,329 @@ +# Changelog + +## [5.3.0] - 2019-10-04 + +### Added + +- Add manifest ([Level/community#83](https://github.com/Level/community/issues/83)) ([#79](https://github.com/Level/deferred-leveldown/issues/79)) ([**@vweevers**](https://github.com/vweevers)) +- Include abstract test suite ([#77](https://github.com/Level/deferred-leveldown/issues/77)) ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Pass db to `AbstractIterator` ([#77](https://github.com/Level/deferred-leveldown/issues/77)) ([**@vweevers**](https://github.com/vweevers)) + +## [5.2.1] - 2019-09-17 + +### Fixed + +- Create iterators in order and add `type` property for `reachdown` ([#75](https://github.com/Level/deferred-leveldown/issues/75)) ([**@vweevers**](https://github.com/vweevers)) + +## [5.2.0] - 2019-09-06 + +### Changed + +- Upgrade `abstract-leveldown` from `~6.0.0` to `~6.1.0` ([#72](https://github.com/Level/deferred-leveldown/issues/72)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `hallmark` devDependency from `^0.1.0` to `^2.0.0` ([#70](https://github.com/Level/deferred-leveldown/issues/70), [#74](https://github.com/Level/deferred-leveldown/issues/74)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `standard` devDependency from `^12.0.0` to `^14.0.0` ([#69](https://github.com/Level/deferred-leveldown/issues/69), [#73](https://github.com/Level/deferred-leveldown/issues/73)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Defer `db.clear()` and `db.compactRange()` ([#72](https://github.com/Level/deferred-leveldown/issues/72)) + +## [5.1.0] - 2019-06-22 + +### Changed + +- Update `nyc` devDependency from `^13.2.0` to `^14.0.0` ([#66](https://github.com/Level/deferred-leveldown/issues/66)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Support seeking ([#68](https://github.com/Level/deferred-leveldown/issues/68)) ([**@MeirionHughes**](https://github.com/MeirionHughes)) + +## [5.0.1] - 2019-03-31 + +### Changed + +- Upgrade `nyc` devDependency from `^12.0.2` to `^13.2.0` ([#63](https://github.com/Level/deferred-leveldown/issues/63)) ([**@vweevers**](https://github.com/vweevers)) +- Apply common project tweaks ([#61](https://github.com/Level/deferred-leveldown/issues/61), [#62](https://github.com/Level/deferred-leveldown/issues/62), [`c4d169e`](https://github.com/Level/deferred-leveldown/commit/c4d169e)) ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Fix subtests by adding `t.plan()` ([#65](https://github.com/Level/deferred-leveldown/issues/65)) ([**@vweevers**](https://github.com/vweevers)) + +## [5.0.0] - 2018-12-21 + +### Changed + +- Upgrade `abstract-leveldown` dependency from `~5.0.0` to `~6.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `standard` devDependency from `^11.0.0` to `^12.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Tweak copyright years for less maintenance ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Added + +- Add `nyc` and `coveralls` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove contributors from `package.json` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove node 9 ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [4.0.2] - 2018-05-30 + +### Changed + +- Replace `util.inherits` with `inherits` module ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [4.0.1] - 2018-05-22 + +### Changed + +- Upgrade `abstract-leveldown` to `5.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [4.0.0] - 2018-05-13 + +### Added + +- Add node 10 to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Upgrade to `standard@11.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove node 4 from Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [3.0.0] - 2018-02-08 + +### Added + +- Add `9` to travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Upgrade to `abstract-leveldown@4.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove `DeferredLevelDOWN.prototype._isBuffer`, no longer needed since we use `Buffer.isBuffer()` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Defer `approximateSize()` separately ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Fix broken link in `README` and clean up old `.jshintrc` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +**Historical Note** `abstract-leveldown@4.0.0` dropped `approximateSize()` so we needed to defer this method separately for stores that support it. + +## [2.0.3] - 2017-11-04 + +### Added + +- Add `4` to travis ([**@vweevers**](https://github.com/vweevers)) +- Add node badge ([**@vweevers**](https://github.com/vweevers)) + +### Changed + +- Upgrade to `abstract-leveldown@3.0.0` ([**@vweevers**](https://github.com/vweevers)) + +**Historical Note** `abstract-leveldown@3.0.0` dropped support for node `0.12` and didn't have any breaking changes to api or behavior, hence a new patch version. + +## [2.0.2] - 2017-10-06 + +### Added + +- Add `standard` for linting ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Use svg instead of png for travis badge ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update to new badge setup ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- `_serializeKey()` and `_serializeValue()` should not modify keys or values ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.0.1] - 2017-09-12 + +### Added + +- Add Greenkeeper badge ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `6` and `8` to travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Upgrade to `abstract-leveldown@2.7.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove `0.8`, `0.10` and `0.11` from travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.0.0] - 2017-07-30 + +### Changed + +- Update dependencies ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update copyright years ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.0.0-2] - 2015-05-28 + +### Fixed + +- Fix `.iterator()` after db is opened ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.0-1] - 2015-05-28 + +No changes. + +## [2.0.0-0] - 2015-05-27 + +### Changed + +- Upgrade to `abstract-leveldown@2.4.0` for `.status` ([**@juliangruber**](https://github.com/juliangruber)) +- Change api to `leveldown` api ([**@juliangruber**](https://github.com/juliangruber)) + +## [1.2.2] - 2017-07-30 + +### Added + +- Add `4`, `6` and `7` to travis ([**@juliangruber**](https://github.com/juliangruber)) +- Add `8` to travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Update `tape` and `abstract-leveldown` dependencies ([**@juliangruber**](https://github.com/juliangruber)) + +### Removed + +- Remove `0.10` from travis ([**@juliangruber**](https://github.com/juliangruber)) + +## [1.2.1] - 2015-08-14 + +### Added + +- Add `0.12`, `2.5` and `3.0` to travis ([**@juliangruber**](https://github.com/juliangruber)) + +### Removed + +- Remove `0.8` and `0.11` from travis ([**@juliangruber**](https://github.com/juliangruber)) + +### Fixed + +- Fix iterator after `setDb` case ([**@substack**](https://github.com/substack)) +- Fix broken travis link ([**@juliangruber**](https://github.com/juliangruber)) + +## [1.2.0] - 2015-05-28 + +### Changed + +- Upgrade to `abstract-leveldown@2.4.0` for `.status` ([**@juliangruber**](https://github.com/juliangruber)) + +## [1.1.0] - 2015-05-22 + +### Changed + +- Export `DeferredIterator` ([**@juliangruber**](https://github.com/juliangruber)) + +## [1.0.0] - 2015-04-28 + +### Changed + +- Upgrade to `abstract-leveldown@2.1.2` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [0.3.0] - 2015-04-16 + +### Added + +- Add support for deferred iterators ([**@juliangruber**](https://github.com/juliangruber)) + +### Changed + +- Change to plain `MIT` license ([**@andrewrk**](https://github.com/andrewrk)) +- Update logo and copyright ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [0.2.0] - 2014-04-26 + +### Removed + +- Remove `bops` and replace with `Buffer` ([**@rvagg**](https://github.com/rvagg)) + +## [0.1.0] - 2013-10-14 + +### Changed + +- `location` passed to `AbstractLevelDOWN` constructor is optional ([**@rvagg**](https://github.com/rvagg)) + +### Removed + +- Remove `npm-dl` badge ([**@rvagg**](https://github.com/rvagg)) + +### Fixed + +- Fix broken travis badge ([**@rvagg**](https://github.com/rvagg)) +- Fix links from `rvagg/` to `Level/` ([**@rvagg**](https://github.com/rvagg)) + +## [0.0.1] - 2013-09-30 + +### Added + +- Add tests ([**@rvagg**](https://github.com/rvagg)) +- Add node `0.10` and `0.11` to travis ([**@rvagg**](https://github.com/rvagg)) + +### Changed + +- Update documentation ([**@rvagg**](https://github.com/rvagg)) + +## 0.0.0 - 2013-09-17 + +:seedling: First release. ([**@rvagg**](https://github.com/rvagg)) + +[5.3.0]: https://github.com/Level/deferred-leveldown/compare/v5.2.1...v5.3.0 + +[5.2.1]: https://github.com/Level/deferred-leveldown/compare/v5.2.0...v5.2.1 + +[5.2.0]: https://github.com/Level/deferred-leveldown/compare/v5.1.0...v5.2.0 + +[5.1.0]: https://github.com/Level/deferred-leveldown/compare/v5.0.1...v5.1.0 + +[5.0.1]: https://github.com/Level/deferred-leveldown/compare/v5.0.0...v5.0.1 + +[5.0.0]: https://github.com/Level/deferred-leveldown/compare/v4.0.2...v5.0.0 + +[4.0.2]: https://github.com/Level/deferred-leveldown/compare/v4.0.1...v4.0.2 + +[4.0.1]: https://github.com/Level/deferred-leveldown/compare/v4.0.0...v4.0.1 + +[4.0.0]: https://github.com/Level/deferred-leveldown/compare/v3.0.0...v4.0.0 + +[3.0.0]: https://github.com/Level/deferred-leveldown/compare/v2.0.3...v3.0.0 + +[2.0.3]: https://github.com/Level/deferred-leveldown/compare/v2.0.2...v2.0.3 + +[2.0.2]: https://github.com/Level/deferred-leveldown/compare/v2.0.1...v2.0.2 + +[2.0.1]: https://github.com/Level/deferred-leveldown/compare/v2.0.0...v2.0.1 + +[2.0.0]: https://github.com/Level/deferred-leveldown/compare/v2.0.0-2...v2.0.0 + +[2.0.0-2]: https://github.com/Level/deferred-leveldown/compare/v2.0.0-1...v2.0.0-2 + +[2.0.0-1]: https://github.com/Level/deferred-leveldown/compare/v2.0.0-0...v2.0.0-1 + +[2.0.0-0]: https://github.com/Level/deferred-leveldown/compare/v1.2.2...v2.0.0-0 + +[1.2.2]: https://github.com/Level/deferred-leveldown/compare/v1.2.1...v1.2.2 + +[1.2.1]: https://github.com/Level/deferred-leveldown/compare/v1.2.0...v1.2.1 + +[1.2.0]: https://github.com/Level/deferred-leveldown/compare/v1.1.0...v1.2.0 + +[1.1.0]: https://github.com/Level/deferred-leveldown/compare/v1.0.0...v1.1.0 + +[1.0.0]: https://github.com/Level/deferred-leveldown/compare/v0.3.0...v1.0.0 + +[0.3.0]: https://github.com/Level/deferred-leveldown/compare/v0.2.0...v0.3.0 + +[0.2.0]: https://github.com/Level/deferred-leveldown/compare/0.1.0...v0.2.0 + +[0.1.0]: https://github.com/Level/deferred-leveldown/compare/0.0.1...0.1.0 + +[0.0.1]: https://github.com/Level/deferred-leveldown/compare/0.0.0...0.0.1 diff --git a/nodejs/node_modules/deferred-leveldown/CONTRIBUTORS.md b/nodejs/node_modules/deferred-leveldown/CONTRIBUTORS.md new file mode 100644 index 00000000..5e0d8f49 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/CONTRIBUTORS.md @@ -0,0 +1,10 @@ +# Contributors + +| Name | GitHub | Social | +| :------------------- | :----------------------------------------------------- | :------------------------------------------------------------ | +| **Lars-Magnus Skog** | [**@ralphtheninja**](https://github.com/ralphtheninja) | [**@ralph@social.weho.st**](https://social.weho.st/@ralph) | +| **Vincent Weevers** | [**@vweevers**](https://github.com/vweevers) | [**@vweevers@twitter**](https://twitter.com/vweevers) | +| **Julian Gruber** | [**@juliangruber**](https://github.com/juliangruber) | [**@juliangruber@twitter**](https://twitter.com/juliangruber) | +| **Rod Vagg** | [**@rvagg**](https://github.com/rvagg) | [**@rvagg@twitter**](https://twitter.com/rvagg) | +| **Meirion Hughes** | [**@MeirionHughes**](https://github.com/MeirionHughes) | | +| **Andrew Kelley** | [**@andrewrk**](https://github.com/andrewrk) | | diff --git a/nodejs/node_modules/deferred-leveldown/LICENSE.md b/nodejs/node_modules/deferred-leveldown/LICENSE.md new file mode 100644 index 00000000..1e78cf89 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +**Copyright © 2013-present Rod Vagg and [Contributors](CONTRIBUTORS.md).** + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/deferred-leveldown/README.md b/nodejs/node_modules/deferred-leveldown/README.md new file mode 100644 index 00000000..9662ab54 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/README.md @@ -0,0 +1,62 @@ +# deferred-leveldown + +> A mock `abstract-leveldown` implementation that queues operations while a real `abstract-leveldown` instance is being opened. + +[![level badge][level-badge]](https://github.com/Level/awesome) +[![npm](https://img.shields.io/npm/v/deferred-leveldown.svg?label=&logo=npm)](https://www.npmjs.com/package/deferred-leveldown) +[![Node version](https://img.shields.io/node/v/deferred-leveldown.svg)](https://www.npmjs.com/package/deferred-leveldown) +[![Travis](https://img.shields.io/travis/Level/deferred-leveldown.svg?logo=travis&label=)](https://travis-ci.org/Level/deferred-leveldown) +[![Coverage Status](https://coveralls.io/repos/github/Level/deferred-leveldown/badge.svg)](https://coveralls.io/github/Level/deferred-leveldown) +[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) +[![npm](https://img.shields.io/npm/dm/deferred-leveldown.svg?label=dl)](https://www.npmjs.com/package/deferred-leveldown) +[![Backers on Open Collective](https://opencollective.com/level/backers/badge.svg?color=orange)](#backers) +[![Sponsors on Open Collective](https://opencollective.com/level/sponsors/badge.svg?color=orange)](#sponsors) + +`deferred-leveldown` implements the basic [abstract-leveldown](https://github.com/Level/abstract-leveldown) API so it can be used as a drop-in replacement where `leveldown` is needed. + +`put()`, `get()`, `del()`, `batch()` and `clear()` operations are all queued and kept in memory until the `abstract-leveldown`-compatible object has been opened through `deferred-leveldown`'s `open()` method. + +`batch()` operations will all be replayed as the array form. Chained-batch operations are converted before being stored. + +```js +const deferred = require('deferred-leveldown') +const leveldown = require('leveldown') + +const db = deferred(leveldown('location')) + +db.put('foo', 'bar', function (err) { + +}) + +db.open(function (err) { + // ... +}) +``` + +**If you are upgrading:** please see [UPGRADING.md](UPGRADING.md). + +## Contributing + +[`Level/deferred-leveldown`](https://github.com/Level/deferred-leveldown) is an **OPEN Open Source Project**. This means that: + +> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +See the [Contribution Guide](https://github.com/Level/community/blob/master/CONTRIBUTING.md) for more details. + +## Donate + +To sustain [`Level`](https://github.com/Level) and its activities, become a backer or sponsor on [Open Collective](https://opencollective.com/level). Your logo or avatar will be displayed on our 28+ [GitHub repositories](https://github.com/Level) and [npm](https://www.npmjs.com/) packages. 💖 + +### Backers + +[![Open Collective backers](https://opencollective.com/level/backers.svg?width=890)](https://opencollective.com/level) + +### Sponsors + +[![Open Collective sponsors](https://opencollective.com/level/sponsors.svg?width=890)](https://opencollective.com/level) + +## License + +[MIT](LICENSE.md) © 2013-present Rod Vagg and [Contributors](CONTRIBUTORS.md). + +[level-badge]: https://leveljs.org/img/badge.svg diff --git a/nodejs/node_modules/deferred-leveldown/UPGRADING.md b/nodejs/node_modules/deferred-leveldown/UPGRADING.md new file mode 100644 index 00000000..3887e10e --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/UPGRADING.md @@ -0,0 +1,19 @@ +# Upgrade Guide + +This document describes breaking changes and how to upgrade. For a complete list of changes including minor and patch releases, please refer to the [changelog](CHANGELOG.md). + +## v5 + + Upgraded `abstract-leveldown` to `v6.0.0`. Please see the corresponding [changelog entry](https://github.com/Level/abstract-leveldown/blob/master/CHANGELOG.md#600---2018-10-20) for more information. + +## v4 + +Dropped support for node 4. No other breaking changes. + +## v3 + +#### `.batch(array)` enforces objects + +This major release contains an upgrade to `abstract-leveldown` with a [breaking change](https://github.com/Level/abstract-leveldown/commit/a2621ad70571f6ade9d2be42632ece042e068805) for the array version of `.batch()`. This change ensures all elements in the batch array are objects. + +If you previously passed arrays to `.batch()` that contained `undefined` or `null`, they would be silently ignored. Now this will produce an error. diff --git a/nodejs/node_modules/deferred-leveldown/deferred-iterator.js b/nodejs/node_modules/deferred-leveldown/deferred-iterator.js new file mode 100644 index 00000000..28149e11 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/deferred-iterator.js @@ -0,0 +1,37 @@ +var AbstractIterator = require('abstract-leveldown').AbstractIterator +var inherits = require('inherits') + +function DeferredIterator (db, options) { + AbstractIterator.call(this, db) + + this._options = options + this._iterator = null + this._operations = [] +} + +inherits(DeferredIterator, AbstractIterator) + +DeferredIterator.prototype.setDb = function (db) { + var it = this._iterator = db.iterator(this._options) + this._operations.forEach(function (op) { + it[op.method].apply(it, op.args) + }) +} + +DeferredIterator.prototype._operation = function (method, args) { + if (this._iterator) return this._iterator[method].apply(this._iterator, args) + this._operations.push({ method: method, args: args }) +} + +'next end'.split(' ').forEach(function (m) { + DeferredIterator.prototype['_' + m] = function () { + this._operation(m, arguments) + } +}) + +// Must defer seek() rather than _seek() because it requires db._serializeKey to be available +DeferredIterator.prototype.seek = function () { + this._operation('seek', arguments) +} + +module.exports = DeferredIterator diff --git a/nodejs/node_modules/deferred-leveldown/deferred-leveldown.js b/nodejs/node_modules/deferred-leveldown/deferred-leveldown.js new file mode 100644 index 00000000..a0ff6243 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/deferred-leveldown.js @@ -0,0 +1,97 @@ +var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN +var inherits = require('inherits') +var DeferredIterator = require('./deferred-iterator') +var deferrables = 'put get del batch clear'.split(' ') +var optionalDeferrables = 'approximateSize compactRange'.split(' ') + +function DeferredLevelDOWN (db) { + AbstractLevelDOWN.call(this, db.supports || {}) + + // TODO (future major): remove this fallback; db must have manifest that + // declares approximateSize and compactRange in additionalMethods. + optionalDeferrables.forEach(function (m) { + if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) { + this.supports.additionalMethods[m] = true + } + }, this) + + this._db = db + this._operations = [] + closed(this) +} + +inherits(DeferredLevelDOWN, AbstractLevelDOWN) + +DeferredLevelDOWN.prototype.type = 'deferred-leveldown' + +DeferredLevelDOWN.prototype._open = function (options, callback) { + var self = this + + this._db.open(options, function (err) { + if (err) return callback(err) + + self._operations.forEach(function (op) { + if (op.iterator) { + op.iterator.setDb(self._db) + } else { + self._db[op.method].apply(self._db, op.args) + } + }) + self._operations = [] + + open(self) + callback() + }) +} + +DeferredLevelDOWN.prototype._close = function (callback) { + var self = this + + this._db.close(function (err) { + if (err) return callback(err) + closed(self) + callback() + }) +} + +function open (self) { + deferrables.concat('iterator').forEach(function (m) { + self['_' + m] = function () { + return this._db[m].apply(this._db, arguments) + } + }) + Object.keys(self.supports.additionalMethods).forEach(function (m) { + self[m] = function () { + return this._db[m].apply(this._db, arguments) + } + }) +} + +function closed (self) { + deferrables.forEach(function (m) { + self['_' + m] = function () { + this._operations.push({ method: m, args: arguments }) + } + }) + Object.keys(self.supports.additionalMethods).forEach(function (m) { + self[m] = function () { + this._operations.push({ method: m, args: arguments }) + } + }) + self._iterator = function (options) { + var it = new DeferredIterator(self, options) + this._operations.push({ iterator: it }) + return it + } +} + +DeferredLevelDOWN.prototype._serializeKey = function (key) { + return key +} + +DeferredLevelDOWN.prototype._serializeValue = function (value) { + return value +} + +module.exports = DeferredLevelDOWN +module.exports.DeferredIterator = DeferredIterator diff --git a/nodejs/node_modules/deferred-leveldown/package.json b/nodejs/node_modules/deferred-leveldown/package.json new file mode 100644 index 00000000..9ce3a835 --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/package.json @@ -0,0 +1,46 @@ +{ + "name": "deferred-leveldown", + "version": "5.3.0", + "description": "For handling delayed-open on LevelDOWN compatible libraries", + "license": "MIT", + "main": "deferred-leveldown.js", + "scripts": { + "test": "standard && hallmark && nyc node test.js", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "hallmark": "hallmark --fix", + "dependency-check": "dependency-check . test.js", + "prepublishOnly": "npm run dependency-check" + }, + "dependencies": { + "abstract-leveldown": "~6.2.1", + "inherits": "^2.0.3" + }, + "devDependencies": { + "coveralls": "^3.0.2", + "dependency-check": "^3.3.0", + "hallmark": "^2.0.0", + "level-community": "^3.0.0", + "memdown": "^5.0.0", + "nyc": "^14.0.0", + "reachdown": "^1.0.0", + "standard": "^14.0.0", + "tape": "^4.10.0" + }, + "hallmark": { + "community": "level-community" + }, + "repository": { + "type": "git", + "url": "https://github.com/Level/deferred-leveldown.git" + }, + "homepage": "https://github.com/Level/deferred-leveldown", + "keywords": [ + "leveldb", + "level", + "levelup", + "leveldown" + ], + "engines": { + "node": ">=6" + } +} diff --git a/nodejs/node_modules/deferred-leveldown/test.js b/nodejs/node_modules/deferred-leveldown/test.js new file mode 100644 index 00000000..ed8d353a --- /dev/null +++ b/nodejs/node_modules/deferred-leveldown/test.js @@ -0,0 +1,566 @@ +var test = require('tape') +var reachdown = require('reachdown') +var memdown = require('memdown') +var suite = require('abstract-leveldown/test') +var DeferredLevelDOWN = require('./') +var noop = function () {} + +const testCommon = suite.common({ + test: test, + factory: function () { + return new DeferredLevelDOWN(memdown()) + }, + + // Unsupported features + createIfMissing: false, + errorIfExists: false, + + // Opt-in to new clear() tests + clear: true +}) + +// Hack: disable failing tests. These fail on serialize tests +require('abstract-leveldown/test/put-test').args = noop +require('abstract-leveldown/test/get-test').args = noop +require('abstract-leveldown/test/del-test').args = noop + +// This fails on "iterator has db reference" test, as expected because +// the return value of db.iterator() depends on whether the db is open. +require('abstract-leveldown/test/iterator-test').args = noop + +// Test abstract-leveldown compliance +suite(testCommon) + +// Custom tests +test('deferred open gets correct options', function (t) { + var OPTIONS = { foo: 'BAR' } + var db = { + open: function (options, callback) { + t.same(options, OPTIONS, 'options passed on to open') + process.nextTick(callback) + } + } + + var ld = new DeferredLevelDOWN(db) + ld.open(OPTIONS, function (err) { + t.error(err, 'no error') + t.end() + }) +}) + +test('single operation', function (t) { + var called = false + var db = { + put: function (key, value, options, callback) { + t.equal(key, 'foo', 'correct key') + t.equal(value, 'bar', 'correct value') + t.deepEqual({}, options, 'empty options') + callback(null, 'called') + }, + open: function (options, callback) { + process.nextTick(callback) + } + } + + var ld = new DeferredLevelDOWN(db) + ld.put('foo', 'bar', function (err, v) { + t.error(err, 'no error') + called = v + }) + + t.ok(called === false, 'not called') + + ld.open(function (err) { + t.error(err, 'no error') + t.ok(called === 'called', 'function called') + t.end() + }) +}) + +test('many operations', function (t) { + var calls = [] + var db = { + put: function (key, value, options, callback) { + if (puts++ === 0) { + t.equal(key, 'foo1', 'correct key') + t.equal(value, 'bar1', 'correct value') + t.deepEqual(options, {}, 'empty options') + } else { + t.equal(key, 'foo2', 'correct key') + t.equal(value, 'bar2', 'correct value') + t.deepEqual(options, {}, 'empty options') + } + callback(null, 'put' + puts) + }, + get: function (key, options, callback) { + if (gets++ === 0) { + t.equal('woo1', key, 'correct key') + t.deepEqual(options, { asBuffer: true }, 'empty options') + } else { + t.equal('woo2', key, 'correct key') + t.deepEqual(options, { asBuffer: true }, 'empty options') + } + callback(null, 'gets' + gets) + }, + del: function (key, options, callback) { + t.equal('blergh', key, 'correct key') + t.deepEqual(options, {}, 'empty options') + callback(null, 'del') + }, + batch: function (arr, options, callback) { + if (batches++ === 0) { + t.deepEqual(arr, [ + { type: 'put', key: 'k1', value: 'v1' }, + { type: 'put', key: 'k2', value: 'v2' } + ], 'correct batch') + } else { + t.deepEqual(arr, [ + { type: 'put', key: 'k3', value: 'v3' }, + { type: 'put', key: 'k4', value: 'v4' } + ], 'correct batch') + } + callback() + }, + clear: function (options, callback) { + if (clears++ === 0) { + t.deepEqual(options, { reverse: false, limit: -1 }, 'default options') + } else { + t.deepEqual(options, { gt: 'k5', reverse: false, limit: -1 }, 'range option') + } + + callback() + }, + open: function (options, callback) { + process.nextTick(callback) + } + } + + var ld = new DeferredLevelDOWN(db) + var puts = 0 + var gets = 0 + var batches = 0 + var clears = 0 + + ld.put('foo1', 'bar1', function (err, v) { + t.error(err, 'no error') + calls.push({ type: 'put', key: 'foo1', v: v }) + }) + ld.get('woo1', function (err, v) { + t.error(err, 'no error') + calls.push({ type: 'get', key: 'woo1', v: v }) + }) + ld.clear(function () { + calls.push({ type: 'clear' }) + }) + ld.put('foo2', 'bar2', function (err, v) { + t.error(err, 'no error') + calls.push({ type: 'put', key: 'foo2', v: v }) + }) + ld.get('woo2', function (err, v) { + t.error(err, 'no error') + calls.push({ type: 'get', key: 'woo2', v: v }) + }) + ld.del('blergh', function (err, v) { + t.error(err, 'no error') + calls.push({ type: 'del', key: 'blergh', v: v }) + }) + ld.batch([ + { type: 'put', key: 'k1', value: 'v1' }, + { type: 'put', key: 'k2', value: 'v2' } + ], function () { + calls.push({ type: 'batch', keys: 'k1,k2' }) + }) + ld + .batch() + .put('k3', 'v3') + .put('k4', 'v4') + .write(function () { + calls.push({ type: 'batch', keys: 'k3,k4' }) + }) + ld.clear({ gt: 'k5' }, function () { + calls.push({ type: 'clear', gt: 'k5' }) + }) + + t.ok(calls.length === 0, 'not called') + + ld.open(function (err) { + t.error(err, 'no error') + + t.equal(calls.length, 9, 'all functions called') + t.deepEqual(calls, [ + { type: 'put', key: 'foo1', v: 'put1' }, + { type: 'get', key: 'woo1', v: 'gets1' }, + { type: 'clear' }, + { type: 'put', key: 'foo2', v: 'put2' }, + { type: 'get', key: 'woo2', v: 'gets2' }, + { type: 'del', key: 'blergh', v: 'del' }, + { type: 'batch', keys: 'k1,k2' }, + { type: 'batch', keys: 'k3,k4' }, + { type: 'clear', gt: 'k5' } + ], 'calls correctly behaved') + + t.end() + }) +}) + +test('keys and values should not be serialized', function (t) { + var DATA = [] + var ITEMS = [ + 123, + 'a string', + Buffer.from('w00t'), + { an: 'object' } + ] + ITEMS.forEach(function (k) { + ITEMS.forEach(function (v) { + DATA.push({ key: k, value: v }) + }) + }) + + function Db (m, fn) { + var db = { + open: function (options, cb) { + process.nextTick(cb) + } + } + var wrapper = function () { + fn.apply(null, arguments) + } + db[m] = wrapper + return new DeferredLevelDOWN(db) + } + + function noop () {} + + t.plan(8) + + t.test('put', function (t) { + var calls = [] + var ld = Db('put', function (key, value, cb) { + calls.push({ key: key, value: value }) + }) + DATA.forEach(function (d) { ld.put(d.key, d.value, noop) }) + ld.open(function (err) { + t.error(err, 'no error') + t.same(calls, DATA, 'value ok') + t.end() + }) + }) + + t.test('get', function (t) { + var calls = [] + var ld = Db('get', function (key, cb) { calls.push(key) }) + ITEMS.forEach(function (key) { ld.get(key, noop) }) + ld.open(function (err) { + t.error(err, 'no error') + t.same(calls, ITEMS, 'value ok') + t.end() + }) + }) + + t.test('del', function (t) { + var calls = [] + var ld = Db('del', function (key, cb) { calls.push(key) }) + ITEMS.forEach(function (key) { ld.del(key, noop) }) + ld.open(function (err) { + t.error(err, 'no error') + t.same(calls, ITEMS, 'value ok') + t.end() + }) + }) + + t.test('clear', function (t) { + var calls = [] + var ld = Db('clear', function (opts, cb) { calls.push(opts) }) + ITEMS.forEach(function (key) { ld.clear({ gt: key }, noop) }) + ld.open(function (err) { + t.error(err, 'no error') + t.same(calls, ITEMS.map(function (key) { + return { gt: key, reverse: false, limit: -1 } + }), 'value ok') + t.end() + }) + }) + + t.test('approximateSize', function (t) { + var calls = [] + var ld = Db('approximateSize', function (start, end, cb) { + calls.push({ start: start, end: end }) + }) + ITEMS.forEach(function (key) { ld.approximateSize(key, key, noop) }) + ld.open(function (err) { + t.error(err, 'no error') + t.same(calls, ITEMS.map(function (i) { + return { start: i, end: i } + }), 'value ok') + t.end() + }) + }) + + t.test('store not supporting approximateSize', function (t) { + var ld = Db('FOO', function () {}) + t.throws(function () { + ld.approximateSize('key', 'key', noop) + }, /approximateSize is not a function/) + t.end() + }) + + t.test('compactRange', function (t) { + var calls = [] + var ld = Db('compactRange', function (start, end, cb) { + calls.push({ start: start, end: end }) + }) + ITEMS.forEach(function (key) { ld.compactRange(key, key, noop) }) + ld.open(function (err) { + t.error(err, 'no error') + t.same(calls, ITEMS.map(function (i) { + return { start: i, end: i } + }), 'value ok') + t.end() + }) + }) + + t.test('store not supporting compactRange', function (t) { + var ld = Db('FOO', function () {}) + t.throws(function () { + ld.compactRange('key', 'key', noop) + }, /compactRange is not a function/) + t.end() + }) +}) + +test('_close calls close for underlying store', function (t) { + t.plan(2) + + var db = { + close: function (callback) { + t.pass('close for underlying store is called') + process.nextTick(callback) + } + } + var ld = new DeferredLevelDOWN(db) + + ld.close(function (err) { + t.error(err, 'no error') + }) +}) + +test('open error on underlying store calls back with error', function (t) { + t.plan(2) + + var db = { + open: function (options, callback) { + t.pass('db.open called') + process.nextTick(callback, new Error('foo')) + } + } + var ld = new DeferredLevelDOWN(db) + + ld.open(function (err) { + t.is(err.message, 'foo') + }) +}) + +test('close error on underlying store calls back with error', function (t) { + t.plan(2) + + var db = { + close: function (callback) { + t.pass('db.close called') + process.nextTick(callback, new Error('foo')) + } + } + var ld = new DeferredLevelDOWN(db) + + ld.close(function (err) { + t.is(err.message, 'foo') + }) +}) + +test('non-deferred approximateSize', function (t) { + t.plan(4) + + var db = { + open: function (options, cb) { + process.nextTick(cb) + }, + approximateSize: function (start, end, callback) { + t.is(start, 'bar') + t.is(end, 'foo') + process.nextTick(callback) + } + } + var ld = new DeferredLevelDOWN(db) + + ld.open(function (err) { + t.error(err) + ld.approximateSize('bar', 'foo', function (err) { + t.error(err) + }) + }) +}) + +test('non-deferred compactRange', function (t) { + t.plan(4) + + var db = { + open: function (options, cb) { + process.nextTick(cb) + }, + compactRange: function (start, end, callback) { + t.is(start, 'bar') + t.is(end, 'foo') + process.nextTick(callback) + } + } + var ld = new DeferredLevelDOWN(db) + + ld.open(function (err) { + t.error(err) + ld.compactRange('bar', 'foo', function (err) { + t.error(err) + }) + }) +}) + +test('iterator - deferred operations', function (t) { + t.plan(9) + + var seekTarget = false + + var db = { + iterator: function (options) { + return { + seek: function (target) { + seekTarget = target + }, + next: function (cb) { + cb(null, 'key', 'value') + }, + end: function (cb) { + process.nextTick(cb) + } + } + }, + open: function (options, callback) { + process.nextTick(callback) + } + } + var ld = new DeferredLevelDOWN(db) + var it = ld.iterator() + var nextFirst = false + + it.seek('foo') + + it.next(function (err, key, value) { + t.is(seekTarget, 'foo', 'seek was called with correct target') + nextFirst = true + t.error(err, 'no error') + t.equal(key, 'key') + t.equal(value, 'value') + }) + + it.end(function (err) { + t.error(err, 'no error') + t.ok(nextFirst) + }) + + ld.open(function (err) { + t.error(err, 'no error') + var it2 = ld.iterator() + it2.end(t.error.bind(t)) + }) + + t.ok(require('./').DeferredIterator) +}) + +test('iterator - non deferred operation', function (t) { + t.plan(5) + var seekTarget = false + + var db = { + iterator: function (options) { + return { + next: function (cb) { + cb(null, 'key', 'value') + }, + seek: function (target) { + seekTarget = target + }, + end: function (cb) { + process.nextTick(cb) + } + } + }, + open: function (options, callback) { + process.nextTick(callback) + } + } + var ld = new DeferredLevelDOWN(db) + var it = ld.iterator() + + ld.open(function (err) { + t.error(err, 'no error') + + it.seek('foo') + + t.is(seekTarget, 'foo', 'seek was called with correct target') + + it.next(function (err, key, value) { + t.error(err, 'no error') + t.equal(key, 'key') + t.equal(value, 'value') + }) + }) +}) + +test('iterator - is created in order', function (t) { + t.plan(4) + + function db () { + return { + order: [], + iterator: function (options) { + this.order.push('iterator created') + return {} + }, + put: function (key, value, options, callback) { + this.order.push('put') + }, + open: function (options, callback) { + process.nextTick(callback) + } + } + } + + var ld1 = new DeferredLevelDOWN(db()) + var ld2 = new DeferredLevelDOWN(db()) + + ld1.iterator() + ld1.put('key', 'value', noop) + + ld2.put('key', 'value', noop) + ld2.iterator() + + ld1.open(function (err) { + t.error(err, 'no error') + t.same(ld1._db.order, ['iterator created', 'put']) + }) + + ld2.open(function (err) { + t.error(err, 'no error') + t.same(ld2._db.order, ['put', 'iterator created']) + }) +}) + +test('reachdown supports deferred-leveldown', function (t) { + // Define just enough methods for reachdown to see this as a real db + var db = { open: noop, _batch: noop, _iterator: noop } + var ld = new DeferredLevelDOWN(db) + + t.is(ld.type, 'deferred-leveldown') + t.is(reachdown(ld, 'deferred-leveldown'), ld) + t.is(reachdown(ld), db) + + t.end() +}) diff --git a/nodejs/node_modules/enabled/.travis.yml b/nodejs/node_modules/enabled/.travis.yml new file mode 100644 index 00000000..6b89a86c --- /dev/null +++ b/nodejs/node_modules/enabled/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "10" + - "9" + - "8" +after_script: + - "npm install coveralls@2.11.x && cat coverage/lcov.info | coveralls" +matrix: + fast_finish: true diff --git a/nodejs/node_modules/enabled/LICENSE b/nodejs/node_modules/enabled/LICENSE new file mode 100644 index 00000000..9beaab11 --- /dev/null +++ b/nodejs/node_modules/enabled/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the Contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/enabled/README.md b/nodejs/node_modules/enabled/README.md new file mode 100644 index 00000000..bed6de32 --- /dev/null +++ b/nodejs/node_modules/enabled/README.md @@ -0,0 +1,68 @@ +# enabled + +[![Version npm][version]](http://browsenpm.org/package/enabled)[![Build Status][build]](https://travis-ci.org/3rd-Eden/enabled)[![Dependencies][david]](https://david-dm.org/3rd-Eden/enabled)[![Coverage Status][cover]](https://coveralls.io/r/3rd-Eden/enabled?branch=master) + +[version]: http://img.shields.io/npm/v/enabled.svg?style=flat-square +[build]: http://img.shields.io/travis/3rd-Eden/enabled/master.svg?style=flat-square +[david]: https://img.shields.io/david/3rd-Eden/enabled.svg?style=flat-square +[cover]: http://img.shields.io/coveralls/3rd-Eden/enabled/master.svg?style=flat-square + +Enabled is a small utility that can check if certain namespace are enabled by +environment variables which are automatically transformed to regular expressions +for matching. + +## Installation + +The module is release in the public npm registry and can be used in browsers and +servers as it uses plain ol ES3 to make the magic work. + +``` +npm install --save enabled +``` + +## Usage + +First of all make sure you've required the module using: + +```js +'use strict'; + +var enabled = require('enabled'); +``` + +The returned `enabled` function accepts 2 arguments. + +1. `name` **string**, The namespace that should match. +2. `pattern` **string**, The pattern that the name should satisfy + +It will return a boolean indication of a match. + +#### Examples + +```js +var flag = 'foo'; + +enabled('foo', flag); // true; +enabled('bar', flag); // false; + +// +// Use * for wild cards. +// +var wildcard = 'foob*'; + +enabled('foobar', wildcard); // true; +enabled('barfoo', wildcard); // false; + +// +// Use - to ignore. +// +var ignore = 'foobar,-shizzle,nizzle'; + +enabled('foobar', ignore); // true; +enabled('shizzle-my-nizzle', ignore); // false; +enabled('nizzle', ignore); // true; +``` + +## License + +[MIT](./LICENSE) diff --git a/nodejs/node_modules/enabled/index.js b/nodejs/node_modules/enabled/index.js new file mode 100644 index 00000000..69ee6509 --- /dev/null +++ b/nodejs/node_modules/enabled/index.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * Checks if a given namespace is allowed by the given variable. + * + * @param {String} name namespace that should be included. + * @param {String} variable Value that needs to be tested. + * @returns {Boolean} Indication if namespace is enabled. + * @public + */ +module.exports = function enabled(name, variable) { + if (!variable) return false; + + var variables = variable.split(/[\s,]+/) + , i = 0; + + for (; i < variables.length; i++) { + variable = variables[i].replace('*', '.*?'); + + if ('-' === variable.charAt(0)) { + if ((new RegExp('^'+ variable.substr(1) +'$')).test(name)) { + return false; + } + + continue; + } + + if ((new RegExp('^'+ variable +'$')).test(name)) { + return true; + } + } + + return false; +}; diff --git a/nodejs/node_modules/enabled/package.json b/nodejs/node_modules/enabled/package.json new file mode 100644 index 00000000..17408a6b --- /dev/null +++ b/nodejs/node_modules/enabled/package.json @@ -0,0 +1,33 @@ +{ + "name": "enabled", + "version": "2.0.0", + "description": "Check if a certain debug flag is enabled.", + "main": "index.js", + "scripts": { + "100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100", + "test": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- test.js", + "watch": "mocha --watch test.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/3rd-Eden/enabled.git" + }, + "keywords": [ + "enabled", + "debug", + "diagnostics", + "flag", + "env", + "variable", + "localstorage" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "assume": "2.1.x", + "istanbul": "^0.4.5", + "mocha": "5.2.x", + "pre-commit": "1.2.x" + } +} diff --git a/nodejs/node_modules/enabled/test.js b/nodejs/node_modules/enabled/test.js new file mode 100644 index 00000000..a160b71e --- /dev/null +++ b/nodejs/node_modules/enabled/test.js @@ -0,0 +1,39 @@ +describe('enabled', function () { + 'use strict'; + + var assume = require('assume') + , enabled = require('./'); + + it('supports wildcards', function () { + var variable = 'b*'; + + assume(enabled('bigpipe', variable)).to.be.true(); + assume(enabled('bro-fist', variable)).to.be.true(); + assume(enabled('ro-fist', variable)).to.be.false(); + }); + + it('is disabled by default', function () { + assume(enabled('bigpipe', '')).to.be.false(); + assume(enabled('bigpipe', 'bigpipe')).to.be.true(); + }); + + it('can ignore loggers using a -', function () { + var variable = 'bigpipe,-primus,sack,-other'; + + assume(enabled('bigpipe', variable)).to.be.true(); + assume(enabled('sack', variable)).to.be.true(); + assume(enabled('primus', variable)).to.be.false(); + assume(enabled('other', variable)).to.be.false(); + assume(enabled('unknown', variable)).to.be.false(); + }); + + it('supports multiple ranges', function () { + var variable = 'bigpipe*,primus*'; + + assume(enabled('bigpipe:', variable)).to.be.true(); + assume(enabled('bigpipes', variable)).to.be.true(); + assume(enabled('primus:', variable)).to.be.true(); + assume(enabled('primush', variable)).to.be.true(); + assume(enabled('unknown', variable)).to.be.false(); + }); +}); diff --git a/nodejs/node_modules/encoding-down/.travis.yml b/nodejs/node_modules/encoding-down/.travis.yml new file mode 100644 index 00000000..8e18725a --- /dev/null +++ b/nodejs/node_modules/encoding-down/.travis.yml @@ -0,0 +1,13 @@ +sudo: false + +language: node_js + +node_js: + - 6 + - 8 + - 10 + +after_success: npm run coverage + +notifications: + email: false diff --git a/nodejs/node_modules/encoding-down/CHANGELOG.md b/nodejs/node_modules/encoding-down/CHANGELOG.md new file mode 100644 index 00000000..cda0b1ff --- /dev/null +++ b/nodejs/node_modules/encoding-down/CHANGELOG.md @@ -0,0 +1,394 @@ +# Changelog + +## [6.3.0] - 2019-10-13 + +### Added + +- Add manifest ([Level/community#83](https://github.com/Level/community/issues/83)) and encode `compactRange()` ([#93](https://github.com/Level/encoding-down/issues/93)) ([**@vweevers**](https://github.com/vweevers)) +- Add `type` property for `reachdown` ([Level/community#82](https://github.com/Level/community/issues/82)) ([`8a23848`](https://github.com/Level/encoding-down/commit/8a23848)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.2.0] - 2019-09-06 + +### Changed + +- Upgrade `hallmark` devDependency from `^0.1.0` to `^2.0.0` ([#85](https://github.com/Level/encoding-down/issues/85), [#91](https://github.com/Level/encoding-down/issues/91)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `standard` devDependency from `^12.0.0` to `^14.0.0` ([#84](https://github.com/Level/encoding-down/issues/84), [#90](https://github.com/Level/encoding-down/issues/90)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `memdown` devDependency from `^4.0.0` to `^5.0.0` ([#88](https://github.com/Level/encoding-down/issues/88)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Support `db.clear()` ([#89](https://github.com/Level/encoding-down/issues/89)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.1.0] - 2019-06-22 + +### Changed + +- Upgrade `nyc` devDependency from `^13.2.0` to `^14.0.0` ([#81](https://github.com/Level/encoding-down/issues/81))) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Support seeking ([#82](https://github.com/Level/encoding-down/issues/82), [#83](https://github.com/Level/encoding-down/issues/83)) ([**@MeirionHughes**](https://github.com/MeirionHughes), [**@vweevers**](https://github.com/vweevers)) + +## [6.0.2] - 2019-03-31 + +### Changed + +- Upgrade `memdown` devDependency from `^3.0.0` to `^4.0.0` ([#80](https://github.com/Level/encoding-down/issues/80)) ([**@vweevers**](https://github.com/vweevers)) +- Upgrade `nyc` devDependency from `^12.0.2` to `^13.2.0` ([#79](https://github.com/Level/encoding-down/issues/79)) ([**@vweevers**](https://github.com/vweevers)) +- Apply common project tweaks ([#77](https://github.com/Level/encoding-down/issues/77), [#78](https://github.com/Level/encoding-down/issues/78)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.0.1] - 2018-12-27 + +### Changed + +- Replace `remark-cli` devDependency with `hallmark` ([#76](https://github.com/Level/encoding-down/issues/76)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Increase coverage to 100% ([#75](https://github.com/Level/encoding-down/issues/75)) ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Fix `approximateSize()` to encode `start` and `end` arguments ([#75](https://github.com/Level/encoding-down/issues/75)) ([**@vweevers**](https://github.com/vweevers)) + +## [6.0.0] - 2018-12-25 + +### Changed + +- Prefer `const` over `var` in README ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `abstract-leveldown` dependency from `^5.0.0` to `^v6.0.0` ([#68](https://github.com/Level/encoding-down/issues/68)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `standard` devDependency from `^11.0.0` to `^v12.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Use full link references in README ([#60](https://github.com/Level/encoding-down/issues/60)) ([**@vweevers**](https://github.com/vweevers)) + +### Added + +- Explain serialization ([#72](https://github.com/Level/encoding-down/issues/72)) ([**@vweevers**](https://github.com/vweevers)) +- Add `nyc` and `coveralls` ([#64](https://github.com/Level/encoding-down/issues/64)) ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove node 9 ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Remove now superfluous `_setupIteratorOptions()` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [5.0.4] - 2018-06-22 + +### Added + +- Add `LICENSE.md` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `CONTRIBUTORS.md` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add `remark` tooling ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [5.0.3] - 2018-05-30 + +### Changed + +- Replace `util.inherits` with `inherits` module ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [5.0.2] - 2018-05-23 + +### Added + +- Add `UPGRADING.md` ([**@vweevers**](https://github.com/vweevers)) + +### Changed + +- Upgrade `abstract-leveldown` to `5.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Upgrade `memdown` to `3.0.0` ([**@vweevers**](https://github.com/vweevers)) + +## [5.0.1] - 2018-05-19 + +### Changed + +- Override `_setupIteratorOptions` to not clobber ranges ([**@ralphtheninja**](https://github.com/ralphtheninja), [**@dominictarr**](https://github.com/dominictarr)) + +## [5.0.0] - 2018-05-13 + +### Added + +- Add 10 to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Update `level-errors` to `2.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update `level-codec` to `9.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove 4 from Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [4.0.1] - 2018-05-19 + +### Changed + +- Override `_setupIteratorOptions` to not clobber ranges ([**@ralphtheninja**](https://github.com/ralphtheninja), [**@dominictarr**](https://github.com/dominictarr)) + +## [4.0.0] - 2018-02-12 + +### Added + +- Add 9 to Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Update `abstract-leveldown` to `4.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update `memdown` to `2.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove 7 from Travis ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [3.0.1] - 2017-12-18 + +### Added + +- Test that default utf8 encoding stringifies numbers ([**@vweevers**](https://github.com/vweevers)) + +### Fixed + +- Skip decoding if `options.keys` or `options.values` is false ([**@vweevers**](https://github.com/vweevers)) + +## [3.0.0] - 2017-11-11 + +### Added + +- README: add node badge (>= 4) ([**@vweevers**](https://github.com/vweevers)) + +### Changed + +- Update `abstract-leveldown` to `3.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Removed + +- Remove 0.12 from Travis ([**@vweevers**](https://github.com/vweevers)) + +## [2.3.4] - 2017-10-24 + +### Added + +- README: add example of npm installed encoding ([**@vweevers**](https://github.com/vweevers)) + +## [2.3.3] - 2017-10-22 + +### Changed + +- README: fix `level-codec` links ([**@vweevers**](https://github.com/vweevers)) + +## [2.3.2] - 2017-10-22 + +### Changed + +- README: tweak badges ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- README: add more code examples ([**@vweevers**](https://github.com/vweevers)) +- Update `level-codec` to `8.0.0` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Fixed + +- Fix problems related to missing `asBuffer`, `keyAsBuffer` and `valueAsBuffer` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.3.1] - 2017-10-02 + +### Changed + +- Refactor typings ([**@MeirionHughes**](https://github.com/MeirionHughes)) + +## [2.3.0] - 2017-09-24 + +### Added + +- Add default export ([**@zixia**](https://github.com/zixia)) + +## [2.2.1] - 2017-09-13 + +### Fixed + +- Fix typings ([**@MeirionHughes**](https://github.com/MeirionHughes)) + +## [2.2.0] - 2017-09-12 + +### Added + +- Add Typescript typings ([**@MeirionHughes**](https://github.com/MeirionHughes)) + +### Changed + +- README: `AbstractLevelDOWN` -> `abstract-leveldown` ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update `abstract-leveldown` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.1.5] - 2017-08-18 + +### Added + +- README: add api docs ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Add basic tests ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +### Changed + +- Enable Travis for ci ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Update dependencies ([**@ralphtheninja**](https://github.com/ralphtheninja)) +- Use `safe-buffer` ([**@ralphtheninja**](https://github.com/ralphtheninja)) + +## [2.1.4] - 2017-01-26 + +### Fixed + +- Rename methods to `_serializeKey()` and `_serializeValue()` ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.1.3] - 2017-01-26 + +### Added + +- Add `_encodeKey()` and `_encodeValue()` id functions ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.1.2] - 2017-01-26 + +### Fixed + +- Emit encoding errors in streams too ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.1.1] - 2017-01-26 + +### Fixed + +- Return encoding errors on get ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.1.0] - 2017-01-26 + +### Added + +- Add support for `approximateSize()` ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.8] - 2017-01-26 + +### Removed + +- Remove `Iterator.prototype.seek` ([**@juliangruber**](https://github.com/juliangruber)) + +### Fixed + +- Fix encoding lt/get range options ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.7] - 2017-01-26 + +### Added + +- Add `'utf8'` as default encoding ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.6] - 2017-01-26 + +### Fixed + +- Fix `typof` -> `typeof` bug ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.5] - 2017-01-26 + +### Fixed + +- Fix bug in `iterator._next()` with undefined key or value ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.4] - 2017-01-26 + +### Changed + +- Update `level-codec` for utf8 fixes ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.3] - 2017-01-26 + +### Fixed + +- Fix bug with incorrect db ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.2] - 2017-01-26 + +### Fixed + +- Fix bug with incorrect db and missing new operator ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.1] - 2017-01-26 + +### Fixed + +- Fix bug with `AbstractChainedBatch` inheritance ([**@juliangruber**](https://github.com/juliangruber)) + +## [2.0.0] - 2017-01-26 + +### Changed + +- Version bump ([**@juliangruber**](https://github.com/juliangruber)) + +## 1.0.0 - 2017-01-26 + +:seedling: Initial release. + +[6.3.0]: https://github.com/Level/encoding-down/compare/v6.2.0...v6.3.0 + +[6.2.0]: https://github.com/Level/encoding-down/compare/v6.1.0...v6.2.0 + +[6.1.0]: https://github.com/Level/encoding-down/compare/v6.0.2...v6.1.0 + +[6.0.2]: https://github.com/Level/encoding-down/compare/v6.0.1...v6.0.2 + +[6.0.1]: https://github.com/Level/encoding-down/compare/v6.0.0...v6.0.1 + +[6.0.0]: https://github.com/Level/encoding-down/compare/v5.0.4...v6.0.0 + +[5.0.4]: https://github.com/Level/encoding-down/compare/v5.0.3...v5.0.4 + +[5.0.3]: https://github.com/Level/encoding-down/compare/v5.0.2...v5.0.3 + +[5.0.2]: https://github.com/Level/encoding-down/compare/v5.0.1...v5.0.2 + +[5.0.1]: https://github.com/Level/encoding-down/compare/v5.0.0...v5.0.1 + +[5.0.0]: https://github.com/Level/encoding-down/compare/v4.0.1...v5.0.0 + +[4.0.1]: https://github.com/Level/encoding-down/compare/v4.0.0...v4.0.1 + +[4.0.0]: https://github.com/Level/encoding-down/compare/v3.0.1...v4.0.0 + +[3.0.1]: https://github.com/Level/encoding-down/compare/v3.0.0...v3.0.1 + +[3.0.0]: https://github.com/Level/encoding-down/compare/v2.3.4...v3.0.0 + +[2.3.4]: https://github.com/Level/encoding-down/compare/v2.3.3...v2.3.4 + +[2.3.3]: https://github.com/Level/encoding-down/compare/v2.3.2...v2.3.3 + +[2.3.2]: https://github.com/Level/encoding-down/compare/v2.3.1...v2.3.2 + +[2.3.1]: https://github.com/Level/encoding-down/compare/v2.3.0...v2.3.1 + +[2.3.0]: https://github.com/Level/encoding-down/compare/v2.2.1...v2.3.0 + +[2.2.1]: https://github.com/Level/encoding-down/compare/v2.2.0...v2.2.1 + +[2.2.0]: https://github.com/Level/encoding-down/compare/v2.1.5...v2.2.0 + +[2.1.5]: https://github.com/Level/encoding-down/compare/v2.1.4...v2.1.5 + +[2.1.4]: https://github.com/Level/encoding-down/compare/v2.1.3...v2.1.4 + +[2.1.3]: https://github.com/Level/encoding-down/compare/v2.1.2...v2.1.3 + +[2.1.2]: https://github.com/Level/encoding-down/compare/v2.1.1...v2.1.2 + +[2.1.1]: https://github.com/Level/encoding-down/compare/v2.1.0...v2.1.1 + +[2.1.0]: https://github.com/Level/encoding-down/compare/v2.0.8...v2.1.0 + +[2.0.8]: https://github.com/Level/encoding-down/compare/v2.0.7...v2.0.8 + +[2.0.7]: https://github.com/Level/encoding-down/compare/v2.0.6...v2.0.7 + +[2.0.6]: https://github.com/Level/encoding-down/compare/v2.0.5...v2.0.6 + +[2.0.5]: https://github.com/Level/encoding-down/compare/v2.0.4...v2.0.5 + +[2.0.4]: https://github.com/Level/encoding-down/compare/v2.0.3...v2.0.4 + +[2.0.3]: https://github.com/Level/encoding-down/compare/v2.0.2...v2.0.3 + +[2.0.2]: https://github.com/Level/encoding-down/compare/v2.0.1...v2.0.2 + +[2.0.1]: https://github.com/Level/encoding-down/compare/v2.0.0...v2.0.1 + +[2.0.0]: https://github.com/Level/encoding-down/compare/v1.0.0...v2.0.0 diff --git a/nodejs/node_modules/encoding-down/CONTRIBUTORS.md b/nodejs/node_modules/encoding-down/CONTRIBUTORS.md new file mode 100644 index 00000000..867a9d04 --- /dev/null +++ b/nodejs/node_modules/encoding-down/CONTRIBUTORS.md @@ -0,0 +1,9 @@ +# Contributors + +| Name | GitHub | Social | +| :------------------- | :----------------------------------------------------- | :------------------------------------------------------------ | +| **Lars-Magnus Skog** | [**@ralphtheninja**](https://github.com/ralphtheninja) | [**@ralph@social.weho.st**](https://social.weho.st/@ralph) | +| **Vincent Weevers** | [**@vweevers**](https://github.com/vweevers) | [**@vweevers@twitter**](https://twitter.com/vweevers) | +| **Julian Gruber** | [**@juliangruber**](https://github.com/juliangruber) | [**@juliangruber@twitter**](https://twitter.com/juliangruber) | +| **Meirion Hughes** | [**@MeirionHughes**](https://github.com/MeirionHughes) | | +| **Huan LI** | [**@zixia**](https://github.com/zixia) | [**@zixia@twitter**](https://twitter.com/zixia) | diff --git a/nodejs/node_modules/encoding-down/LICENSE.md b/nodejs/node_modules/encoding-down/LICENSE.md new file mode 100644 index 00000000..1315b2f3 --- /dev/null +++ b/nodejs/node_modules/encoding-down/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +**Copyright © 2012-present [Contributors](CONTRIBUTORS.md).** + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/encoding-down/README.md b/nodejs/node_modules/encoding-down/README.md new file mode 100644 index 00000000..d493b72e --- /dev/null +++ b/nodejs/node_modules/encoding-down/README.md @@ -0,0 +1,205 @@ +# encoding-down + +> An [`abstract-leveldown`][abstract-leveldown] implementation that wraps another store to encode keys and values. + +[![level badge][level-badge]](https://github.com/Level/awesome) +[![npm](https://img.shields.io/npm/v/encoding-down.svg?label=&logo=npm)](https://www.npmjs.com/package/encoding-down) +[![Node version](https://img.shields.io/node/v/encoding-down.svg)](https://www.npmjs.com/package/encoding-down) +[![Travis](https://img.shields.io/travis/Level/com/encoding-down.svg?logo=travis&label=)](https://travis-ci.com/Level/encoding-down) +[![Coverage Status](https://coveralls.io/repos/github/Level/encoding-down/badge.svg)](https://coveralls.io/github/Level/encoding-down) +[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) +[![npm](https://img.shields.io/npm/dm/encoding-down.svg?label=dl)](https://www.npmjs.com/package/encoding-down) +[![Backers on Open Collective](https://opencollective.com/level/backers/badge.svg?color=orange)](#backers) +[![Sponsors on Open Collective](https://opencollective.com/level/sponsors/badge.svg?color=orange)](#sponsors) + +## Introduction + +Stores like [`leveldown`][leveldown] can only store strings and Buffers. Other types, though accepted, are [_serialized_](https://github.com/Level/abstract-leveldown#db_serializekeykey) before storage, which is an irreversible type conversion. For a richer set of data types you can wrap such a store with `encoding-down`. It allows you to specify an _encoding_ to use for keys and values independently. This not only widens the range of input types, but also limits the range of output types. The encoding is applied to all read and write operations: it encodes writes and decodes reads. + +[Many encodings are builtin][builtin-encodings] courtesy of [`level-codec`][level-codec]. The default encoding is `utf8` which ensures you'll always get back a string. You can also provide a custom encoding like `bytewise` - [or your own](#custom-encodings)! + +## Usage + +Without any options, `encoding-down` defaults to the `utf8` encoding. + +```js +var levelup = require('levelup') +var leveldown = require('leveldown') +var encode = require('encoding-down') + +var db = levelup(encode(leveldown('./db1'))) + +db.put('example', Buffer.from('encoding-down'), function (err) { + db.get('example', function (err, value) { + console.log(typeof value, value) // 'string encoding-down' + }) +}) +``` + +Can we store objects? Yes! + +```js +var db = levelup(encode(leveldown('./db2'), { valueEncoding: 'json' })) + +db.put('example', { awesome: true }, function (err) { + db.get('example', function (err, value) { + console.log(value) // { awesome: true } + console.log(typeof value) // 'object' + }) +}) +``` + +How about storing Buffers, but getting back a hex-encoded string? + +```js +var db = levelup(encode(leveldown('./db3'), { valueEncoding: 'hex' })) + +db.put('example', Buffer.from([0, 255]), function (err) { + db.get('example', function (err, value) { + console.log(typeof value, value) // 'string 00ff' + }) +}) +``` + +What if we previously stored binary data? + +```js +var db = levelup(encode(leveldown('./db4'), { valueEncoding: 'binary' })) + +db.put('example', Buffer.from([0, 255]), function (err) { + db.get('example', function (err, value) { + console.log(typeof value, value) // 'object ' + }) + + // Override the encoding for this operation + db.get('example', { valueEncoding: 'base64' }, function (err, value) { + console.log(typeof value, value) // 'string AP8=' + }) +}) +``` + +And what about keys? + +```js +var db = levelup(encode(leveldown('./db5'), { keyEncoding: 'json' })) + +db.put({ awesome: true }, 'example', function (err) { + db.get({ awesome: true }, function (err, value) { + console.log(value) // 'example' + }) +}) +``` + +```js +var db = levelup(encode(leveldown('./db6'), { keyEncoding: 'binary' })) + +db.put(Buffer.from([0, 255]), 'example', function (err) { + db.get('00ff', { keyEncoding: 'hex' }, function (err, value) { + console.log(value) // 'example' + }) +}) +``` + +## Usage with [`level`][level] + +The [`level`][level] module conveniently bundles `encoding-down` and passes its `options` to `encoding-down`. This means you can simply do: + +```js +var level = require('level') +var db = level('./db7', { valueEncoding: 'json' }) + +db.put('example', 42, function (err) { + db.get('example', function (err, value) { + console.log(value) // 42 + console.log(typeof value) // 'number' + }) +}) +``` + +## API + +### `db = require('encoding-down')(db[, options])` + +- `db` must be an [`abstract-leveldown`][abstract-leveldown] compliant store +- `options` are passed to [`level-codec`][level-codec]: + - `keyEncoding`: encoding to use for keys + - `valueEncoding`: encoding to use for values + +Both encodings default to `'utf8'`. They can be a string (builtin `level-codec` encoding) or an object (custom encoding). + +## Custom encodings + +Please refer to [`level-codec` documentation][encoding-format] for a precise description of the format. Here's a quick example with `level` and `async/await` just for fun: + +```js +var level = require('level') +var lexint = require('lexicographic-integer') + +async function main () { + var db = level('./db8', { + keyEncoding: { + type: 'lexicographic-integer', + encode: (n) => lexint.pack(n, 'hex'), + decode: lexint.unpack, + buffer: false + } + }) + + await db.put(2, 'example') + await db.put(10, 'example') + + // Without our encoding, the keys would sort as 10, 2. + db.createKeyStream().on('data', console.log) // 2, 10 +} + +main() +``` + +With an npm-installed encoding (modularity ftw!) we can reduce the above to: + +```js +var level = require('level') +var lexint = require('lexicographic-integer-encoding')('hex') + +var db = level('./db8', { + keyEncoding: lexint +}) +``` + +## Contributing + +[`Level/encoding-down`](https://github.com/Level/encoding-down) is an **OPEN Open Source Project**. This means that: + +> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project. + +See the [Contribution Guide](https://github.com/Level/community/blob/master/CONTRIBUTING.md) for more details. + +## Donate + +To sustain [`Level`](https://github.com/Level) and its activities, become a backer or sponsor on [Open Collective](https://opencollective.com/level). Your logo or avatar will be displayed on our 28+ [GitHub repositories](https://github.com/Level) and [npm](https://www.npmjs.com/) packages. 💖 + +### Backers + +[![Open Collective backers](https://opencollective.com/level/backers.svg?width=890)](https://opencollective.com/level) + +### Sponsors + +[![Open Collective sponsors](https://opencollective.com/level/sponsors.svg?width=890)](https://opencollective.com/level) + +## License + +[MIT](LICENSE.md) © 2012-present [Contributors](CONTRIBUTORS.md). + +[level-badge]: https://leveljs.org/img/badge.svg + +[abstract-leveldown]: https://github.com/Level/abstract-leveldown + +[leveldown]: https://github.com/Level/leveldown + +[level]: https://github.com/Level/level + +[level-codec]: https://github.com/Level/codec + +[builtin-encodings]: https://github.com/Level/codec#builtin-encodings + +[encoding-format]: https://github.com/Level/codec#encoding-format diff --git a/nodejs/node_modules/encoding-down/UPGRADING.md b/nodejs/node_modules/encoding-down/UPGRADING.md new file mode 100644 index 00000000..0d952d52 --- /dev/null +++ b/nodejs/node_modules/encoding-down/UPGRADING.md @@ -0,0 +1,25 @@ +# Upgrade Guide + +This document describes breaking changes and how to upgrade. For a complete list of changes including minor and patch releases, please refer to the [changelog](CHANGELOG.md). + +## v6 + + Upgraded `abstract-leveldown` to `v6.0.0`. Please see the corresponding [changelog entry](https://github.com/Level/abstract-leveldown/blob/master/CHANGELOG.md#600---2018-10-20) for more information. + +## v5 + +Dropped support for node 4. No other breaking changes. + +## v4 + +Dropped support for node 7. + +#### `.batch(array)` enforces objects + +This major release contains an upgrade to `abstract-leveldown` with a [breaking change](https://github.com/Level/abstract-leveldown/commit/a2621ad70571f6ade9d2be42632ece042e068805) for the array version of `.batch()`. This change ensures all elements in the batch array are objects. + +If you previously passed arrays to `.batch()` that contained `undefined` or `null`, they would be silently ignored. Now this will produce an error. + +## v3 + +Dropped support for node 0.12. No other breaking changes. diff --git a/nodejs/node_modules/encoding-down/index.js b/nodejs/node_modules/encoding-down/index.js new file mode 100644 index 00000000..5e031fe6 --- /dev/null +++ b/nodejs/node_modules/encoding-down/index.js @@ -0,0 +1,178 @@ +'use strict' + +var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN +var AbstractChainedBatch = require('abstract-leveldown').AbstractChainedBatch +var AbstractIterator = require('abstract-leveldown').AbstractIterator +var inherits = require('inherits') +var Codec = require('level-codec') +var EncodingError = require('level-errors').EncodingError +var rangeMethods = ['approximateSize', 'compactRange'] + +module.exports = DB.default = DB + +function DB (db, opts) { + if (!(this instanceof DB)) return new DB(db, opts) + + var manifest = db.supports || {} + var additionalMethods = manifest.additionalMethods || {} + + AbstractLevelDOWN.call(this, manifest) + + this.supports.encodings = true + this.supports.additionalMethods = {} + + rangeMethods.forEach(function (m) { + // TODO (future major): remove this fallback + var fallback = typeof db[m] === 'function' + + if (additionalMethods[m] || fallback) { + this.supports.additionalMethods[m] = true + + this[m] = function (start, end, opts, cb) { + start = this.codec.encodeKey(start, opts) + end = this.codec.encodeKey(end, opts) + return this.db[m](start, end, opts, cb) + } + } + }, this) + + opts = opts || {} + if (typeof opts.keyEncoding === 'undefined') opts.keyEncoding = 'utf8' + if (typeof opts.valueEncoding === 'undefined') opts.valueEncoding = 'utf8' + + this.db = db + this.codec = new Codec(opts) +} + +inherits(DB, AbstractLevelDOWN) + +DB.prototype.type = 'encoding-down' + +DB.prototype._serializeKey = +DB.prototype._serializeValue = function (datum) { + return datum +} + +DB.prototype._open = function (opts, cb) { + this.db.open(opts, cb) +} + +DB.prototype._close = function (cb) { + this.db.close(cb) +} + +DB.prototype._put = function (key, value, opts, cb) { + key = this.codec.encodeKey(key, opts) + value = this.codec.encodeValue(value, opts) + this.db.put(key, value, opts, cb) +} + +DB.prototype._get = function (key, opts, cb) { + var self = this + key = this.codec.encodeKey(key, opts) + opts.asBuffer = this.codec.valueAsBuffer(opts) + this.db.get(key, opts, function (err, value) { + if (err) return cb(err) + try { + value = self.codec.decodeValue(value, opts) + } catch (err) { + return cb(new EncodingError(err)) + } + cb(null, value) + }) +} + +DB.prototype._del = function (key, opts, cb) { + key = this.codec.encodeKey(key, opts) + this.db.del(key, opts, cb) +} + +DB.prototype._chainedBatch = function () { + return new Batch(this) +} + +DB.prototype._batch = function (ops, opts, cb) { + ops = this.codec.encodeBatch(ops, opts) + this.db.batch(ops, opts, cb) +} + +DB.prototype._iterator = function (opts) { + opts.keyAsBuffer = this.codec.keyAsBuffer(opts) + opts.valueAsBuffer = this.codec.valueAsBuffer(opts) + return new Iterator(this, opts) +} + +DB.prototype._clear = function (opts, callback) { + opts = this.codec.encodeLtgt(opts) + this.db.clear(opts, callback) +} + +function Iterator (db, opts) { + AbstractIterator.call(this, db) + this.codec = db.codec + this.keys = opts.keys + this.values = opts.values + this.opts = this.codec.encodeLtgt(opts) + this.it = db.db.iterator(this.opts) +} + +inherits(Iterator, AbstractIterator) + +Iterator.prototype._next = function (cb) { + var self = this + this.it.next(function (err, key, value) { + if (err) return cb(err) + try { + if (self.keys && typeof key !== 'undefined') { + key = self.codec.decodeKey(key, self.opts) + } else { + key = undefined + } + + if (self.values && typeof value !== 'undefined') { + value = self.codec.decodeValue(value, self.opts) + } else { + value = undefined + } + } catch (err) { + return cb(new EncodingError(err)) + } + cb(null, key, value) + }) +} + +Iterator.prototype._seek = function (key) { + key = this.codec.encodeKey(key, this.opts) + this.it.seek(key) +} + +Iterator.prototype._end = function (cb) { + this.it.end(cb) +} + +function Batch (db, codec) { + AbstractChainedBatch.call(this, db) + this.codec = db.codec + this.batch = db.db.batch() +} + +inherits(Batch, AbstractChainedBatch) + +Batch.prototype._put = function (key, value) { + key = this.codec.encodeKey(key) + value = this.codec.encodeValue(value) + this.batch.put(key, value) +} + +Batch.prototype._del = function (key) { + key = this.codec.encodeKey(key) + this.batch.del(key) +} + +Batch.prototype._clear = function () { + this.batch.clear() +} + +Batch.prototype._write = function (opts, cb) { + this.batch.write(opts, cb) +} diff --git a/nodejs/node_modules/encoding-down/package.json b/nodejs/node_modules/encoding-down/package.json new file mode 100644 index 00000000..aa6713d6 --- /dev/null +++ b/nodejs/node_modules/encoding-down/package.json @@ -0,0 +1,42 @@ +{ + "name": "encoding-down", + "version": "6.3.0", + "description": "LevelDOWN wrapper supporting levelup@1 encodings", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "standard && hallmark && nyc node test", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "hallmark": "hallmark --fix", + "dependency-check": "dependency-check . test/*.js", + "prepublishOnly": "npm run dependency-check" + }, + "dependencies": { + "abstract-leveldown": "^6.2.1", + "inherits": "^2.0.3", + "level-codec": "^9.0.0", + "level-errors": "^2.0.0" + }, + "devDependencies": { + "coveralls": "^3.0.2", + "dependency-check": "^3.3.0", + "hallmark": "^2.0.0", + "level-community": "^3.0.0", + "memdown": "^5.0.0", + "nyc": "^14.0.0", + "safe-buffer": "^5.1.1", + "standard": "^14.0.0", + "tape": "^4.8.0" + }, + "hallmark": { + "community": "level-community" + }, + "repository": "Level/encoding-down", + "homepage": "https://github.com/Level/encoding-down", + "keywords": [ + "level" + ], + "engines": { + "node": ">=6" + } +} diff --git a/nodejs/node_modules/encoding-down/test/index.js b/nodejs/node_modules/encoding-down/test/index.js new file mode 100644 index 00000000..ba5d0139 --- /dev/null +++ b/nodejs/node_modules/encoding-down/test/index.js @@ -0,0 +1,803 @@ +var test = require('tape') +var encdown = require('..') +var memdown = require('memdown') +var Buffer = require('safe-buffer').Buffer +var hasOwnProperty = Object.prototype.hasOwnProperty +var noop = function () {} + +test('opens and closes the underlying db', function (t) { + var _db = { + open: function (opts, cb) { + t.pass('open called') + setImmediate(cb) + }, + close: function (cb) { + t.pass('close called') + setImmediate(cb) + } + } + var db = encdown(_db) + db.open(function (err) { + t.error(err, 'no error') + db.close(function (err) { + t.error(err, 'no error') + t.end() + }) + }) +}) + +test('encodings default to utf8', function (t) { + var db = encdown(memdown()) + t.ok(db.db, '.db should be set') + t.ok(db.codec, '.codec should be set') + t.deepEqual(db.codec.opts, { + keyEncoding: 'utf8', + valueEncoding: 'utf8' + }, 'correct defaults') + t.end() +}) + +test('default utf8 encoding stringifies numbers', function (t) { + t.plan(3) + + var db = encdown({ + put: function (key, value, callback) { + t.is(key, '1') + t.is(value, '2') + }, + batch: function (ops, options, callback) { + t.same(ops, [{ type: 'put', key: '3', value: '4' }]) + } + }) + + db.put(1, 2, noop) + db.batch([{ type: 'put', key: 3, value: 4 }], noop) +}) + +test('test safe decode in get', function (t) { + var memdb = memdown() + var db = encdown(memdb, { valueEncoding: 'utf8' }) + db.put('foo', 'this {} is [] not : json', function (err) { + t.error(err, 'no error') + var db2 = encdown(memdb, { valueEncoding: 'json' }) + db2.get('foo', function (err, value) { + t.equals('EncodingError', err.name) + memdb.close(t.end.bind(t)) + }) + }) +}) + +test('can decode from string to json', function (t) { + var memdb = memdown() + var db = encdown(memdb, { valueEncoding: 'utf8' }) + var data = { thisis: 'json' } + db.put('foo', JSON.stringify(data), function (err) { + t.error(err, 'no error') + var db2 = encdown(memdb, { valueEncoding: 'json' }) + db2.get('foo', function (err, value) { + t.error(err, 'no error') + t.deepEqual(value, data, 'JSON.parse') + memdb.close(t.end.bind(t)) + }) + }) +}) + +test('can decode from json to string', function (t) { + var memdb = memdown() + var db = encdown(memdb, { valueEncoding: 'json' }) + var data = { thisis: 'json' } + db.put('foo', data, function (err) { + t.error(err, 'no error') + var db2 = encdown(memdb, { valueEncoding: 'utf8' }) + db2.get('foo', function (err, value) { + t.error(err, 'no error') + t.deepEqual(value, JSON.stringify(data), 'JSON.stringify') + memdb.close(t.end.bind(t)) + }) + }) +}) + +test('binary encoding, using batch', function (t) { + var data = [ + { + type: 'put', + key: Buffer.from([1, 2, 3]), + value: Buffer.from([4, 5, 6]) + }, + { + type: 'put', + key: Buffer.from([7, 8, 9]), + value: Buffer.from([10, 11, 12]) + } + ] + var db = encdown(memdown(), { + keyEncoding: 'binary', + valueEncoding: 'binary' + }) + db.batch(data, function (err) { + t.error(err, 'no error') + db.get(data[0].key, function (err, value) { + t.error(err, 'no error') + t.deepEqual(value, data[0].value) + db.get(data[1].key, function (err, value) { + t.error(err, 'no error') + t.deepEqual(value, data[1].value) + db.close(t.end.bind(t)) + }) + }) + }) +}) + +test('default encoding retrieves a string from underlying store', function (t) { + t.plan(1) + + var down = { + get: function (key, options, cb) { + t.is(options.asBuffer, false, '.asBuffer is false') + } + } + + var db = encdown(down) + + db.get('key', noop) +}) + +test('custom value encoding that retrieves a string from underlying store', function (t) { + t.plan(1) + + var down = { + get: function (key, options, cb) { + t.is(options.asBuffer, false, '.asBuffer is false') + } + } + + var db = encdown(down, { + valueEncoding: { + buffer: false + } + }) + + db.get('key', noop) +}) + +test('get() forwards error from underlying store', function (t) { + t.plan(1) + + var down = { + get: function (key, options, cb) { + process.nextTick(cb, new Error('error from store')) + } + } + + encdown(down).get('key', function (err) { + t.is(err.message, 'error from store') + }) +}) + +test('_del() encodes key', function (t) { + t.plan(1) + + var down = { + del: function (key, options, cb) { + t.is(key, '2') + } + } + + encdown(down).del(2, noop) +}) + +test('chainedBatch.put() encodes key and value', function (t) { + t.plan(2) + + var down = { + batch: function () { + return { + put: function (key, value) { + t.is(key, '1') + t.is(value, '2') + } + } + } + } + + encdown(down).batch().put(1, 2) +}) + +test('chainedBatch.del() encodes key', function (t) { + t.plan(1) + + var down = { + batch: function () { + return { + del: function (key) { + t.is(key, '1') + } + } + } + } + + encdown(down).batch().del(1) +}) + +test('chainedBatch.clear() is forwarded to underlying store', function (t) { + t.plan(1) + + var down = { + batch: function () { + return { + clear: function () { + t.pass('called') + } + } + } + } + + encdown(down).batch().clear() +}) + +test('chainedBatch.write() is forwarded to underlying store', function (t) { + t.plan(1) + + var down = { + batch: function () { + return { + write: function () { + t.pass('called') + } + } + } + } + + encdown(down).batch().write(noop) +}) + +test('custom value encoding that retrieves a buffer from underlying store', function (t) { + t.plan(1) + + var down = { + get: function (key, options, cb) { + t.is(options.asBuffer, true, '.asBuffer is true') + } + } + + var db = encdown(down, { + valueEncoding: { + buffer: true + } + }) + + db.get('key', noop) +}) + +test('.keyAsBuffer and .valueAsBuffer defaults to false', function (t) { + t.plan(2) + + var down = { + iterator: function (options) { + t.is(options.keyAsBuffer, false) + t.is(options.valueAsBuffer, false) + } + } + + encdown(down).iterator() +}) + +test('.keyAsBuffer and .valueAsBuffer as buffers if encoding says so', function (t) { + t.plan(2) + + var down = { + iterator: function (options) { + t.is(options.keyAsBuffer, true) + t.is(options.valueAsBuffer, true) + } + } + + var db = encdown(down, { + keyEncoding: { + buffer: true + }, + valueEncoding: { + buffer: true + } + }) + + db.iterator() +}) + +test('.keyAsBuffer and .valueAsBuffer as strings if encoding says so', function (t) { + t.plan(2) + + var down = { + iterator: function (options) { + t.is(options.keyAsBuffer, false) + t.is(options.valueAsBuffer, false) + } + } + + var db = encdown(down, { + keyEncoding: { + buffer: false + }, + valueEncoding: { + buffer: false + } + }) + + db.iterator() +}) + +test('iterator options.keys and options.values default to true', function (t) { + t.plan(2) + + var down = { + iterator: function (options) { + t.is(options.keys, true) + t.is(options.values, true) + } + } + + encdown(down).iterator() +}) + +test('iterator skips keys if options.keys is false', function (t) { + t.plan(4) + + var down = { + iterator: function (options) { + t.is(options.keys, false) + + return { + next: function (callback) { + callback(null, '', 'value') + } + } + } + } + + var keyEncoding = { + decode: function (key) { + t.fail('should not be called') + } + } + + var db = encdown(down, { keyEncoding: keyEncoding }) + var it = db.iterator({ keys: false }) + + it.next(function (err, key, value) { + t.ifError(err, 'no next error') + t.is(key, undefined, 'normalized key to undefined') + t.is(value, 'value', 'got value') + }) +}) + +test('iterator skips values if options.values is false', function (t) { + t.plan(4) + + var down = { + iterator: function (options) { + t.is(options.values, false) + + return { + next: function (callback) { + callback(null, 'key', '') + } + } + } + } + + var valueEncoding = { + decode: function (value) { + t.fail('should not be called') + } + } + + var db = encdown(down, { valueEncoding: valueEncoding }) + var it = db.iterator({ values: false }) + + it.next(function (err, key, value) { + t.ifError(err, 'no next error') + t.is(key, 'key', 'got key') + t.is(value, undefined, 'normalized value to undefined') + }) +}) + +test('iterator encodes range options', function (t) { + t.plan(7) + + var keyEncoding = { + encode: function (key) { + return 'encoded_' + key + }, + buffer: false + } + + var db = encdown({ + iterator: function (options) { + t.is(options.start, 'encoded_1') + t.is(options.end, 'encoded_2') + t.is(options.gt, 'encoded_3') + t.is(options.gte, 'encoded_4') + t.is(options.lt, 'encoded_5') + t.is(options.lte, 'encoded_6') + t.is(options.foo, 7) + } + }, { keyEncoding }) + + db.iterator({ start: 1, end: 2, gt: 3, gte: 4, lt: 5, lte: 6, foo: 7 }) +}) + +test('iterator does not strip nullish range options', function (t) { + t.plan(12) + + encdown({ + iterator: function (options) { + t.is(options.gt, null) + t.is(options.gte, null) + t.is(options.lt, null) + t.is(options.lte, null) + } + }).iterator({ + gt: null, + gte: null, + lt: null, + lte: null + }) + + encdown({ + iterator: function (options) { + t.ok(hasOwnProperty.call(options, 'gt')) + t.ok(hasOwnProperty.call(options, 'gte')) + t.ok(hasOwnProperty.call(options, 'lt')) + t.ok(hasOwnProperty.call(options, 'lte')) + + t.is(options.gt, undefined) + t.is(options.gte, undefined) + t.is(options.lt, undefined) + t.is(options.lte, undefined) + } + }).iterator({ + gt: undefined, + gte: undefined, + lt: undefined, + lte: undefined + }) +}) + +test('iterator does not add nullish range options', function (t) { + t.plan(4) + + encdown({ + iterator: function (options) { + t.notOk(hasOwnProperty.call(options, 'gt')) + t.notOk(hasOwnProperty.call(options, 'gte')) + t.notOk(hasOwnProperty.call(options, 'lt')) + t.notOk(hasOwnProperty.call(options, 'lte')) + } + }).iterator({}) +}) + +test('iterator forwards next() error from underlying iterator', function (t) { + t.plan(1) + + var down = { + iterator: function () { + return { + next: function (callback) { + process.nextTick(callback, new Error('from underlying iterator')) + } + } + } + } + + var db = encdown(down) + var it = db.iterator() + + it.next(function (err, key, value) { + t.is(err.message, 'from underlying iterator') + }) +}) + +test('iterator forwards end() to underlying iterator', function (t) { + t.plan(2) + + var down = { + iterator: function () { + return { + end: function (callback) { + t.pass('called') + process.nextTick(callback) + } + } + } + } + + var db = encdown(down) + var it = db.iterator() + + it.end(function () { + t.pass('called') + }) +}) + +test('iterator catches decoding error from keyEncoding', function (t) { + t.plan(5) + + var down = { + iterator: function () { + return { + next: function (callback) { + process.nextTick(callback, null, 'key', 'value') + } + } + } + } + + var db = encdown(down, { + keyEncoding: { + decode: function (key) { + t.is(key, 'key') + throw new Error('from codec') + } + } + }) + + db.iterator().next(function (err, key, value) { + t.is(err.message, 'from codec') + t.is(err.name, 'EncodingError') + t.is(key, undefined) + t.is(value, undefined) + }) +}) + +test('iterator catches decoding error from valueEncoding', function (t) { + t.plan(5) + + var down = { + iterator: function () { + return { + next: function (callback) { + process.nextTick(callback, null, 'key', 'value') + } + } + } + } + + var db = encdown(down, { + valueEncoding: { + decode: function (value) { + t.is(value, 'value') + throw new Error('from codec') + } + } + }) + + db.iterator().next(function (err, key, value) { + t.is(err.message, 'from codec') + t.is(err.name, 'EncodingError') + t.is(key, undefined) + t.is(value, undefined) + }) +}) + +test('proxies approximateSize() if it exists', function (t) { + t.is(typeof encdown({ approximateSize: noop }).approximateSize, 'function') + t.ok(encdown({ approximateSize: noop }).supports.additionalMethods.approximateSize) + t.is(encdown({}).approximateSize, undefined) + t.notOk(encdown({}).supports.additionalMethods.approximateSize) + t.end() +}) + +test('proxies compactRange() if it exists', function (t) { + t.is(typeof encdown({ compactRange: noop }).compactRange, 'function') + t.ok(encdown({ compactRange: noop }).supports.additionalMethods.compactRange) + t.is(encdown({}).compactRange, undefined) + t.notOk(encdown({}).supports.additionalMethods.compactRange) + t.end() +}) + +test('encodes start and end of approximateSize()', function (t) { + var db = encdown({ + approximateSize: function (start, end) { + t.is(start, '1') + t.is(end, '2') + t.end() + } + }) + + db.approximateSize(1, 2, noop) +}) + +test('encodes start and end of compactRange()', function (t) { + var db = encdown({ + compactRange: function (start, end) { + t.is(start, '1') + t.is(end, '2') + t.end() + } + }) + + db.compactRange(1, 2, noop) +}) + +test('encodes start and end of approximateSize() with custom encoding', function (t) { + var db = encdown({ + approximateSize: function (start, end) { + t.is(start, '"a"') + t.is(end, '"b"') + t.end() + } + }) + + db.approximateSize('a', 'b', { keyEncoding: 'json' }, noop) +}) + +test('encodes start and end of compactRange() with custom encoding', function (t) { + var db = encdown({ + compactRange: function (start, end) { + t.is(start, '"a"') + t.is(end, '"b"') + t.end() + } + }) + + db.compactRange('a', 'b', { keyEncoding: 'json' }, noop) +}) + +test('encodes seek target', function (t) { + t.plan(1) + + var db = encdown({ + iterator: function () { + return { + seek: function (target) { + t.is(target, '123', 'encoded number') + } + } + } + }, { keyEncoding: 'json' }) + + db.iterator().seek(123) +}) + +test('encodes seek target with custom encoding', function (t) { + t.plan(1) + + var targets = [] + var db = encdown({ + iterator: function () { + return { + seek: function (target) { + targets.push(target) + } + } + } + }) + + db.iterator().seek('a') + db.iterator({ keyEncoding: 'json' }).seek('a') + + t.same(targets, ['a', '"a"'], 'encoded targets') +}) + +test('encodes nullish seek target', function (t) { + t.plan(1) + + var targets = [] + var db = encdown({ + iterator: function () { + return { + seek: function (target) { + targets.push(target) + } + } + } + }, { keyEncoding: { encode: String } }) + + // Unlike keys, nullish targets should not be rejected; + // assume that the encoding gives these types meaning. + db.iterator().seek(null) + db.iterator().seek(undefined) + + t.same(targets, ['null', 'undefined'], 'encoded') +}) + +test('clear() forwards default options', function (t) { + t.plan(3) + + var down = { + clear: function (options, callback) { + t.is(options.reverse, false) + t.is(options.limit, -1) + t.is(callback, noop) + } + } + + encdown(down).clear(noop) +}) + +test('clear() forwards error from underlying store', function (t) { + t.plan(1) + + var down = { + clear: function (options, cb) { + process.nextTick(cb, new Error('error from store')) + } + } + + encdown(down).clear(function (err) { + t.is(err.message, 'error from store') + }) +}) + +test('clear() encodes range options', function (t) { + t.plan(5) + + var keyEncoding = { + encode: function (key) { + return 'encoded_' + key + }, + buffer: false + } + + var db = encdown({ + clear: function (options) { + t.is(options.gt, 'encoded_1') + t.is(options.gte, 'encoded_2') + t.is(options.lt, 'encoded_3') + t.is(options.lte, 'encoded_4') + t.is(options.foo, 5) + } + }, { keyEncoding }) + + db.clear({ gt: 1, gte: 2, lt: 3, lte: 4, foo: 5 }, noop) +}) + +test('clear() does not strip nullish range options', function (t) { + t.plan(12) + + encdown({ + clear: function (options) { + t.is(options.gt, null) + t.is(options.gte, null) + t.is(options.lt, null) + t.is(options.lte, null) + } + }).clear({ + gt: null, + gte: null, + lt: null, + lte: null + }, noop) + + encdown({ + clear: function (options) { + t.ok(hasOwnProperty.call(options, 'gt')) + t.ok(hasOwnProperty.call(options, 'gte')) + t.ok(hasOwnProperty.call(options, 'lt')) + t.ok(hasOwnProperty.call(options, 'lte')) + + t.is(options.gt, undefined) + t.is(options.gte, undefined) + t.is(options.lt, undefined) + t.is(options.lte, undefined) + } + }).clear({ + gt: undefined, + gte: undefined, + lt: undefined, + lte: undefined + }, noop) +}) + +test('clear() does not add nullish range options', function (t) { + t.plan(4) + + encdown({ + clear: function (options) { + t.notOk(hasOwnProperty.call(options, 'gt')) + t.notOk(hasOwnProperty.call(options, 'gte')) + t.notOk(hasOwnProperty.call(options, 'lt')) + t.notOk(hasOwnProperty.call(options, 'lte')) + } + }).clear({}, noop) +}) diff --git a/nodejs/node_modules/errno/.jshintrc b/nodejs/node_modules/errno/.jshintrc new file mode 100644 index 00000000..c8ef3ca4 --- /dev/null +++ b/nodejs/node_modules/errno/.jshintrc @@ -0,0 +1,59 @@ +{ + "predef": [ ] + , "bitwise": false + , "camelcase": false + , "curly": false + , "eqeqeq": false + , "forin": false + , "immed": false + , "latedef": false + , "noarg": true + , "noempty": true + , "nonew": true + , "plusplus": false + , "quotmark": true + , "regexp": false + , "undef": true + , "unused": true + , "strict": false + , "trailing": true + , "maxlen": 120 + , "asi": true + , "boss": true + , "debug": true + , "eqnull": true + , "esnext": true + , "evil": true + , "expr": true + , "funcscope": false + , "globalstrict": false + , "iterator": false + , "lastsemic": true + , "laxbreak": true + , "laxcomma": true + , "loopfunc": true + , "multistr": false + , "onecase": false + , "proto": false + , "regexdash": false + , "scripturl": true + , "smarttabs": false + , "shadow": false + , "sub": true + , "supernew": false + , "validthis": true + , "browser": true + , "couch": false + , "devel": false + , "dojo": false + , "mootools": false + , "node": true + , "nonstandard": true + , "prototypejs": false + , "rhino": false + , "worker": true + , "wsh": false + , "nomen": false + , "onevar": false + , "passfail": false +} \ No newline at end of file diff --git a/nodejs/node_modules/errno/.travis.yml b/nodejs/node_modules/errno/.travis.yml new file mode 100644 index 00000000..9c068879 --- /dev/null +++ b/nodejs/node_modules/errno/.travis.yml @@ -0,0 +1,19 @@ +sudo: false + +language: node_js + +node_js: + - 14 + - 12 + - 10 + - 9 + - 8 + - 7 + - 6 + - 5 + - 4 + +arch: + - amd64 + - ppc64le + diff --git a/nodejs/node_modules/errno/README.md b/nodejs/node_modules/errno/README.md new file mode 100644 index 00000000..a4d0fb54 --- /dev/null +++ b/nodejs/node_modules/errno/README.md @@ -0,0 +1,145 @@ +# node-errno + +> Better [libuv](https://github.com/libuv/libuv)/[Node.js](https://nodejs.org)/[io.js](https://iojs.org) error handling & reporting. Available in npm as *errno*. + +[![npm](https://img.shields.io/npm/v/errno.svg)](https://www.npmjs.com/package/errno) +[![Build Status](https://secure.travis-ci.org/rvagg/node-errno.png)](http://travis-ci.org/rvagg/node-errno) +[![npm](https://img.shields.io/npm/dm/errno.svg)](https://www.npmjs.com/package/errno) + +* [errno exposed](#errnoexposed) +* [Custom errors](#customerrors) + + +## errno exposed + +Ever find yourself needing more details about Node.js errors? Me too, so *node-errno* contains the errno mappings direct from libuv so you can use them in your code. + +**By errno:** + +```js +require('errno').errno[3] +// → { +// "errno": 3, +// "code": "EACCES", +// "description": "permission denied" +// } +``` + +**By code:** + +```js +require('errno').code.ENOTEMPTY +// → { +// "errno": 53, +// "code": "ENOTEMPTY", +// "description": "directory not empty" +// } +``` + +**Make your errors more descriptive:** + +```js +var errno = require('errno') + +function errmsg(err) { + var str = 'Error: ' + // if it's a libuv error then get the description from errno + if (errno.errno[err.errno]) + str += errno.errno[err.errno].description + else + str += err.message + + // if it's a `fs` error then it'll have a 'path' property + if (err.path) + str += ' [' + err.path + ']' + + return str +} + +var fs = require('fs') + +fs.readFile('thisisnotarealfile.txt', function (err, data) { + if (err) + console.log(errmsg(err)) +}) +``` + +**Use as a command line tool:** + +``` +~ $ errno 53 +{ + "errno": 53, + "code": "ENOTEMPTY", + "description": "directory not empty" +} +~ $ errno EROFS +{ + "errno": 56, + "code": "EROFS", + "description": "read-only file system" +} +~ $ errno foo +No such errno/code: "foo" +``` + +Supply no arguments for the full list. Error codes are processed case-insensitive. + +You will need to install with `npm install errno -g` if you want the `errno` command to be available without supplying a full path to the node_modules installation. + + +## Custom errors + +Use `errno.custom.createError()` to create custom `Error` objects to throw around in your Node.js library. Create error hierarchies so `instanceof` becomes a useful tool in tracking errors. Call-stack is correctly captured at the time you create an instance of the error object, plus a `cause` property will make available the original error object if you pass one in to the constructor. + +```js +var create = require('errno').custom.createError +var MyError = create('MyError') // inherits from Error +var SpecificError = create('SpecificError', MyError) // inherits from MyError +var OtherError = create('OtherError', MyError) + +// use them! +if (condition) throw new SpecificError('Eeek! Something bad happened') + +if (err) return callback(new OtherError(err)) +``` + +Also available is a `errno.custom.FilesystemError` with in-built access to errno properties: + +```js +fs.readFile('foo', function (err, data) { + if (err) return callback(new errno.custom.FilesystemError(err)) + // do something else +}) +``` + +The resulting error object passed through the callback will have the following properties: `code`, `errno`, `path` and `message` will contain a descriptive human-readable message. + +## Contributors + +* [bahamas10](https://github.com/bahamas10) (Dave Eddy) - Added CLI +* [ralphtheninja](https://github.com/ralphtheninja) (Lars-Magnus Skog) + +## Copyright & Licence + +*Copyright (c) 2012-2015 [Rod Vagg](https://github.com/rvagg) ([@rvagg](https://twitter.com/rvagg))* + +Made available under the MIT licence: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/errno/build.js b/nodejs/node_modules/errno/build.js new file mode 100755 index 00000000..fce89260 --- /dev/null +++ b/nodejs/node_modules/errno/build.js @@ -0,0 +1,43 @@ +#!/usr/bin/env node + +var request = require('request') + , fs = require('fs') + + , uvheadloc = 'https://raw.github.com/joyent/libuv/master/include/uv.h' + , defreg = /^\s*XX\(\s*([\-\d]+),\s*([A-Z]+),\s*"([^"]*)"\s*\)\s*\\?$/ + + +request(uvheadloc, function (err, response) { + if (err) + throw err + + var data, out + + data = response.body + .split('\n') + .map(function (line) { return line.match(defreg) }) + .filter(function (match) { return match }) + .map(function (match) { return { + errno: parseInt(match[1], 10) + , code: match[2] + , description: match[3] + }}) + + out = 'var all = module.exports.all = ' + JSON.stringify(data, 0, 1) + '\n\n' + + out += '\nmodule.exports.errno = {\n ' + + data.map(function (e, i) { + return '\'' + e.errno + '\': all[' + i + ']' + }).join('\n , ') + + '\n}\n\n' + + out += '\nmodule.exports.code = {\n ' + + data.map(function (e, i) { + return '\'' + e.code + '\': all[' + i + ']' + }).join('\n , ') + + '\n}\n\n' + + out += '\nmodule.exports.custom = require("./custom")(module.exports)\n' + + fs.writeFile('errno.js', out) +}) \ No newline at end of file diff --git a/nodejs/node_modules/errno/cli.js b/nodejs/node_modules/errno/cli.js new file mode 100755 index 00000000..61d179bb --- /dev/null +++ b/nodejs/node_modules/errno/cli.js @@ -0,0 +1,22 @@ +#!/usr/bin/env node + +var errno = require('./') + , arg = process.argv[2] + , data, code + +if (arg === undefined) { + console.log(JSON.stringify(errno.code, null, 2)) + process.exit(0) +} + +if ((code = +arg) == arg) + data = errno.errno[code] +else + data = errno.code[arg] || errno.code[arg.toUpperCase()] + +if (data) + console.log(JSON.stringify(data, null, 2)) +else { + console.error('No such errno/code: "' + arg + '"') + process.exit(1) +} diff --git a/nodejs/node_modules/errno/custom.js b/nodejs/node_modules/errno/custom.js new file mode 100644 index 00000000..ca8c1d8d --- /dev/null +++ b/nodejs/node_modules/errno/custom.js @@ -0,0 +1,57 @@ +var prr = require('prr') + +function init (type, message, cause) { + if (!!message && typeof message != 'string') { + message = message.message || message.name + } + prr(this, { + type : type + , name : type + // can be passed just a 'cause' + , cause : typeof message != 'string' ? message : cause + , message : message + }, 'ewr') +} + +// generic prototype, not intended to be actually used - helpful for `instanceof` +function CustomError (message, cause) { + Error.call(this) + if (Error.captureStackTrace) + Error.captureStackTrace(this, this.constructor) + init.call(this, 'CustomError', message, cause) +} + +CustomError.prototype = new Error() + +function createError (errno, type, proto) { + var err = function (message, cause) { + init.call(this, type, message, cause) + //TODO: the specificity here is stupid, errno should be available everywhere + if (type == 'FilesystemError') { + this.code = this.cause.code + this.path = this.cause.path + this.errno = this.cause.errno + this.message = + (errno.errno[this.cause.errno] + ? errno.errno[this.cause.errno].description + : this.cause.message) + + (this.cause.path ? ' [' + this.cause.path + ']' : '') + } + Error.call(this) + if (Error.captureStackTrace) + Error.captureStackTrace(this, err) + } + err.prototype = !!proto ? new proto() : new CustomError() + return err +} + +module.exports = function (errno) { + var ce = function (type, proto) { + return createError(errno, type, proto) + } + return { + CustomError : CustomError + , FilesystemError : ce('FilesystemError') + , createError : ce + } +} diff --git a/nodejs/node_modules/errno/errno.js b/nodejs/node_modules/errno/errno.js new file mode 100644 index 00000000..efb79d41 --- /dev/null +++ b/nodejs/node_modules/errno/errno.js @@ -0,0 +1,313 @@ +var all = module.exports.all = [ + { + errno: -2, + code: 'ENOENT', + description: 'no such file or directory' + }, + { + errno: -1, + code: 'UNKNOWN', + description: 'unknown error' + }, + { + errno: 0, + code: 'OK', + description: 'success' + }, + { + errno: 1, + code: 'EOF', + description: 'end of file' + }, + { + errno: 2, + code: 'EADDRINFO', + description: 'getaddrinfo error' + }, + { + errno: 3, + code: 'EACCES', + description: 'permission denied' + }, + { + errno: 4, + code: 'EAGAIN', + description: 'resource temporarily unavailable' + }, + { + errno: 5, + code: 'EADDRINUSE', + description: 'address already in use' + }, + { + errno: 6, + code: 'EADDRNOTAVAIL', + description: 'address not available' + }, + { + errno: 7, + code: 'EAFNOSUPPORT', + description: 'address family not supported' + }, + { + errno: 8, + code: 'EALREADY', + description: 'connection already in progress' + }, + { + errno: 9, + code: 'EBADF', + description: 'bad file descriptor' + }, + { + errno: 10, + code: 'EBUSY', + description: 'resource busy or locked' + }, + { + errno: 11, + code: 'ECONNABORTED', + description: 'software caused connection abort' + }, + { + errno: 12, + code: 'ECONNREFUSED', + description: 'connection refused' + }, + { + errno: 13, + code: 'ECONNRESET', + description: 'connection reset by peer' + }, + { + errno: 14, + code: 'EDESTADDRREQ', + description: 'destination address required' + }, + { + errno: 15, + code: 'EFAULT', + description: 'bad address in system call argument' + }, + { + errno: 16, + code: 'EHOSTUNREACH', + description: 'host is unreachable' + }, + { + errno: 17, + code: 'EINTR', + description: 'interrupted system call' + }, + { + errno: 18, + code: 'EINVAL', + description: 'invalid argument' + }, + { + errno: 19, + code: 'EISCONN', + description: 'socket is already connected' + }, + { + errno: 20, + code: 'EMFILE', + description: 'too many open files' + }, + { + errno: 21, + code: 'EMSGSIZE', + description: 'message too long' + }, + { + errno: 22, + code: 'ENETDOWN', + description: 'network is down' + }, + { + errno: 23, + code: 'ENETUNREACH', + description: 'network is unreachable' + }, + { + errno: 24, + code: 'ENFILE', + description: 'file table overflow' + }, + { + errno: 25, + code: 'ENOBUFS', + description: 'no buffer space available' + }, + { + errno: 26, + code: 'ENOMEM', + description: 'not enough memory' + }, + { + errno: 27, + code: 'ENOTDIR', + description: 'not a directory' + }, + { + errno: 28, + code: 'EISDIR', + description: 'illegal operation on a directory' + }, + { + errno: 29, + code: 'ENONET', + description: 'machine is not on the network' + }, + { + errno: 31, + code: 'ENOTCONN', + description: 'socket is not connected' + }, + { + errno: 32, + code: 'ENOTSOCK', + description: 'socket operation on non-socket' + }, + { + errno: 33, + code: 'ENOTSUP', + description: 'operation not supported on socket' + }, + { + errno: 34, + code: 'ENOENT', + description: 'no such file or directory' + }, + { + errno: 35, + code: 'ENOSYS', + description: 'function not implemented' + }, + { + errno: 36, + code: 'EPIPE', + description: 'broken pipe' + }, + { + errno: 37, + code: 'EPROTO', + description: 'protocol error' + }, + { + errno: 38, + code: 'EPROTONOSUPPORT', + description: 'protocol not supported' + }, + { + errno: 39, + code: 'EPROTOTYPE', + description: 'protocol wrong type for socket' + }, + { + errno: 40, + code: 'ETIMEDOUT', + description: 'connection timed out' + }, + { + errno: 41, + code: 'ECHARSET', + description: 'invalid Unicode character' + }, + { + errno: 42, + code: 'EAIFAMNOSUPPORT', + description: 'address family for hostname not supported' + }, + { + errno: 44, + code: 'EAISERVICE', + description: 'servname not supported for ai_socktype' + }, + { + errno: 45, + code: 'EAISOCKTYPE', + description: 'ai_socktype not supported' + }, + { + errno: 46, + code: 'ESHUTDOWN', + description: 'cannot send after transport endpoint shutdown' + }, + { + errno: 47, + code: 'EEXIST', + description: 'file already exists' + }, + { + errno: 48, + code: 'ESRCH', + description: 'no such process' + }, + { + errno: 49, + code: 'ENAMETOOLONG', + description: 'name too long' + }, + { + errno: 50, + code: 'EPERM', + description: 'operation not permitted' + }, + { + errno: 51, + code: 'ELOOP', + description: 'too many symbolic links encountered' + }, + { + errno: 52, + code: 'EXDEV', + description: 'cross-device link not permitted' + }, + { + errno: 53, + code: 'ENOTEMPTY', + description: 'directory not empty' + }, + { + errno: 54, + code: 'ENOSPC', + description: 'no space left on device' + }, + { + errno: 55, + code: 'EIO', + description: 'i/o error' + }, + { + errno: 56, + code: 'EROFS', + description: 'read-only file system' + }, + { + errno: 57, + code: 'ENODEV', + description: 'no such device' + }, + { + errno: 58, + code: 'ESPIPE', + description: 'invalid seek' + }, + { + errno: 59, + code: 'ECANCELED', + description: 'operation canceled' + } +] + +module.exports.errno = {} +module.exports.code = {} + +all.forEach(function (error) { + module.exports.errno[error.errno] = error + module.exports.code[error.code] = error +}) + +module.exports.custom = require('./custom')(module.exports) +module.exports.create = module.exports.custom.createError diff --git a/nodejs/node_modules/errno/package.json b/nodejs/node_modules/errno/package.json new file mode 100644 index 00000000..eee3e559 --- /dev/null +++ b/nodejs/node_modules/errno/package.json @@ -0,0 +1,33 @@ +{ + "name": "errno", + "authors": [ + "Rod Vagg @rvagg (https://github.com/rvagg)" + ], + "description": "libuv errno details exposed", + "keywords": [ + "errors", + "errno", + "libuv" + ], + "version": "0.1.8", + "main": "errno.js", + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "./cli.js" + }, + "devDependencies": { + "error-stack-parser": "^2.0.1", + "inherits": "^2.0.3", + "tape": "~4.8.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/rvagg/node-errno.git" + }, + "license": "MIT", + "scripts": { + "test": "node --use_strict test.js" + } +} diff --git a/nodejs/node_modules/errno/test.js b/nodejs/node_modules/errno/test.js new file mode 100644 index 00000000..1c046357 --- /dev/null +++ b/nodejs/node_modules/errno/test.js @@ -0,0 +1,88 @@ +var test = require('tape') + , inherits = require('inherits') + , ErrorStackParser = require('error-stack-parser') + , errno = require('./') + +test('sanity checks', function (t) { + t.ok(errno.all, 'errno.all not found') + t.ok(errno.errno, 'errno.errno not found') + t.ok(errno.code, 'errno.code not found') + + t.equal(errno.all.length, 60, 'found ' + errno.all.length + ', expected 60') + t.equal(errno.errno['-1'], errno.all[1], 'errno -1 not second element') + + t.equal(errno.code['UNKNOWN'], errno.all[1], 'code UNKNOWN not second element') + + t.equal(errno.errno[1], errno.all[3], 'errno 1 not fourth element') + + t.equal(errno.code['EOF'], errno.all[3], 'code EOF not fourth element') + t.end() +}) + +test('custom errors', function (t) { + const Cust = errno.create('FooNotBarError') + const cust = new Cust('foo is not bar') + + t.equal(cust.name, 'FooNotBarError', 'correct custom name') + t.equal(cust.type, 'FooNotBarError', 'correct custom type') + t.equal(cust.message, 'foo is not bar', 'correct custom message') + t.notOk(cust.cause, 'no cause') + t.end() +}) + +test('callstack', function (t) { + const MyError = errno.create('MyError') + + function lastFunction (ErrorType, cb) { + process.nextTick(cb, new ErrorType('oh noes!')) + } + + function secondLastFunction (ErrorType, cb) { + lastFunction(ErrorType, cb) + } + + function testFrames (t) { + return function (err) { + const stack = ErrorStackParser.parse(err) + t.same(stack[0].functionName, 'lastFunction', 'last stack frame ok') + t.same(stack[1].functionName, 'secondLastFunction', 'second last stack frame ok') + t.end() + } + } + + t.test('custom error, default prototype', function (t) { + secondLastFunction(MyError, testFrames(t)) + }) + + t.test('custom error, custom prototype', function (t) { + const MyError2 = errno.create('MyError2', MyError) + secondLastFunction(MyError2, testFrames(t)) + }) + + t.test('custom error, using inheritance', function (t) { + const CustomError = errno.custom.CustomError + + function MyError3 (message, cause) { + CustomError.call(this, message, cause) + } + + inherits(MyError3, CustomError) + + secondLastFunction(MyError3, testFrames(t)) + }) +}) + +test('error without message', function (t) { + const Cust = errno.create('WriteError') + const cust = new Cust({ + code: 22, + message: '', + name: 'QuotaExceededError' + }) + + t.equal(cust.name, 'WriteError', 'correct custom name') + t.equal(cust.type, 'WriteError', 'correct custom type') + t.equal(cust.message, 'QuotaExceededError', 'message is the name') + t.notOk(cust.cause, 'no cause') + t.end() +}) diff --git a/nodejs/node_modules/fecha/LICENSE b/nodejs/node_modules/fecha/LICENSE new file mode 100644 index 00000000..cc9084b0 --- /dev/null +++ b/nodejs/node_modules/fecha/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Taylor Hakes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/nodejs/node_modules/fecha/README.md b/nodejs/node_modules/fecha/README.md new file mode 100644 index 00000000..b128a5a8 --- /dev/null +++ b/nodejs/node_modules/fecha/README.md @@ -0,0 +1,320 @@ +# fecha [![Build Status](https://travis-ci.org/taylorhakes/fecha.svg?branch=master)](https://travis-ci.org/taylorhakes/fecha) + +Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. + +### NPM +``` +npm install fecha --save +``` +### Yarn +``` +yarn add fecha +``` + +### Fecha vs Moment + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FechaMoment
Size (Min. and Gzipped)2.1KBs13.1KBs
Date Parsing
Date Formatting
Date Manipulation
I18n Support
+ +## Use it + +#### Formatting +`format` accepts a Date object (or timestamp) and a string format and returns a formatted string. See below for +available format tokens. + +Note: `format` will throw an error when passed invalid parameters +```js +import { format } from 'fecha'; + +type format = (date: Date, format?: string, i18n?: I18nSettings) => str; + +// Custom formats +format(new Date(2015, 10, 20), 'dddd MMMM Do, YYYY'); // 'Friday November 20th, 2015' +format(new Date(1998, 5, 3, 15, 23, 10, 350), 'YYYY-MM-DD hh:mm:ss.SSS A'); // '1998-06-03 03:23:10.350 PM' + +// Named masks +format(new Date(2015, 10, 20), 'isoDate'); // '2015-11-20' +format(new Date(2015, 10, 20), 'mediumDate'); // 'Nov 20, 2015' +format(new Date(2015, 10, 20, 3, 2, 1), 'isoDateTime'); // '2015-11-20T03:02:01-05:00' +format(new Date(2015, 2, 10, 5, 30, 20), 'shortTime'); // '05:30' + +// Literals +format(new Date(2001, 2, 5, 6, 7, 2, 5), '[on] MM-DD-YYYY [at] HH:mm'); // 'on 03-05-2001 at 06:07' +``` + +#### Parsing +`parse` accepts a Date string and a string format and returns a Date object. See below for available format tokens. + +*NOTE*: `parse` will throw an error when passed invalid string format or missing format. You MUST specify a format. +```js +import { parse } from 'fecha'; + +type parse = (dateStr: string, format: string, i18n?: I18nSettingsOptional) => Date|null; + +// Custom formats +parse('February 3rd, 2014', 'MMMM Do, YYYY'); // new Date(2014, 1, 3) +parse('10-12-10 14:11:12', 'YY-MM-DD HH:mm:ss'); // new Date(2010, 11, 10, 14, 11, 12) + +// Named masks +parse('5/3/98', 'shortDate'); // new Date(1998, 4, 3) +parse('November 4, 2005', 'longDate'); // new Date(2005, 10, 4) +parse('2015-11-20T03:02:01-05:00', 'isoDateTime'); // new Date(2015, 10, 20, 3, 2, 1) + +// Override i18n +parse('4 de octubre de 1983', 'M de MMMM de YYYY', { + monthNames: [ + 'enero', + 'febrero', + 'marzo', + 'abril', + 'mayo', + 'junio', + 'julio', + 'agosto', + 'septiembre', + 'octubre', + 'noviembre', + 'diciembre' + ] +}); // new Date(1983, 9, 4) +``` + +#### i18n Support +```js +import {setGlobalDateI18n} from 'fecha'; + +/* +Default I18n Settings +{ + dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'], + dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + amPm: ['am', 'pm'], + // D is the day of the month, function returns something like... 3rd or 11th + DoFn(dayOfMonth) { + return dayOfMonth + [ 'th', 'st', 'nd', 'rd' ][ dayOfMonth % 10 > 3 ? 0 : (dayOfMonth - dayOfMonth % 10 !== 10) * dayOfMonth % 10 ]; + } +} +*/ + +setGlobalDateI18n({ + dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'], + dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + amPm: ['am', 'pm'], + // D is the day of the month, function returns something like... 3rd or 11th + DoFn: function (D) { + return D + [ 'th', 'st', 'nd', 'rd' ][ D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10 ]; + } +}); + +``` + +#### Custom Named Masks +```js +import { format, setGlobalDateMasks } from 'fecha'; +/* +Default global masks +{ + default: 'ddd MMM DD YYYY HH:mm:ss', + shortDate: 'M/D/YY', + mediumDate: 'MMM D, YYYY', + longDate: 'MMMM D, YYYY', + fullDate: 'dddd, MMMM D, YYYY', + shortTime: 'HH:mm', + mediumTime: 'HH:mm:ss', + longTime: 'HH:mm:ss.SSS' +} +*/ + +// Create a new mask +setGlobalDateMasks({ + myMask: 'HH:mm:ss YY/MM/DD'; +}); + +// Use it +format(new Date(2014, 5, 6, 14, 10, 45), 'myMask'); // '14:10:45 14/06/06' +``` + +### Formatting Tokens + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TokenOutput
MonthM1 2 ... 11 12
MM01 02 ... 11 12
MMMJan Feb ... Nov Dec
MMMMJanuary February ... November December
Day of MonthD1 2 ... 30 31
Do1st 2nd ... 30th 31st
DD01 02 ... 30 31
Day of Weekd0 1 ... 5 6
dddSun Mon ... Fri Sat
ddddSunday Monday ... Friday Saturday
YearYY70 71 ... 29 30
YYYY1970 1971 ... 2029 2030
AM/PMAAM PM
aam pm
HourH0 1 ... 22 23
HH00 01 ... 22 23
h1 2 ... 11 12
hh01 02 ... 11 12
Minutem0 1 ... 58 59
mm00 01 ... 58 59
Seconds0 1 ... 58 59
ss00 01 ... 58 59
Fractional SecondS0 1 ... 8 9
SS0 1 ... 98 99
SSS0 1 ... 998 999
TimezoneZ + -07:00 -06:00 ... +06:00 +07:00 +
ZZ + -0700 -0600 ... +0600 +0700 +
diff --git a/nodejs/node_modules/fecha/dist/fecha.min.js b/nodejs/node_modules/fecha/dist/fecha.min.js new file mode 100644 index 00000000..fc2b2013 --- /dev/null +++ b/nodejs/node_modules/fecha/dist/fecha.min.js @@ -0,0 +1,2 @@ +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.fecha={})}(this,function(t){"use strict";var n=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,e="[^\\s]+",r=/\[([^]*?)\]/gm;function o(t,n){for(var e=[],r=0,o=t.length;r-1?r:null}};function a(t){for(var n=[],e=1;e3?0:(t-t%10!=10?1:0)*t%10]}},m=a({},f),c=function(t){return m=a(m,t)},l=function(t){return t.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},h=function(t,n){for(void 0===n&&(n=2),t=String(t);t.length0?"-":"+")+h(100*Math.floor(Math.abs(n)/60)+Math.abs(n)%60,4)},Z:function(t){var n=t.getTimezoneOffset();return(n>0?"-":"+")+h(Math.floor(Math.abs(n)/60),2)+":"+h(Math.abs(n)%60,2)}},M=function(t){return+t-1},D=[null,"\\d\\d?"],Y=[null,e],y=["isPm",e,function(t,n){var e=t.toLowerCase();return e===n.amPm[0]?0:e===n.amPm[1]?1:null}],p=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(t){var n=(t+"").match(/([+-]|\d\d)/gi);if(n){var e=60*+n[1]+parseInt(n[2],10);return"+"===n[0]?e:-e}return 0}],S={D:["day","\\d\\d?"],DD:["day","\\d\\d"],Do:["day","\\d\\d?"+e,function(t){return parseInt(t,10)}],M:["month","\\d\\d?",M],MM:["month","\\d\\d",M],YY:["year","\\d\\d",function(t){var n=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+t>68?n-1:n)+t)}],h:["hour","\\d\\d?",void 0,"isPm"],hh:["hour","\\d\\d",void 0,"isPm"],H:["hour","\\d\\d?"],HH:["hour","\\d\\d"],m:["minute","\\d\\d?"],mm:["minute","\\d\\d"],s:["second","\\d\\d?"],ss:["second","\\d\\d"],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(t){return 100*+t}],SS:["millisecond","\\d\\d",function(t){return 10*+t}],SSS:["millisecond","\\d{3}"],d:D,dd:D,ddd:Y,dddd:Y,MMM:["month",e,u("monthNamesShort")],MMMM:["month",e,u("monthNames")],a:y,A:y,ZZ:p,Z:p},v={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},H=function(t){return a(v,t)},b=function(t,e,o){if(void 0===e&&(e=v.default),void 0===o&&(o={}),"number"==typeof t&&(t=new Date(t)),"[object Date]"!==Object.prototype.toString.call(t)||isNaN(t.getTime()))throw new Error("Invalid Date pass to format");var u=[];e=(e=v[e]||e).replace(r,function(t,n){return u.push(n),"@@@"});var i=a(a({},m),o);return(e=e.replace(n,function(n){return g[n](t,i)})).replace(/@@@/g,function(){return u.shift()})};function w(t,e,o){if(void 0===o&&(o={}),"string"!=typeof e)throw new Error("Invalid format in fecha parse");if(e=v[e]||e,t.length>1e3)return null;var u={year:(new Date).getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},i=[],d=[],s=e.replace(r,function(t,n){return d.push(l(n)),"@@@"}),f={},c={};s=l(s).replace(n,function(t){var n=S[t],e=n[0],r=n[1],o=n[3];if(f[e])throw new Error("Invalid format. "+e+" specified twice in format");return f[e]=!0,o&&(c[o]=!0),i.push(n),"("+r+")"}),Object.keys(c).forEach(function(t){if(!f[t])throw new Error("Invalid format. "+t+" is required in specified format")}),s=s.replace(/@@@/g,function(){return d.shift()});var h=t.match(new RegExp(s,"i"));if(!h)return null;for(var g,M=a(a({},m),o),D=1;D11||u.month<0||u.day>31||u.day<1||u.hour>23||u.hour<0||u.minute>59||u.minute<0||u.second>59||u.second<0)return null;return g}var P={format:b,parse:w,defaultI18n:f,setGlobalDateI18n:c,setGlobalDateMasks:H};t.assign=a,t.default=P,t.format=b,t.parse=w,t.defaultI18n=f,t.setGlobalDateI18n=c,t.setGlobalDateMasks=H,Object.defineProperty(t,"__esModule",{value:!0})}); +//# sourceMappingURL=fecha.min.js.map diff --git a/nodejs/node_modules/fecha/dist/fecha.min.js.map b/nodejs/node_modules/fecha/dist/fecha.min.js.map new file mode 100644 index 00000000..723f49bb --- /dev/null +++ b/nodejs/node_modules/fecha/dist/fecha.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fecha.min.js","sources":["../src/fecha.ts"],"sourcesContent":["const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\\1?|[aA]|\"[^\"]*\"|'[^']*'/g;\nconst twoDigitsOptional = \"\\\\d\\\\d?\";\nconst twoDigits = \"\\\\d\\\\d\";\nconst threeDigits = \"\\\\d{3}\";\nconst fourDigits = \"\\\\d{4}\";\nconst word = \"[^\\\\s]+\";\nconst literal = /\\[([^]*?)\\]/gm;\n\ntype DateInfo = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n millisecond: number;\n isPm: number | null;\n timezoneOffset: number | null;\n};\n\nexport type I18nSettings = {\n amPm: [string, string];\n dayNames: Days;\n dayNamesShort: Days;\n monthNames: Months;\n monthNamesShort: Months;\n DoFn(dayOfMonth: number): string;\n};\n\nexport type I18nSettingsOptional = Partial;\n\nexport type Days = [string, string, string, string, string, string, string];\nexport type Months = [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string\n];\n\nfunction shorten(arr: T, sLen: number): string[] {\n const newArr: string[] = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\n\nconst monthUpdate = (\n arrName: \"monthNames\" | \"monthNamesShort\" | \"dayNames\" | \"dayNamesShort\"\n) => (v: string, i18n: I18nSettings): number | null => {\n const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());\n const index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n};\n\nexport function assign(a: A): A;\nexport function assign(a: A, b: B): A & B;\nexport function assign(a: A, b: B, c: C): A & B & C;\nexport function assign(a: A, b: B, c: C, d: D): A & B & C & D;\nexport function assign(origObj: any, ...args: any[]): any {\n for (const obj of args) {\n for (const key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\n\nconst dayNames: Days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nconst monthNames: Months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\n\nconst monthNamesShort: Months = shorten(monthNames, 3) as Months;\nconst dayNamesShort: Days = shorten(dayNames, 3) as Days;\n\nconst defaultI18n: I18nSettings = {\n dayNamesShort,\n dayNames,\n monthNamesShort,\n monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn(dayOfMonth: number) {\n return (\n dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][\n dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10\n ]\n );\n }\n};\nlet globalI18n = assign({}, defaultI18n);\nconst setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>\n (globalI18n = assign(globalI18n, i18n));\n\nconst regexEscape = (str: string): string =>\n str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n\nconst pad = (val: string | number, len = 2): string => {\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\n\nconst formatFlags: Record<\n string,\n (dateObj: Date, i18n: I18nSettings) => string\n> = {\n D: (dateObj: Date): string => String(dateObj.getDate()),\n DD: (dateObj: Date): string => pad(dateObj.getDate()),\n Do: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.DoFn(dateObj.getDate()),\n d: (dateObj: Date): string => String(dateObj.getDay()),\n dd: (dateObj: Date): string => pad(dateObj.getDay()),\n ddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNamesShort[dateObj.getDay()],\n dddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNames[dateObj.getDay()],\n M: (dateObj: Date): string => String(dateObj.getMonth() + 1),\n MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),\n MMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNamesShort[dateObj.getMonth()],\n MMMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNames[dateObj.getMonth()],\n YY: (dateObj: Date): string =>\n pad(String(dateObj.getFullYear()), 4).substr(2),\n YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),\n h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),\n hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),\n H: (dateObj: Date): string => String(dateObj.getHours()),\n HH: (dateObj: Date): string => pad(dateObj.getHours()),\n m: (dateObj: Date): string => String(dateObj.getMinutes()),\n mm: (dateObj: Date): string => pad(dateObj.getMinutes()),\n s: (dateObj: Date): string => String(dateObj.getSeconds()),\n ss: (dateObj: Date): string => pad(dateObj.getSeconds()),\n S: (dateObj: Date): string =>\n String(Math.round(dateObj.getMilliseconds() / 100)),\n SS: (dateObj: Date): string =>\n pad(Math.round(dateObj.getMilliseconds() / 10), 2),\n SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),\n a: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],\n A: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase(),\n ZZ(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)\n );\n },\n Z(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2)\n );\n }\n};\n\ntype ParseInfo = [\n keyof DateInfo,\n string,\n ((v: string, i18n: I18nSettings) => number | null)?,\n string?\n];\nconst monthParse = (v: string): number => +v - 1;\nconst emptyDigits: ParseInfo = [null, twoDigitsOptional];\nconst emptyWord: ParseInfo = [null, word];\nconst amPm: ParseInfo = [\n \"isPm\",\n word,\n (v: string, i18n: I18nSettings): number | null => {\n const val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n } else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nconst timezoneOffset: ParseInfo = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n (v: string): number | null => {\n const parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n\n if (parts) {\n const minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n\n return 0;\n }\n];\nconst parseFlags: Record = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n (v: string): number => {\n const now = new Date();\n const cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", (v: string): number => +v * 100],\n SS: [\"millisecond\", twoDigits, (v: string): number => +v * 10],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n\n// Some common format strings\nconst globalMasks: { [key: string]: string } = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nconst setGlobalDateMasks = (masks: {\n [key: string]: string;\n}): { [key: string]: string } => assign(globalMasks, masks);\n\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nconst format = (\n dateObj: Date,\n mask: string = globalMasks[\"default\"],\n i18n: I18nSettingsOptional = {}\n): string => {\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n\n if (\n Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())\n ) {\n throw new Error(\"Invalid Date pass to format\");\n }\n\n mask = globalMasks[mask] || mask;\n\n const literals: string[] = [];\n\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n // Apply formatting rules\n mask = mask.replace(token, $0 =>\n formatFlags[$0](dateObj, combinedI18nSettings)\n );\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, () => literals.shift());\n};\n\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(\n dateStr: string,\n format: string,\n i18n: I18nSettingsOptional = {}\n): Date | null {\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n\n // Default to the beginning of the year.\n const today = new Date();\n const dateInfo: DateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n const parseInfo: ParseInfo[] = [];\n const literals: string[] = [];\n\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n let newFormat = format.replace(literal, ($0, $1) => {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n const specifiedFields: { [field: string]: boolean } = {};\n const requiredFields: { [field: string]: boolean } = {};\n\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, $0 => {\n const info = parseFlags[$0];\n const [field, regex, , requiredField] = info;\n\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(`Invalid format. ${field} specified twice in format`);\n }\n\n specifiedFields[field] = true;\n\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(field => {\n if (!specifiedFields[field]) {\n throw new Error(\n `Invalid format. ${field} is required in specified format`\n );\n }\n });\n\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, () => literals.shift());\n\n // Check if the date string matches the format. If it doesn't return null\n const matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n\n // For each match, call the parser function for that date part\n for (let i = 1; i < matches.length; i++) {\n const [field, , parser] = parseInfo[i - 1];\n const value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n\n dateInfo[field] = value;\n }\n\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n\n let dateTZ: Date;\n if (dateInfo.timezoneOffset == null) {\n dateTZ = new Date(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute,\n dateInfo.second,\n dateInfo.millisecond\n );\n const validateFields: [\n \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\",\n \"getMonth\" | \"getDate\" | \"getHours\" | \"getMinutes\" | \"getSeconds\"\n ][] = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (let i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (\n specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()\n ) {\n return null;\n }\n }\n } else {\n dateTZ = new Date(\n Date.UTC(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute - dateInfo.timezoneOffset,\n dateInfo.second,\n dateInfo.millisecond\n )\n );\n\n // We can't validate dates in another timezone unfortunately. Do a basic check instead\n if (\n dateInfo.month > 11 ||\n dateInfo.month < 0 ||\n dateInfo.day > 31 ||\n dateInfo.day < 1 ||\n dateInfo.hour > 23 ||\n dateInfo.hour < 0 ||\n dateInfo.minute > 59 ||\n dateInfo.minute < 0 ||\n dateInfo.second > 59 ||\n dateInfo.second < 0\n ) {\n return null;\n }\n }\n\n // Don't allow invalid dates\n\n return dateTZ;\n}\nexport default {\n format,\n parse,\n defaultI18n,\n setGlobalDateI18n,\n setGlobalDateMasks\n};\nexport { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n"],"names":["token","word","literal","shorten","arr","sLen","newArr","i","len","length","push","substr","monthUpdate","arrName","v","i18n","index","map","toLowerCase","indexOf","assign","origObj","_i","args","args_1","_a","obj","key","dayNames","monthNames","monthNamesShort","defaultI18n","dayNamesShort","amPm","DoFn","dayOfMonth","globalI18n","setGlobalDateI18n","regexEscape","str","replace","pad","val","String","formatFlags","D","dateObj","getDate","DD","Do","d","getDay","dd","ddd","dddd","M","getMonth","MM","MMM","MMMM","YY","getFullYear","YYYY","h","getHours","hh","H","HH","m","getMinutes","mm","s","getSeconds","ss","S","Math","round","getMilliseconds","SS","SSS","a","A","toUpperCase","ZZ","offset","getTimezoneOffset","floor","abs","Z","monthParse","emptyDigits","emptyWord","timezoneOffset","parts","match","minutes","parseInt","parseFlags","cent","Date","undefined","globalMasks","default","shortDate","mediumDate","longDate","fullDate","isoDate","isoDateTime","shortTime","mediumTime","longTime","setGlobalDateMasks","masks","format","mask","Object","prototype","toString","call","isNaN","getTime","Error","literals","$0","$1","combinedI18nSettings","shift","parse","dateStr","dateInfo","year","month","day","hour","minute","second","millisecond","isPm","parseInfo","newFormat","specifiedFields","requiredFields","info","field","regex","requiredField","keys","forEach","matches","RegExp","dateTZ","parser","value","validateFields","UTC"],"mappings":"wLAAA,IAAMA,EAAQ,6EAKRC,EAAO,UACPC,EAAU,gBAyChB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X,OAAOe,SAGPrC,SACAc,QACAjG,cACAM,oBACA2E"} \ No newline at end of file diff --git a/nodejs/node_modules/fecha/lib/fecha.d.ts b/nodejs/node_modules/fecha/lib/fecha.d.ts new file mode 100644 index 00000000..47404a05 --- /dev/null +++ b/nodejs/node_modules/fecha/lib/fecha.d.ts @@ -0,0 +1,52 @@ +export declare type I18nSettings = { + amPm: [string, string]; + dayNames: Days; + dayNamesShort: Days; + monthNames: Months; + monthNamesShort: Months; + DoFn(dayOfMonth: number): string; +}; +export declare type I18nSettingsOptional = Partial; +export declare type Days = [string, string, string, string, string, string, string]; +export declare type Months = [string, string, string, string, string, string, string, string, string, string, string, string]; +export declare function assign(a: A): A; +export declare function assign(a: A, b: B): A & B; +export declare function assign(a: A, b: B, c: C): A & B & C; +export declare function assign(a: A, b: B, c: C, d: D): A & B & C & D; +declare const defaultI18n: I18nSettings; +declare const setGlobalDateI18n: (i18n: I18nSettingsOptional) => I18nSettings; +declare const setGlobalDateMasks: (masks: { + [key: string]: string; +}) => { + [key: string]: string; +}; +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +declare const format: (dateObj: Date, mask?: string, i18n?: I18nSettingsOptional) => string; +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +declare function parse(dateStr: string, format: string, i18n?: I18nSettingsOptional): Date | null; +declare const _default: { + format: (dateObj: Date, mask?: string, i18n?: Partial) => string; + parse: typeof parse; + defaultI18n: I18nSettings; + setGlobalDateI18n: (i18n: Partial) => I18nSettings; + setGlobalDateMasks: (masks: { + [key: string]: string; + }) => { + [key: string]: string; + }; +}; +export default _default; +export { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; diff --git a/nodejs/node_modules/fecha/lib/fecha.js b/nodejs/node_modules/fecha/lib/fecha.js new file mode 100644 index 00000000..db931096 --- /dev/null +++ b/nodejs/node_modules/fecha/lib/fecha.js @@ -0,0 +1,403 @@ +var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; +var twoDigitsOptional = "\\d\\d?"; +var twoDigits = "\\d\\d"; +var threeDigits = "\\d{3}"; +var fourDigits = "\\d{4}"; +var word = "[^\\s]+"; +var literal = /\[([^]*?)\]/gm; +function shorten(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; +} +var monthUpdate = function (arrName) { return function (v, i18n) { + var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); }); + var index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; +}; }; +function assign(origObj) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var obj = args_1[_a]; + for (var key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; +} +var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" +]; +var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; +var monthNamesShort = shorten(monthNames, 3); +var dayNamesShort = shorten(dayNames, 3); +var defaultI18n = { + dayNamesShort: dayNamesShort, + dayNames: dayNames, + monthNamesShort: monthNamesShort, + monthNames: monthNames, + amPm: ["am", "pm"], + DoFn: function (dayOfMonth) { + return (dayOfMonth + + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]); + } +}; +var globalI18n = assign({}, defaultI18n); +var setGlobalDateI18n = function (i18n) { + return (globalI18n = assign(globalI18n, i18n)); +}; +var regexEscape = function (str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); +}; +var pad = function (val, len) { + if (len === void 0) { len = 2; } + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; +}; +var formatFlags = { + D: function (dateObj) { return String(dateObj.getDate()); }, + DD: function (dateObj) { return pad(dateObj.getDate()); }, + Do: function (dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function (dateObj) { return String(dateObj.getDay()); }, + dd: function (dateObj) { return pad(dateObj.getDay()); }, + ddd: function (dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function (dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function (dateObj) { return String(dateObj.getMonth() + 1); }, + MM: function (dateObj) { return pad(dateObj.getMonth() + 1); }, + MMM: function (dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function (dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function (dateObj) { + return pad(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); }, + h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); }, + hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); }, + H: function (dateObj) { return String(dateObj.getHours()); }, + HH: function (dateObj) { return pad(dateObj.getHours()); }, + m: function (dateObj) { return String(dateObj.getMinutes()); }, + mm: function (dateObj) { return pad(dateObj.getMinutes()); }, + s: function (dateObj) { return String(dateObj.getSeconds()); }, + ss: function (dateObj) { return pad(dateObj.getSeconds()); }, + S: function (dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function (dateObj) { + return pad(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); }, + a: function (dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function (dateObj, i18n) { + return dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(); + }, + ZZ: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)); + }, + Z: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2)); + } +}; +var monthParse = function (v) { return +v - 1; }; +var emptyDigits = [null, twoDigitsOptional]; +var emptyWord = [null, word]; +var amPm = [ + "isPm", + word, + function (v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } + else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } +]; +var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function (v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } +]; +var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function (v) { + var now = new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function (v) { return +v * 100; }], + SS: ["millisecond", twoDigits, function (v) { return +v * 10; }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset +}; +// Some common format strings +var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; +var setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); }; +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +var format = function (dateObj, mask, i18n) { + if (mask === void 0) { mask = globalMasks["default"]; } + if (i18n === void 0) { i18n = {}; } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function ($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // Apply formatting rules + mask = mask.replace(token, function ($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, function () { return literals.shift(); }); +}; +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +function parse(dateStr, format, i18n) { + if (i18n === void 0) { i18n = {}; } + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + // Default to the beginning of the year. + var today = new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + var newFormat = format.replace(literal, function ($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, function ($0) { + var info = parseFlags[$0]; + var field = info[0], regex = info[1], requiredField = info[3]; + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error("Invalid format. " + field + " specified twice in format"); + } + specifiedFields[field] = true; + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + parseInfo.push(info); + return "(" + regex + ")"; + }); + // Check all the required fields are present + Object.keys(requiredFields).forEach(function (field) { + if (!specifiedFields[field]) { + throw new Error("Invalid format. " + field + " is required in specified format"); + } + }); + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); }); + // Check if the date string matches the format. If it doesn't return null + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // For each match, call the parser function for that date part + for (var i = 1; i < matches.length; i++) { + var _a = parseInfo[i - 1], field = _a[0], parser = _a[2]; + var value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + dateInfo[field] = value; + } + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } + else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + var dateTZ; + if (dateInfo.timezoneOffset == null) { + dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if (specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) { + return null; + } + } + } + else { + dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); + // We can't validate dates in another timezone unfortunately. Do a basic check instead + if (dateInfo.month > 11 || + dateInfo.month < 0 || + dateInfo.day > 31 || + dateInfo.day < 1 || + dateInfo.hour > 23 || + dateInfo.hour < 0 || + dateInfo.minute > 59 || + dateInfo.minute < 0 || + dateInfo.second > 59 || + dateInfo.second < 0) { + return null; + } + } + // Don't allow invalid dates + return dateTZ; +} +var fecha = { + format: format, + parse: parse, + defaultI18n: defaultI18n, + setGlobalDateI18n: setGlobalDateI18n, + setGlobalDateMasks: setGlobalDateMasks +}; + +export default fecha; +export { assign, format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; +//# sourceMappingURL=fecha.js.map diff --git a/nodejs/node_modules/fecha/lib/fecha.js.map b/nodejs/node_modules/fecha/lib/fecha.js.map new file mode 100644 index 00000000..d61aa715 --- /dev/null +++ b/nodejs/node_modules/fecha/lib/fecha.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fecha.js","sources":["../src/fecha.ts"],"sourcesContent":["const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\\1?|[aA]|\"[^\"]*\"|'[^']*'/g;\nconst twoDigitsOptional = \"\\\\d\\\\d?\";\nconst twoDigits = \"\\\\d\\\\d\";\nconst threeDigits = \"\\\\d{3}\";\nconst fourDigits = \"\\\\d{4}\";\nconst word = \"[^\\\\s]+\";\nconst literal = /\\[([^]*?)\\]/gm;\n\ntype DateInfo = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n millisecond: number;\n isPm: number | null;\n timezoneOffset: number | null;\n};\n\nexport type I18nSettings = {\n amPm: [string, string];\n dayNames: Days;\n dayNamesShort: Days;\n monthNames: Months;\n monthNamesShort: Months;\n DoFn(dayOfMonth: number): string;\n};\n\nexport type I18nSettingsOptional = Partial;\n\nexport type Days = [string, string, string, string, string, string, string];\nexport type Months = [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string\n];\n\nfunction shorten(arr: T, sLen: number): string[] {\n const newArr: string[] = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\n\nconst monthUpdate = (\n arrName: \"monthNames\" | \"monthNamesShort\" | \"dayNames\" | \"dayNamesShort\"\n) => (v: string, i18n: I18nSettings): number | null => {\n const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());\n const index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n};\n\nexport function assign(a: A): A;\nexport function assign(a: A, b: B): A & B;\nexport function assign(a: A, b: B, c: C): A & B & C;\nexport function assign(a: A, b: B, c: C, d: D): A & B & C & D;\nexport function assign(origObj: any, ...args: any[]): any {\n for (const obj of args) {\n for (const key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\n\nconst dayNames: Days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nconst monthNames: Months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\n\nconst monthNamesShort: Months = shorten(monthNames, 3) as Months;\nconst dayNamesShort: Days = shorten(dayNames, 3) as Days;\n\nconst defaultI18n: I18nSettings = {\n dayNamesShort,\n dayNames,\n monthNamesShort,\n monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn(dayOfMonth: number) {\n return (\n dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][\n dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10\n ]\n );\n }\n};\nlet globalI18n = assign({}, defaultI18n);\nconst setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>\n (globalI18n = assign(globalI18n, i18n));\n\nconst regexEscape = (str: string): string =>\n str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n\nconst pad = (val: string | number, len = 2): string => {\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\n\nconst formatFlags: Record<\n string,\n (dateObj: Date, i18n: I18nSettings) => string\n> = {\n D: (dateObj: Date): string => String(dateObj.getDate()),\n DD: (dateObj: Date): string => pad(dateObj.getDate()),\n Do: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.DoFn(dateObj.getDate()),\n d: (dateObj: Date): string => String(dateObj.getDay()),\n dd: (dateObj: Date): string => pad(dateObj.getDay()),\n ddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNamesShort[dateObj.getDay()],\n dddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNames[dateObj.getDay()],\n M: (dateObj: Date): string => String(dateObj.getMonth() + 1),\n MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),\n MMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNamesShort[dateObj.getMonth()],\n MMMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNames[dateObj.getMonth()],\n YY: (dateObj: Date): string =>\n pad(String(dateObj.getFullYear()), 4).substr(2),\n YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),\n h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),\n hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),\n H: (dateObj: Date): string => String(dateObj.getHours()),\n HH: (dateObj: Date): string => pad(dateObj.getHours()),\n m: (dateObj: Date): string => String(dateObj.getMinutes()),\n mm: (dateObj: Date): string => pad(dateObj.getMinutes()),\n s: (dateObj: Date): string => String(dateObj.getSeconds()),\n ss: (dateObj: Date): string => pad(dateObj.getSeconds()),\n S: (dateObj: Date): string =>\n String(Math.round(dateObj.getMilliseconds() / 100)),\n SS: (dateObj: Date): string =>\n pad(Math.round(dateObj.getMilliseconds() / 10), 2),\n SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),\n a: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],\n A: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase(),\n ZZ(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)\n );\n },\n Z(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2)\n );\n }\n};\n\ntype ParseInfo = [\n keyof DateInfo,\n string,\n ((v: string, i18n: I18nSettings) => number | null)?,\n string?\n];\nconst monthParse = (v: string): number => +v - 1;\nconst emptyDigits: ParseInfo = [null, twoDigitsOptional];\nconst emptyWord: ParseInfo = [null, word];\nconst amPm: ParseInfo = [\n \"isPm\",\n word,\n (v: string, i18n: I18nSettings): number | null => {\n const val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n } else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nconst timezoneOffset: ParseInfo = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n (v: string): number | null => {\n const parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n\n if (parts) {\n const minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n\n return 0;\n }\n];\nconst parseFlags: Record = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n (v: string): number => {\n const now = new Date();\n const cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", (v: string): number => +v * 100],\n SS: [\"millisecond\", twoDigits, (v: string): number => +v * 10],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n\n// Some common format strings\nconst globalMasks: { [key: string]: string } = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nconst setGlobalDateMasks = (masks: {\n [key: string]: string;\n}): { [key: string]: string } => assign(globalMasks, masks);\n\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nconst format = (\n dateObj: Date,\n mask: string = globalMasks[\"default\"],\n i18n: I18nSettingsOptional = {}\n): string => {\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n\n if (\n Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())\n ) {\n throw new Error(\"Invalid Date pass to format\");\n }\n\n mask = globalMasks[mask] || mask;\n\n const literals: string[] = [];\n\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n // Apply formatting rules\n mask = mask.replace(token, $0 =>\n formatFlags[$0](dateObj, combinedI18nSettings)\n );\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, () => literals.shift());\n};\n\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(\n dateStr: string,\n format: string,\n i18n: I18nSettingsOptional = {}\n): Date | null {\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n\n // Default to the beginning of the year.\n const today = new Date();\n const dateInfo: DateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n const parseInfo: ParseInfo[] = [];\n const literals: string[] = [];\n\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n let newFormat = format.replace(literal, ($0, $1) => {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n const specifiedFields: { [field: string]: boolean } = {};\n const requiredFields: { [field: string]: boolean } = {};\n\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, $0 => {\n const info = parseFlags[$0];\n const [field, regex, , requiredField] = info;\n\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(`Invalid format. ${field} specified twice in format`);\n }\n\n specifiedFields[field] = true;\n\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(field => {\n if (!specifiedFields[field]) {\n throw new Error(\n `Invalid format. ${field} is required in specified format`\n );\n }\n });\n\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, () => literals.shift());\n\n // Check if the date string matches the format. If it doesn't return null\n const matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n\n // For each match, call the parser function for that date part\n for (let i = 1; i < matches.length; i++) {\n const [field, , parser] = parseInfo[i - 1];\n const value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n\n dateInfo[field] = value;\n }\n\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n\n let dateTZ: Date;\n if (dateInfo.timezoneOffset == null) {\n dateTZ = new Date(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute,\n dateInfo.second,\n dateInfo.millisecond\n );\n const validateFields: [\n \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\",\n \"getMonth\" | \"getDate\" | \"getHours\" | \"getMinutes\" | \"getSeconds\"\n ][] = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (let i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (\n specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()\n ) {\n return null;\n }\n }\n } else {\n dateTZ = new Date(\n Date.UTC(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute - dateInfo.timezoneOffset,\n dateInfo.second,\n dateInfo.millisecond\n )\n );\n\n // We can't validate dates in another timezone unfortunately. Do a basic check instead\n if (\n dateInfo.month > 11 ||\n dateInfo.month < 0 ||\n dateInfo.day > 31 ||\n dateInfo.day < 1 ||\n dateInfo.hour > 23 ||\n dateInfo.hour < 0 ||\n dateInfo.minute > 59 ||\n dateInfo.minute < 0 ||\n dateInfo.second > 59 ||\n dateInfo.second < 0\n ) {\n return null;\n }\n }\n\n // Don't allow invalid dates\n\n return dateTZ;\n}\nexport default {\n format,\n parse,\n defaultI18n,\n setGlobalDateI18n,\n setGlobalDateMasks\n};\nexport { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n"],"names":[],"mappings":"AAAA,IAAM,KAAK,GAAG,4EAA4E,CAAC;AAC3F,IAAM,iBAAiB,GAAG,SAAS,CAAC;AACpC,IAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,IAAM,WAAW,GAAG,QAAQ,CAAC;AAC7B,IAAM,UAAU,GAAG,QAAQ,CAAC;AAC5B,IAAM,IAAI,GAAG,SAAS,CAAC;AACvB,IAAM,OAAO,GAAG,eAAe,CAAC;AAyChC,SAAS,OAAO,CAAqB,GAAM,EAAE,IAAY;IACvD,IAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC9C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;KACrC;IACD,OAAO,MAAM,CAAC;CACf;AAED,IAAM,WAAW,GAAG,UAClB,OAAwE,IACrE,OAAA,UAAC,CAAS,EAAE,IAAkB;IACjC,IAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE,GAAA,CAAC,CAAC;IAC7D,IAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;IACpD,IAAI,KAAK,GAAG,CAAC,CAAC,EAAE;QACd,OAAO,KAAK,CAAC;KACd;IACD,OAAO,IAAI,CAAC;CACb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CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EACjE;gBACA,OAAO,IAAI,CAAC;aACb;SACF;KACF;SAAM;QACL,MAAM,GAAG,IAAI,IAAI,CACf,IAAI,CAAC,GAAG,CACN,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,KAAK,EACd,QAAQ,CAAC,GAAG,EACZ,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,cAAc,EACzC,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,WAAW,CACrB,CACF,CAAC;;QAGF,IACE,QAAQ,CAAC,KAAK,GAAG,EAAE;YACnB,QAAQ,CAAC,KAAK,GAAG,CAAC;YAClB,QAAQ,CAAC,GAAG,GAAG,EAAE;YACjB,QAAQ,CAAC,GAAG,GAAG,CAAC;YAChB,QAAQ,CAAC,IAAI,GAAG,EAAE;YAClB,QAAQ,CAAC,IAAI,GAAG,CAAC;YACjB,QAAQ,CAAC,MAAM,GAAG,EAAE;YACpB,QAAQ,CAAC,MAAM,GAAG,CAAC;YACnB,QAAQ,CAAC,MAAM,GAAG,EAAE;YACpB,QAAQ,CAAC,MAAM,GAAG,CAAC,EACnB;YACA,OAAO,IAAI,CAAC;SACb;KACF;;IAID,OAAO,MAAM,CAAC;CACf;AACD,YAAe;IACb,MAAM,QAAA;IACN,KAAK,OAAA;IACL,WAAW,aAAA;IACX,iBAAiB,mBAAA;IACjB,kBAAkB,oBAAA;CACnB,CAAC;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/fecha/lib/fecha.umd.js b/nodejs/node_modules/fecha/lib/fecha.umd.js new file mode 100644 index 00000000..b61a0f66 --- /dev/null +++ b/nodejs/node_modules/fecha/lib/fecha.umd.js @@ -0,0 +1,418 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.fecha = {}))); +}(this, (function (exports) { 'use strict'; + + var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; + var twoDigitsOptional = "\\d\\d?"; + var twoDigits = "\\d\\d"; + var threeDigits = "\\d{3}"; + var fourDigits = "\\d{4}"; + var word = "[^\\s]+"; + var literal = /\[([^]*?)\]/gm; + function shorten(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; + } + var monthUpdate = function (arrName) { return function (v, i18n) { + var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); }); + var index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; + }; }; + function assign(origObj) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var obj = args_1[_a]; + for (var key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; + } + var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ]; + var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ]; + var monthNamesShort = shorten(monthNames, 3); + var dayNamesShort = shorten(dayNames, 3); + var defaultI18n = { + dayNamesShort: dayNamesShort, + dayNames: dayNames, + monthNamesShort: monthNamesShort, + monthNames: monthNames, + amPm: ["am", "pm"], + DoFn: function (dayOfMonth) { + return (dayOfMonth + + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]); + } + }; + var globalI18n = assign({}, defaultI18n); + var setGlobalDateI18n = function (i18n) { + return (globalI18n = assign(globalI18n, i18n)); + }; + var regexEscape = function (str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); + }; + var pad = function (val, len) { + if (len === void 0) { len = 2; } + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; + }; + var formatFlags = { + D: function (dateObj) { return String(dateObj.getDate()); }, + DD: function (dateObj) { return pad(dateObj.getDate()); }, + Do: function (dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function (dateObj) { return String(dateObj.getDay()); }, + dd: function (dateObj) { return pad(dateObj.getDay()); }, + ddd: function (dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function (dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function (dateObj) { return String(dateObj.getMonth() + 1); }, + MM: function (dateObj) { return pad(dateObj.getMonth() + 1); }, + MMM: function (dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function (dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function (dateObj) { + return pad(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); }, + h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); }, + hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); }, + H: function (dateObj) { return String(dateObj.getHours()); }, + HH: function (dateObj) { return pad(dateObj.getHours()); }, + m: function (dateObj) { return String(dateObj.getMinutes()); }, + mm: function (dateObj) { return pad(dateObj.getMinutes()); }, + s: function (dateObj) { return String(dateObj.getSeconds()); }, + ss: function (dateObj) { return pad(dateObj.getSeconds()); }, + S: function (dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function (dateObj) { + return pad(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); }, + a: function (dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function (dateObj, i18n) { + return dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(); + }, + ZZ: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)); + }, + Z: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2)); + } + }; + var monthParse = function (v) { return +v - 1; }; + var emptyDigits = [null, twoDigitsOptional]; + var emptyWord = [null, word]; + var amPm = [ + "isPm", + word, + function (v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } + else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } + ]; + var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function (v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } + ]; + var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function (v) { + var now = new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function (v) { return +v * 100; }], + SS: ["millisecond", twoDigits, function (v) { return +v * 10; }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset + }; + // Some common format strings + var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" + }; + var setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); }; + /*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ + var format = function (dateObj, mask, i18n) { + if (mask === void 0) { mask = globalMasks["default"]; } + if (i18n === void 0) { i18n = {}; } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function ($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // Apply formatting rules + mask = mask.replace(token, function ($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, function () { return literals.shift(); }); + }; + /** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ + function parse(dateStr, format, i18n) { + if (i18n === void 0) { i18n = {}; } + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + // Default to the beginning of the year. + var today = new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + var newFormat = format.replace(literal, function ($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, function ($0) { + var info = parseFlags[$0]; + var field = info[0], regex = info[1], requiredField = info[3]; + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error("Invalid format. " + field + " specified twice in format"); + } + specifiedFields[field] = true; + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + parseInfo.push(info); + return "(" + regex + ")"; + }); + // Check all the required fields are present + Object.keys(requiredFields).forEach(function (field) { + if (!specifiedFields[field]) { + throw new Error("Invalid format. " + field + " is required in specified format"); + } + }); + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); }); + // Check if the date string matches the format. If it doesn't return null + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // For each match, call the parser function for that date part + for (var i = 1; i < matches.length; i++) { + var _a = parseInfo[i - 1], field = _a[0], parser = _a[2]; + var value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + dateInfo[field] = value; + } + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } + else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + var dateTZ; + if (dateInfo.timezoneOffset == null) { + dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if (specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) { + return null; + } + } + } + else { + dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); + // We can't validate dates in another timezone unfortunately. Do a basic check instead + if (dateInfo.month > 11 || + dateInfo.month < 0 || + dateInfo.day > 31 || + dateInfo.day < 1 || + dateInfo.hour > 23 || + dateInfo.hour < 0 || + dateInfo.minute > 59 || + dateInfo.minute < 0 || + dateInfo.second > 59 || + dateInfo.second < 0) { + return null; + } + } + // Don't allow invalid dates + return dateTZ; + } + var fecha = { + format: format, + parse: parse, + defaultI18n: defaultI18n, + setGlobalDateI18n: setGlobalDateI18n, + setGlobalDateMasks: setGlobalDateMasks + }; + + exports.assign = assign; + exports.default = fecha; + exports.format = format; + exports.parse = parse; + exports.defaultI18n = defaultI18n; + exports.setGlobalDateI18n = setGlobalDateI18n; + exports.setGlobalDateMasks = setGlobalDateMasks; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=fecha.umd.js.map diff --git a/nodejs/node_modules/fecha/lib/fecha.umd.js.map b/nodejs/node_modules/fecha/lib/fecha.umd.js.map new file mode 100644 index 00000000..850634ba --- /dev/null +++ b/nodejs/node_modules/fecha/lib/fecha.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fecha.umd.js","sources":["../src/fecha.ts"],"sourcesContent":["const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\\1?|[aA]|\"[^\"]*\"|'[^']*'/g;\nconst twoDigitsOptional = \"\\\\d\\\\d?\";\nconst twoDigits = \"\\\\d\\\\d\";\nconst threeDigits = \"\\\\d{3}\";\nconst fourDigits = \"\\\\d{4}\";\nconst word = \"[^\\\\s]+\";\nconst literal = /\\[([^]*?)\\]/gm;\n\ntype DateInfo = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n millisecond: number;\n isPm: number | null;\n timezoneOffset: number | null;\n};\n\nexport type I18nSettings = {\n amPm: [string, string];\n dayNames: Days;\n dayNamesShort: Days;\n monthNames: Months;\n monthNamesShort: Months;\n DoFn(dayOfMonth: number): string;\n};\n\nexport type I18nSettingsOptional = Partial;\n\nexport type Days = [string, string, string, string, string, string, string];\nexport type Months = [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string\n];\n\nfunction shorten(arr: T, sLen: number): string[] {\n const newArr: string[] = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\n\nconst monthUpdate = (\n arrName: \"monthNames\" | \"monthNamesShort\" | \"dayNames\" | \"dayNamesShort\"\n) => (v: string, i18n: I18nSettings): number | null => {\n const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());\n const index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n};\n\nexport function assign(a: A): A;\nexport function assign(a: A, b: B): A & B;\nexport function assign(a: A, b: B, c: C): A & B & C;\nexport function assign(a: A, b: B, c: C, d: D): A & B & C & D;\nexport function assign(origObj: any, ...args: any[]): any {\n for (const obj of args) {\n for (const key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\n\nconst dayNames: Days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nconst monthNames: Months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\n\nconst monthNamesShort: Months = shorten(monthNames, 3) as Months;\nconst dayNamesShort: Days = shorten(dayNames, 3) as Days;\n\nconst defaultI18n: I18nSettings = {\n dayNamesShort,\n dayNames,\n monthNamesShort,\n monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn(dayOfMonth: number) {\n return (\n dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][\n dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10\n ]\n );\n }\n};\nlet globalI18n = assign({}, defaultI18n);\nconst setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>\n (globalI18n = assign(globalI18n, i18n));\n\nconst regexEscape = (str: string): string =>\n str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n\nconst pad = (val: string | number, len = 2): string => {\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\n\nconst formatFlags: Record<\n string,\n (dateObj: Date, i18n: I18nSettings) => string\n> = {\n D: (dateObj: Date): string => String(dateObj.getDate()),\n DD: (dateObj: Date): string => pad(dateObj.getDate()),\n Do: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.DoFn(dateObj.getDate()),\n d: (dateObj: Date): string => String(dateObj.getDay()),\n dd: (dateObj: Date): string => pad(dateObj.getDay()),\n ddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNamesShort[dateObj.getDay()],\n dddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNames[dateObj.getDay()],\n M: (dateObj: Date): string => String(dateObj.getMonth() + 1),\n MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),\n MMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNamesShort[dateObj.getMonth()],\n MMMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNames[dateObj.getMonth()],\n YY: (dateObj: Date): string =>\n pad(String(dateObj.getFullYear()), 4).substr(2),\n YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),\n h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),\n hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),\n H: (dateObj: Date): string => String(dateObj.getHours()),\n HH: (dateObj: Date): string => pad(dateObj.getHours()),\n m: (dateObj: Date): string => String(dateObj.getMinutes()),\n mm: (dateObj: Date): string => pad(dateObj.getMinutes()),\n s: (dateObj: Date): string => String(dateObj.getSeconds()),\n ss: (dateObj: Date): string => pad(dateObj.getSeconds()),\n S: (dateObj: Date): string =>\n String(Math.round(dateObj.getMilliseconds() / 100)),\n SS: (dateObj: Date): string =>\n pad(Math.round(dateObj.getMilliseconds() / 10), 2),\n SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),\n a: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],\n A: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase(),\n ZZ(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)\n );\n },\n Z(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2)\n );\n }\n};\n\ntype ParseInfo = [\n keyof DateInfo,\n string,\n ((v: string, i18n: I18nSettings) => number | null)?,\n string?\n];\nconst monthParse = (v: string): number => +v - 1;\nconst emptyDigits: ParseInfo = [null, twoDigitsOptional];\nconst emptyWord: ParseInfo = [null, word];\nconst amPm: ParseInfo = [\n \"isPm\",\n word,\n (v: string, i18n: I18nSettings): number | null => {\n const val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n } else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nconst timezoneOffset: ParseInfo = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n (v: string): number | null => {\n const parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n\n if (parts) {\n const minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n\n return 0;\n }\n];\nconst parseFlags: Record = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n (v: string): number => {\n const now = new Date();\n const cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", (v: string): number => +v * 100],\n SS: [\"millisecond\", twoDigits, (v: string): number => +v * 10],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n\n// Some common format strings\nconst globalMasks: { [key: string]: string } = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nconst setGlobalDateMasks = (masks: {\n [key: string]: string;\n}): { [key: string]: string } => assign(globalMasks, masks);\n\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nconst format = (\n dateObj: Date,\n mask: string = globalMasks[\"default\"],\n i18n: I18nSettingsOptional = {}\n): string => {\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n\n if (\n Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())\n ) {\n throw new Error(\"Invalid Date pass to format\");\n }\n\n mask = globalMasks[mask] || mask;\n\n const literals: string[] = [];\n\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n // Apply formatting rules\n mask = mask.replace(token, $0 =>\n formatFlags[$0](dateObj, combinedI18nSettings)\n );\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, () => literals.shift());\n};\n\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(\n dateStr: string,\n format: string,\n i18n: I18nSettingsOptional = {}\n): Date | null {\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n\n // Default to the beginning of the year.\n const today = new Date();\n const dateInfo: DateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n const parseInfo: ParseInfo[] = [];\n const literals: string[] = [];\n\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n let newFormat = format.replace(literal, ($0, $1) => {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n const specifiedFields: { [field: string]: boolean } = {};\n const requiredFields: { [field: string]: boolean } = {};\n\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, $0 => {\n const info = parseFlags[$0];\n const [field, regex, , requiredField] = info;\n\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(`Invalid format. ${field} specified twice in format`);\n }\n\n specifiedFields[field] = true;\n\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(field => {\n if (!specifiedFields[field]) {\n throw new Error(\n `Invalid format. ${field} is required in specified format`\n );\n }\n });\n\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, () => literals.shift());\n\n // Check if the date string matches the format. If it doesn't return null\n const matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n\n // For each match, call the parser function for that date part\n for (let i = 1; i < matches.length; i++) {\n const [field, , parser] = parseInfo[i - 1];\n const value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n\n dateInfo[field] = value;\n }\n\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n\n let dateTZ: Date;\n if (dateInfo.timezoneOffset == null) {\n dateTZ = new Date(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute,\n dateInfo.second,\n dateInfo.millisecond\n );\n const validateFields: [\n \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\",\n \"getMonth\" | \"getDate\" | \"getHours\" | \"getMinutes\" | \"getSeconds\"\n ][] = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (let i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (\n specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()\n ) {\n return null;\n }\n }\n } else {\n dateTZ = new Date(\n Date.UTC(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute - dateInfo.timezoneOffset,\n dateInfo.second,\n dateInfo.millisecond\n )\n );\n\n // We can't validate dates in another timezone unfortunately. Do a basic check instead\n if (\n dateInfo.month > 11 ||\n dateInfo.month < 0 ||\n dateInfo.day > 31 ||\n dateInfo.day < 1 ||\n dateInfo.hour > 23 ||\n dateInfo.hour < 0 ||\n dateInfo.minute > 59 ||\n dateInfo.minute < 0 ||\n dateInfo.second > 59 ||\n dateInfo.second < 0\n ) {\n return null;\n }\n }\n\n // Don't allow invalid dates\n\n return dateTZ;\n}\nexport default {\n format,\n parse,\n defaultI18n,\n setGlobalDateI18n,\n setGlobalDateMasks\n};\nexport { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n"],"names":[],"mappings":";;;;;;EAAA,IAAM,KAAK,GAAG,4EAA4E,CAAC;EAC3F,IAAM,iBAAiB,GAAG,SAAS,CAAC;EACpC,IAAM,SAAS,GAAG,QAAQ,CAAC;EAC3B,IAAM,WAAW,GAAG,QAAQ,CAAC;EAC7B,IAAM,UAAU,GAAG,QAAQ,CAAC;EAC5B,IAAM,IAAI,GAAG,SAAS,CAAC;EACvB,IAAM,OAAO,GAAG,eAAe,CAAC;EAyChC,SAAS,OAAO,CAAqB,GAAM,EAAE,IAAY;MACvD,IAAM,MAAM,GAAa,EAAE,CAAC;MAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;UAC9C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;OACrC;MACD,OAAO,MAAM,CAAC;EAChB,CAAC;EAED,IAAM,WAAW,GAAG,UAClB,OAAwE,IACrE,OAAA,UAAC,CAAS,EAAE,IAAkB;MACjC,IAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE,GAAA,CAAC,CAAC;MAC7D,IAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;MACpD,IAAI,KAAK,GAAG,CAAC,CAAC,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D,IACE,eAAe,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;kBACrC,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EACjE;kBACA,OAAO,IAAI,CAAC;eACb;WACF;OACF;WAAM;UACL,MAAM,GAAG,IAAI,IAAI,CACf,IAAI,CAAC,GAAG,CACN,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,KAAK,EACd,QAAQ,CAAC,GAAG,EACZ,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,cAAc,EACzC,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,WAAW,CACrB,CACF,CAAC;;UAGF,IACE,QAAQ,CAAC,KAAK,GAAG,EAAE;cACnB,QAAQ,CAAC,KAAK,GAAG,CAAC;cAClB,QAAQ,CAAC,GAAG,GAAG,EAAE;cACjB,QAAQ,CAAC,GAAG,GAAG,CAAC;cAChB,QAAQ,CAAC,IAAI,GAAG,EAAE;cAClB,QAAQ,CAAC,IAAI,GAAG,CAAC;cACjB,QAAQ,CAAC,MAAM,GAAG,EAAE;cACpB,QAAQ,CAAC,MAAM,GAAG,CAAC;cACnB,QAAQ,CAAC,MAAM,GAAG,EAAE;cACpB,QAAQ,CAAC,MAAM,GAAG,CAAC,EACnB;cACA,OAAO,IAAI,CAAC;WACb;OACF;;MAID,OAAO,MAAM,CAAC;EAChB,CAAC;AACD,cAAe;MACb,MAAM,QAAA;MACN,KAAK,OAAA;MACL,WAAW,aAAA;MACX,iBAAiB,mBAAA;MACjB,kBAAkB,oBAAA;GACnB,CAAC;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/fecha/package.json b/nodejs/node_modules/fecha/package.json new file mode 100644 index 00000000..6ebb621c --- /dev/null +++ b/nodejs/node_modules/fecha/package.json @@ -0,0 +1,55 @@ +{ + "name": "fecha", + "version": "4.2.3", + "description": "Date formatting and parsing", + "main": "lib/fecha.umd.js", + "module": "lib/fecha.js", + "scripts": { + "test-only": "ts-node test.js", + "test": "prettier --check *.js src/*.ts && eslint --ext .ts src && npm run build && nyc --cache --reporter=text ts-node test.js", + "build": "NODE_ENV=production rollup -c --sourcemap && tsc", + "format": "prettier --write *.js src/*.ts" + }, + "repository": { + "type": "git", + "url": "https://taylorhakes@github.com/taylorhakes/fecha.git" + }, + "keywords": [ + "date", + "parse", + "moment", + "format", + "fecha", + "formatting" + ], + "author": "Taylor Hakes", + "license": "MIT", + "bugs": { + "url": "https://github.com/taylorhakes/fecha/issues" + }, + "homepage": "https://github.com/taylorhakes/fecha", + "devDependencies": { + "@istanbuljs/nyc-config-typescript": "^1.0.1", + "@typescript-eslint/eslint-plugin": "^2.14.0", + "@typescript-eslint/parser": "^2.14.0", + "eslint": "^7.23.0", + "eslint-config-prettier": "^8.1.0", + "nyc": "^15.0.0", + "painless": "^0.9.7", + "prettier": "1.19.1", + "rollup": "^0.59.0", + "rollup-plugin-sourcemaps": "^0.5.0", + "rollup-plugin-typescript": "^1.0.1", + "rollup-plugin-uglify": "^3.0.0", + "source-map-support": "^0.5.16", + "ts-node": "^8.5.4", + "tslib": "^1.10.0", + "typescript": "^3.7.4" + }, + "files": [ + "lib", + "dist", + "src" + ], + "types": "lib/fecha.d.ts" +} diff --git a/nodejs/node_modules/fecha/src/fecha.ts b/nodejs/node_modules/fecha/src/fecha.ts new file mode 100644 index 00000000..6f6bcff6 --- /dev/null +++ b/nodejs/node_modules/fecha/src/fecha.ts @@ -0,0 +1,524 @@ +const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; +const twoDigitsOptional = "\\d\\d?"; +const twoDigits = "\\d\\d"; +const threeDigits = "\\d{3}"; +const fourDigits = "\\d{4}"; +const word = "[^\\s]+"; +const literal = /\[([^]*?)\]/gm; + +type DateInfo = { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + millisecond: number; + isPm: number | null; + timezoneOffset: number | null; +}; + +export type I18nSettings = { + amPm: [string, string]; + dayNames: Days; + dayNamesShort: Days; + monthNames: Months; + monthNamesShort: Months; + DoFn(dayOfMonth: number): string; +}; + +export type I18nSettingsOptional = Partial; + +export type Days = [string, string, string, string, string, string, string]; +export type Months = [ + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string +]; + +function shorten(arr: T, sLen: number): string[] { + const newArr: string[] = []; + for (let i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; +} + +const monthUpdate = ( + arrName: "monthNames" | "monthNamesShort" | "dayNames" | "dayNamesShort" +) => (v: string, i18n: I18nSettings): number | null => { + const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase()); + const index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; +}; + +export function assign(a: A): A; +export function assign(a: A, b: B): A & B; +export function assign(a: A, b: B, c: C): A & B & C; +export function assign(a: A, b: B, c: C, d: D): A & B & C & D; +export function assign(origObj: any, ...args: any[]): any { + for (const obj of args) { + for (const key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; +} + +const dayNames: Days = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" +]; +const monthNames: Months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; + +const monthNamesShort: Months = shorten(monthNames, 3) as Months; +const dayNamesShort: Days = shorten(dayNames, 3) as Days; + +const defaultI18n: I18nSettings = { + dayNamesShort, + dayNames, + monthNamesShort, + monthNames, + amPm: ["am", "pm"], + DoFn(dayOfMonth: number) { + return ( + dayOfMonth + + ["th", "st", "nd", "rd"][ + dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10 + ] + ); + } +}; +let globalI18n = assign({}, defaultI18n); +const setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings => + (globalI18n = assign(globalI18n, i18n)); + +const regexEscape = (str: string): string => + str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); + +const pad = (val: string | number, len = 2): string => { + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; +}; + +const formatFlags: Record< + string, + (dateObj: Date, i18n: I18nSettings) => string +> = { + D: (dateObj: Date): string => String(dateObj.getDate()), + DD: (dateObj: Date): string => pad(dateObj.getDate()), + Do: (dateObj: Date, i18n: I18nSettings): string => + i18n.DoFn(dateObj.getDate()), + d: (dateObj: Date): string => String(dateObj.getDay()), + dd: (dateObj: Date): string => pad(dateObj.getDay()), + ddd: (dateObj: Date, i18n: I18nSettings): string => + i18n.dayNamesShort[dateObj.getDay()], + dddd: (dateObj: Date, i18n: I18nSettings): string => + i18n.dayNames[dateObj.getDay()], + M: (dateObj: Date): string => String(dateObj.getMonth() + 1), + MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1), + MMM: (dateObj: Date, i18n: I18nSettings): string => + i18n.monthNamesShort[dateObj.getMonth()], + MMMM: (dateObj: Date, i18n: I18nSettings): string => + i18n.monthNames[dateObj.getMonth()], + YY: (dateObj: Date): string => + pad(String(dateObj.getFullYear()), 4).substr(2), + YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4), + h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12), + hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12), + H: (dateObj: Date): string => String(dateObj.getHours()), + HH: (dateObj: Date): string => pad(dateObj.getHours()), + m: (dateObj: Date): string => String(dateObj.getMinutes()), + mm: (dateObj: Date): string => pad(dateObj.getMinutes()), + s: (dateObj: Date): string => String(dateObj.getSeconds()), + ss: (dateObj: Date): string => pad(dateObj.getSeconds()), + S: (dateObj: Date): string => + String(Math.round(dateObj.getMilliseconds() / 100)), + SS: (dateObj: Date): string => + pad(Math.round(dateObj.getMilliseconds() / 10), 2), + SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3), + a: (dateObj: Date, i18n: I18nSettings): string => + dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1], + A: (dateObj: Date, i18n: I18nSettings): string => + dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(), + ZZ(dateObj: Date): string { + const offset = dateObj.getTimezoneOffset(); + return ( + (offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4) + ); + }, + Z(dateObj: Date): string { + const offset = dateObj.getTimezoneOffset(); + return ( + (offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2) + ); + } +}; + +type ParseInfo = [ + keyof DateInfo, + string, + ((v: string, i18n: I18nSettings) => number | null)?, + string? +]; +const monthParse = (v: string): number => +v - 1; +const emptyDigits: ParseInfo = [null, twoDigitsOptional]; +const emptyWord: ParseInfo = [null, word]; +const amPm: ParseInfo = [ + "isPm", + word, + (v: string, i18n: I18nSettings): number | null => { + const val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } +]; +const timezoneOffset: ParseInfo = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + (v: string): number | null => { + const parts = (v + "").match(/([+-]|\d\d)/gi); + + if (parts) { + const minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + + return 0; + } +]; +const parseFlags: Record = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + (v: string): number => { + const now = new Date(); + const cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", (v: string): number => +v * 100], + SS: ["millisecond", twoDigits, (v: string): number => +v * 10], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset +}; + +// Some common format strings +const globalMasks: { [key: string]: string } = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; +const setGlobalDateMasks = (masks: { + [key: string]: string; +}): { [key: string]: string } => assign(globalMasks, masks); + +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +const format = ( + dateObj: Date, + mask: string = globalMasks["default"], + i18n: I18nSettingsOptional = {} +): string => { + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + + if ( + Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime()) + ) { + throw new Error("Invalid Date pass to format"); + } + + mask = globalMasks[mask] || mask; + + const literals: string[] = []; + + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function($0, $1) { + literals.push($1); + return "@@@"; + }); + + const combinedI18nSettings: I18nSettings = assign( + assign({}, globalI18n), + i18n + ); + // Apply formatting rules + mask = mask.replace(token, $0 => + formatFlags[$0](dateObj, combinedI18nSettings) + ); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, () => literals.shift()); +}; + +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +function parse( + dateStr: string, + format: string, + i18n: I18nSettingsOptional = {} +): Date | null { + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + + // Default to the beginning of the year. + const today = new Date(); + const dateInfo: DateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + const parseInfo: ParseInfo[] = []; + const literals: string[] = []; + + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + let newFormat = format.replace(literal, ($0, $1) => { + literals.push(regexEscape($1)); + return "@@@"; + }); + const specifiedFields: { [field: string]: boolean } = {}; + const requiredFields: { [field: string]: boolean } = {}; + + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, $0 => { + const info = parseFlags[$0]; + const [field, regex, , requiredField] = info; + + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error(`Invalid format. ${field} specified twice in format`); + } + + specifiedFields[field] = true; + + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + + parseInfo.push(info); + return "(" + regex + ")"; + }); + + // Check all the required fields are present + Object.keys(requiredFields).forEach(field => { + if (!specifiedFields[field]) { + throw new Error( + `Invalid format. ${field} is required in specified format` + ); + } + }); + + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, () => literals.shift()); + + // Check if the date string matches the format. If it doesn't return null + const matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + + const combinedI18nSettings: I18nSettings = assign( + assign({}, globalI18n), + i18n + ); + + // For each match, call the parser function for that date part + for (let i = 1; i < matches.length; i++) { + const [field, , parser] = parseInfo[i - 1]; + const value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + + dateInfo[field] = value; + } + + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + + let dateTZ: Date; + if (dateInfo.timezoneOffset == null) { + dateTZ = new Date( + dateInfo.year, + dateInfo.month, + dateInfo.day, + dateInfo.hour, + dateInfo.minute, + dateInfo.second, + dateInfo.millisecond + ); + const validateFields: [ + "month" | "day" | "hour" | "minute" | "second", + "getMonth" | "getDate" | "getHours" | "getMinutes" | "getSeconds" + ][] = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (let i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if ( + specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]() + ) { + return null; + } + } + } else { + dateTZ = new Date( + Date.UTC( + dateInfo.year, + dateInfo.month, + dateInfo.day, + dateInfo.hour, + dateInfo.minute - dateInfo.timezoneOffset, + dateInfo.second, + dateInfo.millisecond + ) + ); + + // We can't validate dates in another timezone unfortunately. Do a basic check instead + if ( + dateInfo.month > 11 || + dateInfo.month < 0 || + dateInfo.day > 31 || + dateInfo.day < 1 || + dateInfo.hour > 23 || + dateInfo.hour < 0 || + dateInfo.minute > 59 || + dateInfo.minute < 0 || + dateInfo.second > 59 || + dateInfo.second < 0 + ) { + return null; + } + } + + // Don't allow invalid dates + + return dateTZ; +} +export default { + format, + parse, + defaultI18n, + setGlobalDateI18n, + setGlobalDateMasks +}; +export { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; diff --git a/nodejs/node_modules/fn.name/.gitattributes b/nodejs/node_modules/fn.name/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/nodejs/node_modules/fn.name/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/nodejs/node_modules/fn.name/.travis.yml b/nodejs/node_modules/fn.name/.travis.yml new file mode 100644 index 00000000..dec03398 --- /dev/null +++ b/nodejs/node_modules/fn.name/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - "10" + - "8" + - "6" + - "4" +script: + - "npm run test-travis" +after_script: + - "npm install coveralls@2.11.x && cat coverage/lcov.info | coveralls" diff --git a/nodejs/node_modules/fn.name/LICENSE b/nodejs/node_modules/fn.name/LICENSE new file mode 100644 index 00000000..b68d272b --- /dev/null +++ b/nodejs/node_modules/fn.name/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the Contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/nodejs/node_modules/fn.name/README.md b/nodejs/node_modules/fn.name/README.md new file mode 100644 index 00000000..1b199ea8 --- /dev/null +++ b/nodejs/node_modules/fn.name/README.md @@ -0,0 +1,42 @@ +# fn.name + +[![Version npm][version]](http://npm.im/fn.name)[![Build Status][build]](https://travis-ci.org/3rd-Eden/fn.name)[![Dependencies][david]](https://david-dm.org/3rd-Eden/fn.name)[![Coverage Status][cover]](https://coveralls.io/r/3rd-Eden/fn.name?branch=master) + +[version]: http://img.shields.io/npm/v/fn.name.svg?style=flat-square +[build]: http://img.shields.io/travis/3rd-Eden/fn.name/master.svg?style=flat-square +[david]: https://img.shields.io/david/3rd-Eden/fn.name.svg?style=flat-square +[cover]: http://img.shields.io/coveralls/3rd-Eden/fn.name/master.svg?style=flat-square + +Extract the name of a given function. Nothing more than that. + +## Installation + +This module is compatible with Browserify and Node.js and can be installed +using: + +``` +npm install --save fn.name +``` + +## Usage + +Using this module is super simple, it exposes the function directly on the +exports so it can be required as followed: + +```js +'use strict'; + +var name = require('fn.name'); +``` + +Now that we have the `name` function we can pass it functions: + +```js +console.log(name(function foo() {})) // foo +``` + +And that's it folks! + +## License + +MIT diff --git a/nodejs/node_modules/fn.name/index.js b/nodejs/node_modules/fn.name/index.js new file mode 100644 index 00000000..0fb0f596 --- /dev/null +++ b/nodejs/node_modules/fn.name/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var toString = Object.prototype.toString; + +/** + * Extract names from functions. + * + * @param {Function} fn The function who's name we need to extract. + * @returns {String} The name of the function. + * @public + */ +module.exports = function name(fn) { + if ('string' === typeof fn.displayName && fn.constructor.name) { + return fn.displayName; + } else if ('string' === typeof fn.name && fn.name) { + return fn.name; + } + + // + // Check to see if the constructor has a name. + // + if ( + 'object' === typeof fn + && fn.constructor + && 'string' === typeof fn.constructor.name + ) return fn.constructor.name; + + // + // toString the given function and attempt to parse it out of it, or determine + // the class. + // + var named = fn.toString() + , type = toString.call(fn).slice(8, -1); + + if ('Function' === type) { + named = named.substring(named.indexOf('(') + 1, named.indexOf(')')); + } else { + named = type; + } + + return named || 'anonymous'; +}; diff --git a/nodejs/node_modules/fn.name/package.json b/nodejs/node_modules/fn.name/package.json new file mode 100644 index 00000000..83cde5cf --- /dev/null +++ b/nodejs/node_modules/fn.name/package.json @@ -0,0 +1,37 @@ +{ + "name": "fn.name", + "version": "1.1.0", + "description": "Extract names from functions", + "main": "index.js", + "scripts": { + "test": "mocha test.js", + "watch": "mocha --watch test.js", + "coverage": "istanbul cover ./node_modules/.bin/_mocha -- test.js", + "test-travis": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/3rd-Eden/fn.name" + }, + "keywords": [ + "fn.name", + "function.name", + "name", + "function", + "extract", + "parse", + "names" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "bugs": { + "url": "https://github.com/3rd-Eden/fn.name/issues" + }, + "devDependencies": { + "assume": "2.x.x", + "istanbul": "0.3.x", + "mocha": "5.x.x", + "pre-commit": "1.x.x" + }, + "homepage": "https://github.com/3rd-Eden/fn.name" +} diff --git a/nodejs/node_modules/fn.name/test.js b/nodejs/node_modules/fn.name/test.js new file mode 100644 index 00000000..b7d8f443 --- /dev/null +++ b/nodejs/node_modules/fn.name/test.js @@ -0,0 +1,73 @@ +describe('fn.name', function () { + 'use strict'; + + var assume = require('assume') + , name = require('./'); + + it('is exported as a function', function () { + assume(name).is.a('function'); + }); + + it('can extract the name from a function declaration', function () { + function foobar() {} + + assume(name(foobar)).equals('foobar'); + }); + + it('can extract the name from a function expression', function () { + var a = function bar() {}; + + assume(name(a)).equals('bar'); + }); + + it('can be overriden using displayName', function () { + var a = function bar() {}; + a.displayName = 'bro'; + + assume(name(a)).equals('bro'); + }); + + it('works with constructed instances', function () { + function Bar(){} + + var foo = new Bar(); + + assume(name(foo)).equals('Bar'); + }); + + it('works with anonymous', function () { + assume(name(function () {})).equals('anonymous'); + }); + + it('returns the className if we were not given a function', function () { + assume(name('string')).equals('String'); + }); + + // + // Test if the env supports async functions, if so add a test to ensure + // that we will work with async functions. + // + var asyncfn = true; + try { new Function('return async function hello() {}')(); } + catch (e) { asyncfn = false; } + + if (asyncfn) it('detects the name of async functions', function () { + var fn = new Function('return async function hello() {}')(); + + assume(name(fn)).equals('hello'); + }); + + // + // Test that this env supports generators, if so add a test to ensure that + // we will work with generators. + // + var generators = true; + try { new Function('return function* generator() {}')(); } + catch (e) { generator = false; } + + if (generators) it('detecs the name of a generator', function () { + var fn = new Function('return function* hello() {}')(); + + assume(name(fn)).equals('hello'); + }); +}); diff --git a/nodejs/node_modules/http/README.md b/nodejs/node_modules/http/README.md new file mode 100644 index 00000000..5e9a74ca --- /dev/null +++ b/nodejs/node_modules/http/README.md @@ -0,0 +1,9 @@ +# Security holding package + +This package name is not currently in use, but was formerly occupied +by another package. To avoid malicious use, npm is hanging on to the +package name, but loosely, and we'll probably give it to you if you +want it. + +You may adopt this package by contacting support@npmjs.com and +requesting the name. diff --git a/nodejs/node_modules/http/package.json b/nodejs/node_modules/http/package.json new file mode 100644 index 00000000..4196f28c --- /dev/null +++ b/nodejs/node_modules/http/package.json @@ -0,0 +1,6 @@ +{ + "name": "http", + "version": "0.0.1-security", + "description": "security holding package", + "repository": "npm/security-holder" +} diff --git a/nodejs/node_modules/ieee754/LICENSE b/nodejs/node_modules/ieee754/LICENSE new file mode 100644 index 00000000..5aac82c7 --- /dev/null +++ b/nodejs/node_modules/ieee754/LICENSE @@ -0,0 +1,11 @@ +Copyright 2008 Fair Oaks Labs, Inc. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/nodejs/node_modules/ieee754/README.md b/nodejs/node_modules/ieee754/README.md new file mode 100644 index 00000000..cb7527b3 --- /dev/null +++ b/nodejs/node_modules/ieee754/README.md @@ -0,0 +1,51 @@ +# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg +[travis-url]: https://travis-ci.org/feross/ieee754 +[npm-image]: https://img.shields.io/npm/v/ieee754.svg +[npm-url]: https://npmjs.org/package/ieee754 +[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg +[downloads-url]: https://npmjs.org/package/ieee754 +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg +[saucelabs-url]: https://saucelabs.com/u/ieee754 + +### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. + +## install + +``` +npm install ieee754 +``` + +## methods + +`var ieee754 = require('ieee754')` + +The `ieee754` object has the following functions: + +``` +ieee754.read = function (buffer, offset, isLE, mLen, nBytes) +ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) +``` + +The arguments mean the following: + +- buffer = the buffer +- offset = offset into the buffer +- value = value to set (only for `write`) +- isLe = is little endian? +- mLen = mantissa length +- nBytes = number of bytes + +## what is ieee754? + +The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). + +## license + +BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. diff --git a/nodejs/node_modules/ieee754/index.d.ts b/nodejs/node_modules/ieee754/index.d.ts new file mode 100644 index 00000000..f1e43548 --- /dev/null +++ b/nodejs/node_modules/ieee754/index.d.ts @@ -0,0 +1,10 @@ +declare namespace ieee754 { + export function read( + buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, + nBytes: number): number; + export function write( + buffer: Uint8Array, value: number, offset: number, isLE: boolean, + mLen: number, nBytes: number): void; + } + + export = ieee754; \ No newline at end of file diff --git a/nodejs/node_modules/ieee754/index.js b/nodejs/node_modules/ieee754/index.js new file mode 100644 index 00000000..81d26c34 --- /dev/null +++ b/nodejs/node_modules/ieee754/index.js @@ -0,0 +1,85 @@ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/nodejs/node_modules/ieee754/package.json b/nodejs/node_modules/ieee754/package.json new file mode 100644 index 00000000..7b238513 --- /dev/null +++ b/nodejs/node_modules/ieee754/package.json @@ -0,0 +1,52 @@ +{ + "name": "ieee754", + "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", + "version": "1.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "contributors": [ + "Romain Beauxis " + ], + "devDependencies": { + "airtap": "^3.0.0", + "standard": "*", + "tape": "^5.0.1" + }, + "keywords": [ + "IEEE 754", + "buffer", + "convert", + "floating point", + "ieee754" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/ieee754.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/nodejs/node_modules/immediate/.travis.yml b/nodejs/node_modules/immediate/.travis.yml new file mode 100644 index 00000000..a42ec86c --- /dev/null +++ b/nodejs/node_modules/immediate/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - 'lts/*' +notifications: + email: false diff --git a/nodejs/node_modules/immediate/LICENSE.txt b/nodejs/node_modules/immediate/LICENSE.txt new file mode 100644 index 00000000..88c18c27 --- /dev/null +++ b/nodejs/node_modules/immediate/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, Domenic Denicola, Brian Cavalier + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/immediate/README.md b/nodejs/node_modules/immediate/README.md new file mode 100644 index 00000000..450e0b0c --- /dev/null +++ b/nodejs/node_modules/immediate/README.md @@ -0,0 +1,85 @@ +# immediate [![Build Status](https://travis-ci.org/calvinmetcalf/immediate.svg?branch=master)](https://travis-ci.org/calvinmetcalf/immediate) + +[![testling status](https://ci.testling.com/calvinmetcalf/immediate.png)](https://ci.testling.com/calvinmetcalf/immediate) + +``` +npm install immediate --save +``` + +then + +```js +var immediate = require("immediate"); + +immediate(function () { + // this will run soon +}); + +immediate(function (arg1, arg2) { + // get your args like in iojs +}, thing1, thing2); +``` + +## Introduction + +**immediate** is a microtask library, descended from [NobleJS's setImmediate](https://github.com/NobleJS/setImmediate), but including ideas from [Cujo's When](https://github.com/cujojs/when) and [RSVP][RSVP]. + +immediate takes the tricks from setImmediate and RSVP and combines them with the scheduler inspired (vaguely) by when's. + +Note versions 2.6.5 and earlier were strictly speaking a 'macrotask' library not a microtask one, [see this for the difference](https://github.com/YuzuJS/setImmediate#macrotasks-and-microtasks), if you need a macrotask library, [I got you covered](https://github.com/calvinmetcalf/macrotask). + +Several new features were added in versions 3.1.0 and 3.2.0 to maintain parity with +process.nextTick, but the 3.0.x series is still being kept up to date if you just need +the small barebones version + +## The Tricks + +### `process.nextTick` + +Note that we check for *actual* Node.js environments, not emulated ones like those produced by browserify or similar. + +### `queueMicrotask` + +Function available in major browser these days which you can use to add a function into the microtask queue managed by V8. + +### `MutationObserver` + +This is what [RSVP][RSVP] uses, it's very fast, details on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). + + +### `MessageChannel` + +Unfortunately, `postMessage` has completely different semantics inside web workers, and so cannot be used there. So we +turn to [`MessageChannel`][MessageChannel], which has worse browser support, but does work inside a web worker. + +### ` + + + + + +` + +console.log(testHtml) diff --git a/nodejs/node_modules/lib0/binary.d.ts b/nodejs/node_modules/lib0/binary.d.ts new file mode 100644 index 00000000..890f0c47 --- /dev/null +++ b/nodejs/node_modules/lib0/binary.d.ts @@ -0,0 +1,87 @@ +/** + * Binary data constants. + * + * @module binary + */ +/** + * n-th bit activated. + * + * @type {number} + */ +export const BIT1: number; +export const BIT2: 2; +export const BIT3: 4; +export const BIT4: 8; +export const BIT5: 16; +export const BIT6: 32; +export const BIT7: 64; +export const BIT8: 128; +export const BIT9: 256; +export const BIT10: 512; +export const BIT11: 1024; +export const BIT12: 2048; +export const BIT13: 4096; +export const BIT14: 8192; +export const BIT15: 16384; +export const BIT16: 32768; +export const BIT17: 65536; +export const BIT18: number; +export const BIT19: number; +export const BIT20: number; +export const BIT21: number; +export const BIT22: number; +export const BIT23: number; +export const BIT24: number; +export const BIT25: number; +export const BIT26: number; +export const BIT27: number; +export const BIT28: number; +export const BIT29: number; +export const BIT30: number; +export const BIT31: number; +export const BIT32: number; +/** + * First n bits activated. + * + * @type {number} + */ +export const BITS0: number; +export const BITS1: 1; +export const BITS2: 3; +export const BITS3: 7; +export const BITS4: 15; +export const BITS5: 31; +export const BITS6: 63; +export const BITS7: 127; +export const BITS8: 255; +export const BITS9: 511; +export const BITS10: 1023; +export const BITS11: 2047; +export const BITS12: 4095; +export const BITS13: 8191; +export const BITS14: 16383; +export const BITS15: 32767; +export const BITS16: 65535; +export const BITS17: number; +export const BITS18: number; +export const BITS19: number; +export const BITS20: number; +export const BITS21: number; +export const BITS22: number; +export const BITS23: number; +export const BITS24: number; +export const BITS25: number; +export const BITS26: number; +export const BITS27: number; +export const BITS28: number; +export const BITS29: number; +export const BITS30: number; +/** + * @type {number} + */ +export const BITS31: number; +/** + * @type {number} + */ +export const BITS32: number; +//# sourceMappingURL=binary.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/binary.d.ts.map b/nodejs/node_modules/lib0/binary.d.ts.map new file mode 100644 index 00000000..df831ff9 --- /dev/null +++ b/nodejs/node_modules/lib0/binary.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.d.ts","sourceRoot":"","sources":["binary.js"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH;;;;GAIG;AACH,mBAFU,MAAM,CAEK;AACrB,qBAAqB;AACrB,qBAAqB;AACrB,qBAAqB;AACrB,sBAAsB;AACtB,sBAAsB;AACtB,sBAAsB;AACtB,uBAAuB;AACvB,uBAAuB;AACvB,wBAAwB;AACxB,yBAAyB;AACzB,yBAAyB;AACzB,yBAAyB;AACzB,yBAAyB;AACzB,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAE5B;;;;GAIG;AACH,oBAFU,MAAM,CAEM;AACtB,sBAAsB;AACtB,sBAAsB;AACtB,sBAAsB;AACtB,uBAAuB;AACvB,uBAAuB;AACvB,uBAAuB;AACvB,wBAAwB;AACxB,wBAAwB;AACxB,wBAAwB;AACxB,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B,2BAA2B;AAC3B,2BAA2B;AAC3B,2BAA2B;AAC3B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B;;GAEG;AACH,qBAFU,MAAM,CAEgB;AAChC;;GAEG;AACH,qBAFU,MAAM,CAEgB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/binary.js b/nodejs/node_modules/lib0/binary.js new file mode 100644 index 00000000..babab552 --- /dev/null +++ b/nodejs/node_modules/lib0/binary.js @@ -0,0 +1,90 @@ +/* eslint-env browser */ + +/** + * Binary data constants. + * + * @module binary + */ + +/** + * n-th bit activated. + * + * @type {number} + */ +export const BIT1 = 1 +export const BIT2 = 2 +export const BIT3 = 4 +export const BIT4 = 8 +export const BIT5 = 16 +export const BIT6 = 32 +export const BIT7 = 64 +export const BIT8 = 128 +export const BIT9 = 256 +export const BIT10 = 512 +export const BIT11 = 1024 +export const BIT12 = 2048 +export const BIT13 = 4096 +export const BIT14 = 8192 +export const BIT15 = 16384 +export const BIT16 = 32768 +export const BIT17 = 65536 +export const BIT18 = 1 << 17 +export const BIT19 = 1 << 18 +export const BIT20 = 1 << 19 +export const BIT21 = 1 << 20 +export const BIT22 = 1 << 21 +export const BIT23 = 1 << 22 +export const BIT24 = 1 << 23 +export const BIT25 = 1 << 24 +export const BIT26 = 1 << 25 +export const BIT27 = 1 << 26 +export const BIT28 = 1 << 27 +export const BIT29 = 1 << 28 +export const BIT30 = 1 << 29 +export const BIT31 = 1 << 30 +export const BIT32 = 1 << 31 + +/** + * First n bits activated. + * + * @type {number} + */ +export const BITS0 = 0 +export const BITS1 = 1 +export const BITS2 = 3 +export const BITS3 = 7 +export const BITS4 = 15 +export const BITS5 = 31 +export const BITS6 = 63 +export const BITS7 = 127 +export const BITS8 = 255 +export const BITS9 = 511 +export const BITS10 = 1023 +export const BITS11 = 2047 +export const BITS12 = 4095 +export const BITS13 = 8191 +export const BITS14 = 16383 +export const BITS15 = 32767 +export const BITS16 = 65535 +export const BITS17 = BIT18 - 1 +export const BITS18 = BIT19 - 1 +export const BITS19 = BIT20 - 1 +export const BITS20 = BIT21 - 1 +export const BITS21 = BIT22 - 1 +export const BITS22 = BIT23 - 1 +export const BITS23 = BIT24 - 1 +export const BITS24 = BIT25 - 1 +export const BITS25 = BIT26 - 1 +export const BITS26 = BIT27 - 1 +export const BITS27 = BIT28 - 1 +export const BITS28 = BIT29 - 1 +export const BITS29 = BIT30 - 1 +export const BITS30 = BIT31 - 1 +/** + * @type {number} + */ +export const BITS31 = 0x7FFFFFFF +/** + * @type {number} + */ +export const BITS32 = 0xFFFFFFFF diff --git a/nodejs/node_modules/lib0/binary.test.d.ts b/nodejs/node_modules/lib0/binary.test.d.ts new file mode 100644 index 00000000..1c2e5865 --- /dev/null +++ b/nodejs/node_modules/lib0/binary.test.d.ts @@ -0,0 +1,4 @@ +export function testBitx(tc: t.TestCase): void; +export function testBitsx(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=binary.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/binary.test.d.ts.map b/nodejs/node_modules/lib0/binary.test.d.ts.map new file mode 100644 index 00000000..c91944d3 --- /dev/null +++ b/nodejs/node_modules/lib0/binary.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.test.d.ts","sourceRoot":"","sources":["binary.test.js"],"names":[],"mappings":"AAMO,6BAFI,EAAE,QAAQ,QAOpB;AAKM,8BAFI,EAAE,QAAQ,QAWpB;mBAxBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/broadcastchannel.d.ts b/nodejs/node_modules/lib0/broadcastchannel.d.ts new file mode 100644 index 00000000..d8f048e5 --- /dev/null +++ b/nodejs/node_modules/lib0/broadcastchannel.d.ts @@ -0,0 +1,8 @@ +export function subscribe(room: string, f: (arg0: any, arg1: any) => any): (arg0: any, arg1: any) => any; +export function unsubscribe(room: string, f: (arg0: any, arg1: any) => any): boolean; +export function publish(room: string, data: any, origin?: any): void; +export type Channel = { + subs: Set<(arg0: any, arg1: any) => any>; + bc: any; +}; +//# sourceMappingURL=broadcastchannel.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/broadcastchannel.d.ts.map b/nodejs/node_modules/lib0/broadcastchannel.d.ts.map new file mode 100644 index 00000000..cc6674ca --- /dev/null +++ b/nodejs/node_modules/lib0/broadcastchannel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"broadcastchannel.d.ts","sourceRoot":"","sources":["broadcastchannel.js"],"names":[],"mappings":"AA+FO,gCAHI,MAAM,YACG,GAAG,QAAE,GAAG,KAAE,GAAG,UAAb,GAAG,QAAE,GAAG,KAAE,GAAG,CAKhC;AASM,kCAHI,MAAM,YACG,GAAG,QAAE,GAAG,KAAE,GAAG,WAUhC;AAUM,8BAJI,MAAM,QACN,GAAG,WACH,GAAG,QAMb;;UAvGa,WAAa,GAAG,QAAE,GAAG,KAAE,GAAG,CAAC;QAC3B,GAAG"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/broadcastchannel.js b/nodejs/node_modules/lib0/broadcastchannel.js new file mode 100644 index 00000000..0959283b --- /dev/null +++ b/nodejs/node_modules/lib0/broadcastchannel.js @@ -0,0 +1,130 @@ +/* eslint-env browser */ + +/** + * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback. + * + * ```js + * // In browser window A: + * broadcastchannel.subscribe('my events', data => console.log(data)) + * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab + * + * // In browser window B: + * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B' + * ``` + * + * @module broadcastchannel + */ + +// @todo before next major: use Uint8Array instead as buffer object + +import * as map from './map.js' +import * as set from './set.js' +import * as buffer from './buffer.js' +import * as storage from './storage.js' + +/** + * @typedef {Object} Channel + * @property {Set} Channel.subs + * @property {any} Channel.bc + */ + +/** + * @type {Map} + */ +const channels = new Map() + +/* c8 ignore start */ +class LocalStoragePolyfill { + /** + * @param {string} room + */ + constructor (room) { + this.room = room + /** + * @type {null|function({data:ArrayBuffer}):void} + */ + this.onmessage = null + /** + * @param {any} e + */ + this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') }) + storage.onChange(this._onChange) + } + + /** + * @param {ArrayBuffer} buf + */ + postMessage (buf) { + storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf))) + } + + close () { + storage.offChange(this._onChange) + } +} +/* c8 ignore stop */ + +// Use BroadcastChannel or Polyfill +/* c8 ignore next */ +const BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel + +/** + * @param {string} room + * @return {Channel} + */ +const getChannel = room => + map.setIfUndefined(channels, room, () => { + const subs = set.create() + const bc = new BC(room) + /** + * @param {{data:ArrayBuffer}} e + */ + /* c8 ignore next */ + bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel')) + return { + bc, subs + } + }) + +/** + * Subscribe to global `publish` events. + * + * @function + * @param {string} room + * @param {function(any, any):any} f + */ +export const subscribe = (room, f) => { + getChannel(room).subs.add(f) + return f +} + +/** + * Unsubscribe from `publish` global events. + * + * @function + * @param {string} room + * @param {function(any, any):any} f + */ +export const unsubscribe = (room, f) => { + const channel = getChannel(room) + const unsubscribed = channel.subs.delete(f) + if (unsubscribed && channel.subs.size === 0) { + channel.bc.close() + channels.delete(room) + } + return unsubscribed +} + +/** + * Publish data to all subscribers (including subscribers on this tab) + * + * @function + * @param {string} room + * @param {any} data + * @param {any} [origin] + */ +export const publish = (room, data, origin = null) => { + const c = getChannel(room) + c.bc.postMessage(data) + c.subs.forEach(sub => sub(data, origin)) +} diff --git a/nodejs/node_modules/lib0/broadcastchannel.test.d.ts b/nodejs/node_modules/lib0/broadcastchannel.test.d.ts new file mode 100644 index 00000000..a746c1dd --- /dev/null +++ b/nodejs/node_modules/lib0/broadcastchannel.test.d.ts @@ -0,0 +1,3 @@ +export function testBroadcastChannel(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=broadcastchannel.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/broadcastchannel.test.d.ts.map b/nodejs/node_modules/lib0/broadcastchannel.test.d.ts.map new file mode 100644 index 00000000..9e26d533 --- /dev/null +++ b/nodejs/node_modules/lib0/broadcastchannel.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"broadcastchannel.test.d.ts","sourceRoot":"","sources":["broadcastchannel.test.js"],"names":[],"mappings":"AAMO,yCAFI,EAAE,QAAQ,QAkBpB;mBAtBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/buffer.d.ts b/nodejs/node_modules/lib0/buffer.d.ts new file mode 100644 index 00000000..23660269 --- /dev/null +++ b/nodejs/node_modules/lib0/buffer.d.ts @@ -0,0 +1,22 @@ +export function createUint8ArrayFromLen(len: number): Uint8Array; +export function createUint8ArrayViewFromArrayBuffer(buffer: ArrayBuffer, byteOffset: number, length: number): Uint8Array; +export function createUint8ArrayFromArrayBuffer(buffer: ArrayBuffer): Uint8Array; +/** + * @param {Uint8Array} bytes + * @return {string} + */ +export function toBase64(bytes: Uint8Array): string; +/** + * @param {string} s + * @return {Uint8Array} + */ +export function fromBase64(s: string): Uint8Array; +export function toBase64UrlEncoded(buf: Uint8Array): string; +export function fromBase64UrlEncoded(base64: string): Uint8Array; +export function toHexString(buf: Uint8Array): string; +export function fromHexString(hex: string): Uint8Array; +export function copyUint8Array(uint8Array: Uint8Array): Uint8Array; +export function encodeAny(data: any): Uint8Array; +export function decodeAny(buf: Uint8Array): any; +export function shiftNBitsLeft(bs: Uint8Array, N: number): Uint8Array; +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/buffer.d.ts.map b/nodejs/node_modules/lib0/buffer.d.ts.map new file mode 100644 index 00000000..1d7264db --- /dev/null +++ b/nodejs/node_modules/lib0/buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["buffer.js"],"names":[],"mappings":"AAgBO,6CAFI,MAAM,cAEgD;AAS1D,4DAJI,WAAW,cACX,MAAM,UACN,MAAM,cAE4G;AAOtH,wDAFI,WAAW,cAEyD;AAG/E;;;GAGG;AACH,gCAHW,UAAU,GACT,MAAM,CASjB;AAUD;;;GAGG;AACH,8BAHW,MAAM,GACL,UAAU,CAUrB;AAqBM,wCAFI,UAAU,UAE+F;AAK7G,6CAFI,MAAM,cAEyF;AAOnG,iCAFI,UAAU,UAE0E;AAOxF,mCAFI,MAAM,cAShB;AAQM,2CAHI,UAAU,GACT,UAAU,CAMrB;AASM,gCAHI,GAAG,GACF,UAAU,CAGwC;AAQvD,+BAHI,UAAU,GACT,GAAG,CAE8D;AAQtE,mCAHI,UAAU,KACV,MAAM,cAWhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/buffer.js b/nodejs/node_modules/lib0/buffer.js new file mode 100644 index 00000000..85d66016 --- /dev/null +++ b/nodejs/node_modules/lib0/buffer.js @@ -0,0 +1,163 @@ +/** + * Utility functions to work with buffers (Uint8Array). + * + * @module buffer + */ + +import * as string from './string.js' +import * as env from './environment.js' +import * as array from './array.js' +import * as math from './math.js' +import * as encoding from './encoding.js' +import * as decoding from './decoding.js' + +/** + * @param {number} len + */ +export const createUint8ArrayFromLen = len => new Uint8Array(len) + +/** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + * @param {number} byteOffset + * @param {number} length + */ +export const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length) + +/** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + */ +export const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer) + +/* c8 ignore start */ +/** + * @param {Uint8Array} bytes + * @return {string} + */ +const toBase64Browser = bytes => { + let s = '' + for (let i = 0; i < bytes.byteLength; i++) { + s += string.fromCharCode(bytes[i]) + } + // eslint-disable-next-line no-undef + return btoa(s) +} +/* c8 ignore stop */ + +/** + * @param {Uint8Array} bytes + * @return {string} + */ +const toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64') + +/* c8 ignore start */ +/** + * @param {string} s + * @return {Uint8Array} + */ +const fromBase64Browser = s => { + // eslint-disable-next-line no-undef + const a = atob(s) + const bytes = createUint8ArrayFromLen(a.length) + for (let i = 0; i < a.length; i++) { + bytes[i] = a.charCodeAt(i) + } + return bytes +} +/* c8 ignore stop */ + +/** + * @param {string} s + */ +const fromBase64Node = s => { + const buf = Buffer.from(s, 'base64') + return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength) +} + +/* c8 ignore next */ +export const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node + +/* c8 ignore next */ +export const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node + +/** + * Implements base64url - see https://datatracker.ietf.org/doc/html/rfc4648#section-5 + * @param {Uint8Array} buf + */ +export const toBase64UrlEncoded = buf => toBase64(buf).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '') + +/** + * @param {string} base64 + */ +export const fromBase64UrlEncoded = base64 => fromBase64(base64.replaceAll('-', '+').replaceAll('_', '/')) + +/** + * Base64 is always a more efficient choice. This exists for utility purposes only. + * + * @param {Uint8Array} buf + */ +export const toHexString = buf => array.map(buf, b => b.toString(16).padStart(2, '0')).join('') + +/** + * Note: This function expects that the hex doesn't start with 0x.. + * + * @param {string} hex + */ +export const fromHexString = hex => { + const hlen = hex.length + const buf = new Uint8Array(math.ceil(hlen / 2)) + for (let i = 0; i < hlen; i += 2) { + buf[buf.length - i / 2 - 1] = Number.parseInt(hex.slice(hlen - i - 2, hlen - i), 16) + } + return buf +} + +/** + * Copy the content of an Uint8Array view to a new ArrayBuffer. + * + * @param {Uint8Array} uint8Array + * @return {Uint8Array} + */ +export const copyUint8Array = uint8Array => { + const newBuf = createUint8ArrayFromLen(uint8Array.byteLength) + newBuf.set(uint8Array) + return newBuf +} + +/** + * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type. + * See encoding.writeAny for more information. + * + * @param {any} data + * @return {Uint8Array} + */ +export const encodeAny = data => + encoding.encode(encoder => encoding.writeAny(encoder, data)) + +/** + * Decode an any-encoded value. + * + * @param {Uint8Array} buf + * @return {any} + */ +export const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf)) + +/** + * Shift Byte Array {N} bits to the left. Does not expand byte array. + * + * @param {Uint8Array} bs + * @param {number} N should be in the range of [0-7] + */ +export const shiftNBitsLeft = (bs, N) => { + if (N === 0) return bs + bs = new Uint8Array(bs) + bs[0] <<= N + for (let i = 1; i < bs.length; i++) { + bs[i - 1] |= bs[i] >>> (8 - N) + bs[i] <<= N + } + return bs +} diff --git a/nodejs/node_modules/lib0/buffer.test.d.ts b/nodejs/node_modules/lib0/buffer.test.d.ts new file mode 100644 index 00000000..0bd7014c --- /dev/null +++ b/nodejs/node_modules/lib0/buffer.test.d.ts @@ -0,0 +1,6 @@ +export function testRepeatBase64urlEncoding(tc: t.TestCase): void; +export function testRepeatBase64Encoding(tc: t.TestCase): void; +export function testRepeatHexEncoding(tc: t.TestCase): void; +export function testAnyEncoding(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=buffer.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/buffer.test.d.ts.map b/nodejs/node_modules/lib0/buffer.test.d.ts.map new file mode 100644 index 00000000..c4ee1797 --- /dev/null +++ b/nodejs/node_modules/lib0/buffer.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.test.d.ts","sourceRoot":"","sources":["buffer.test.js"],"names":[],"mappings":"AA2BO,gDAFI,EAAE,QAAQ,QAIpB;AAKM,6CAFI,EAAE,QAAQ,QAIpB;AAKM,0CAFI,EAAE,QAAQ,QAIpB;AAKM,qCAFI,EAAE,QAAQ,QAMpB;mBApDkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/cache.d.ts b/nodejs/node_modules/lib0/cache.d.ts new file mode 100644 index 00000000..afcd5643 --- /dev/null +++ b/nodejs/node_modules/lib0/cache.d.ts @@ -0,0 +1,52 @@ +/** + * @template K, V + */ +export class Cache { + /** + * @param {number} timeout + */ + constructor(timeout: number); + timeout: number; + /** + * @type list.List> + */ + _q: list.List>; + /** + * @type {Map>} + */ + _map: Map>; +} +export function removeStale(cache: Cache): number; +export function set(cache: Cache, key: K, value: V): void; +export function get(cache: Cache, key: K): V | undefined; +export function refreshTimeout(cache: Cache, key: K): void; +export function getAsync(cache: Cache, key: K): V | Promise | undefined; +export function remove(cache: Cache, key: K): NonNullable | undefined; +export function setIfUndefined(cache: Cache, key: K, init: () => Promise, removeNull?: boolean): V | Promise; +export function create(timeout: number): Cache; +import * as list from './list.js'; +/** + * @template K, V + * + * @implements {list.ListNode} + */ +declare class Entry implements list.ListNode { + /** + * @param {K} key + * @param {V | Promise} val + */ + constructor(key: K, val: V | Promise); + /** + * @type {this | null} + */ + prev: Entry | null; + /** + * @type {this | null} + */ + next: Entry | null; + created: number; + val: V | Promise; + key: K; +} +export {}; +//# sourceMappingURL=cache.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/cache.d.ts.map b/nodejs/node_modules/lib0/cache.d.ts.map new file mode 100644 index 00000000..3f36948b --- /dev/null +++ b/nodejs/node_modules/lib0/cache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["cache.js"],"names":[],"mappings":"AAqCA;;GAEG;AACH;IACE;;OAEG;IACH,qBAFW,MAAM,EAYhB;IATC,gBAAsB;IACtB;;OAEG;IACH,IAFS,KAAK,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAER;IACvB;;OAEG;IACH,MAFU,IAAI,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAEL;CAE3B;AAQM,uDAFK,MAAM,CAUjB;AASM,sEAcN;AAwBM,qEAGN;AAQM,uEASN;AAYM,uFAGN;AAQM,qFAON;AAWM,sGAHI,OAAO,kBAwBjB;AAKM,gCAFI,MAAM,mBAEkC;sBArM7B,WAAW;AAIjC;;;;GAIG;AACH,qCAFgB,IAAI,CAAC,QAAQ;IAG3B;;;OAGG;IACH,iBAHW,CAAC,OACD,CAAC,GAAG,QAAQ,CAAC,CAAC,EAcxB;IAXC;;OAEG;IACH,yBAAgB;IAChB;;OAEG;IACH,yBAAgB;IAChB,gBAAiC;IACjC,oBAAc;IACd,OAAc;CAEjB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/cache.js b/nodejs/node_modules/lib0/cache.js new file mode 100644 index 00000000..6bb716a4 --- /dev/null +++ b/nodejs/node_modules/lib0/cache.js @@ -0,0 +1,206 @@ +/* eslint-env browser */ + +/** + * An implementation of a map which has keys that expire. + * + * @module cache + */ + +import * as list from './list.js' +import * as map from './map.js' +import * as time from './time.js' + +/** + * @template K, V + * + * @implements {list.ListNode} + */ +class Entry { + /** + * @param {K} key + * @param {V | Promise} val + */ + constructor (key, val) { + /** + * @type {this | null} + */ + this.prev = null + /** + * @type {this | null} + */ + this.next = null + this.created = time.getUnixTime() + this.val = val + this.key = key + } +} + +/** + * @template K, V + */ +export class Cache { + /** + * @param {number} timeout + */ + constructor (timeout) { + this.timeout = timeout + /** + * @type list.List> + */ + this._q = list.create() + /** + * @type {Map>} + */ + this._map = map.create() + } +} + +/** + * @template K, V + * + * @param {Cache} cache + * @return {number} Returns the current timestamp + */ +export const removeStale = cache => { + const now = time.getUnixTime() + const q = cache._q + while (q.start && now - q.start.created > cache.timeout) { + cache._map.delete(q.start.key) + list.popFront(q) + } + return now +} + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @param {V} value + */ +export const set = (cache, key, value) => { + const now = removeStale(cache) + const q = cache._q + const n = cache._map.get(key) + if (n) { + list.removeNode(q, n) + list.pushEnd(q, n) + n.created = now + n.val = value + } else { + const node = new Entry(key, value) + list.pushEnd(q, node) + cache._map.set(key, node) + } +} + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @return {Entry | undefined} + */ +const getNode = (cache, key) => { + removeStale(cache) + const n = cache._map.get(key) + if (n) { + return n + } +} + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @return {V | undefined} + */ +export const get = (cache, key) => { + const n = getNode(cache, key) + return n && !(n.val instanceof Promise) ? n.val : undefined +} + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + */ +export const refreshTimeout = (cache, key) => { + const now = time.getUnixTime() + const q = cache._q + const n = cache._map.get(key) + if (n) { + list.removeNode(q, n) + list.pushEnd(q, n) + n.created = now + } +} + +/** + * Works well in conjunktion with setIfUndefined which has an async init function. + * Using getAsync & setIfUndefined ensures that the init function is only called once. + * + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @return {V | Promise | undefined} + */ +export const getAsync = (cache, key) => { + const n = getNode(cache, key) + return n ? n.val : undefined +} + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + */ +export const remove = (cache, key) => { + const n = cache._map.get(key) + if (n) { + list.removeNode(cache._q, n) + cache._map.delete(key) + return n.val && !(n.val instanceof Promise) ? n.val : undefined + } +} + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @param {function():Promise} init + * @param {boolean} removeNull Optional argument that automatically removes values that resolve to null/undefined from the cache. + * @return {Promise | V} + */ +export const setIfUndefined = (cache, key, init, removeNull = false) => { + removeStale(cache) + const q = cache._q + const n = cache._map.get(key) + if (n) { + return n.val + } else { + const p = init() + const node = new Entry(key, p) + list.pushEnd(q, node) + cache._map.set(key, node) + p.then(v => { + if (p === node.val) { + node.val = v + } + if (removeNull && v == null) { + remove(cache, key) + } + }) + return p + } +} + +/** + * @param {number} timeout + */ +export const create = timeout => new Cache(timeout) diff --git a/nodejs/node_modules/lib0/cache.test.d.ts b/nodejs/node_modules/lib0/cache.test.d.ts new file mode 100644 index 00000000..693e0d4b --- /dev/null +++ b/nodejs/node_modules/lib0/cache.test.d.ts @@ -0,0 +1,3 @@ +export function testCache(tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=cache.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/cache.test.d.ts.map b/nodejs/node_modules/lib0/cache.test.d.ts.map new file mode 100644 index 00000000..c7782063 --- /dev/null +++ b/nodejs/node_modules/lib0/cache.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.test.d.ts","sourceRoot":"","sources":["cache.test.js"],"names":[],"mappings":"AAOO,8BAFI,EAAE,QAAQ,iBA6EpB;mBAlFkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/component.d.ts b/nodejs/node_modules/lib0/component.d.ts new file mode 100644 index 00000000..2f0e2b98 --- /dev/null +++ b/nodejs/node_modules/lib0/component.d.ts @@ -0,0 +1,86 @@ +/** + * @type {CustomElementRegistry} + */ +export const registry: CustomElementRegistry; +export function define(name: string, constr: any, opts?: ElementDefinitionOptions | undefined): void; +export function whenDefined(name: string): Promise; +/** + * @template S + */ +export class Lib0Component extends HTMLElement { + /** + * @param {S} [state] + */ + constructor(state?: S | undefined); + /** + * @type {S|null} + */ + state: S | null; + /** + * @type {any} + */ + _internal: any; + /** + * @param {S} _state + * @param {boolean} [_forceStateUpdate] Force that the state is rerendered even if state didn't change + */ + setState(_state: S, _forceStateUpdate?: boolean | undefined): void; + /** + * @param {any} _stateUpdate + */ + updateState(_stateUpdate: any): void; +} +export function createComponent(name: string, { template, style, state: defaultState, onStateChange, childStates, attrs, listeners, slots }: CONF): typeof Lib0Component; +export function createComponentDefiner(definer: Function): () => any; +export function defineListComponent(): any; +export function defineLazyLoadingComponent(): any; +export type CONF = { + /** + * Template for the shadow dom. + */ + template?: string | null | undefined; + /** + * shadow dom style. Is only used when + * `CONF.template` is defined + */ + style?: string | undefined; + /** + * Initial component state. + */ + state?: S | undefined; + /** + * Called when + * the state changes. + */ + onStateChange?: ((arg0: S, arg1: S | null, arg2: Lib0Component) => void) | undefined; + /** + * maps from + * CSS-selector to transformer function. The first element that matches the + * CSS-selector receives state updates via the transformer function. + */ + childStates?: { + [x: string]: (arg0: any, arg1: any) => Object; + } | undefined; + /** + * attrs-keys and state-keys should be camelCase, but the DOM uses kebap-case. I.e. + * `attrs = { myAttr: 4 }` is represeted as `` in the DOM + */ + attrs?: { + [x: string]: "string" | "number" | "json" | "bool"; + } | undefined; + /** + * Maps from dom-event-name + * to event listener. + */ + listeners?: { + [x: string]: (arg0: CustomEvent, arg1: Lib0Component) => boolean | void; + } | undefined; + /** + * Fill slots + * automatically when state changes. Maps from slot-name to slot-html. + */ + slots?: ((arg0: S, arg1: S, arg2: Lib0Component) => { + [x: string]: string; + }) | undefined; +}; +//# sourceMappingURL=component.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/component.d.ts.map b/nodejs/node_modules/lib0/component.d.ts.map new file mode 100644 index 00000000..0815a1f2 --- /dev/null +++ b/nodejs/node_modules/lib0/component.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"component.d.ts","sourceRoot":"","sources":["component.js"],"names":[],"mappings":"AAiBA;;GAEG;AACH,uBAFU,qBAAqB,CAEO;AAO/B,6BAJI,MAAM,UACN,GAAG,qDAGmE;AAM1E,kCAHI,MAAM,GACL,QAAQ,wBAAwB,CAAC,CAEgB;AAM7D;;GAEG;AACH;IACE;;OAEG;IACH,mCAUC;IARC;;OAEG;IACH,OAFU,CAAC,GAAC,IAAI,CAEuB;IACvC;;OAEG;IACH,WAFU,GAAG,CAEM;IAGrB;;;OAGG;IACH,iBAHW,CAAC,iDAGkC;IAE9C;;QAEI;IACJ,0BAFY,GAAG,QAEe;CAC/B;AA6DM,yCAJI,MAAM,2GAEL,oBAAoB,CAuM/B;AAKM,qEAWN;AANQ,2CAKN;AALM,kDAKN;;;;;;;;;;;;;;;;;;;4BAzOoB,CAAC,QAAC,CAAC,GAAC,IAAI,QAAC,cAAc,CAAC,CAAC,KAAE,IAAI;;;;;;;4BAEjB,GAAG,QAAE,GAAG,KAAE,MAAM;;;;;;;;;;;;;;4BAMf,WAAW,QAAE,cAAc,GAAG,CAAC,KAAE,OAAO,GAAC,IAAI;;;;;;oBAE5D,CAAC,QAAE,CAAC,QAAE,cAAc,CAAC,CAAC;YAAS,MAAM,GAAC,MAAM"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/component.js b/nodejs/node_modules/lib0/component.js new file mode 100644 index 00000000..e8e51d93 --- /dev/null +++ b/nodejs/node_modules/lib0/component.js @@ -0,0 +1,414 @@ +/* eslint-env browser */ + +/** + * Web components. + * + * @module component + */ + +import * as dom from './dom.js' +import * as diff from './diff.js' +import * as object from './object.js' +import * as json from './json.js' +import * as string from './string.js' +import * as array from './array.js' +import * as number from './number.js' +import * as func from './function.js' + +/** + * @type {CustomElementRegistry} + */ +export const registry = customElements + +/** + * @param {string} name + * @param {any} constr + * @param {ElementDefinitionOptions} [opts] + */ +export const define = (name, constr, opts) => registry.define(name, constr, opts) + +/** + * @param {string} name + * @return {Promise} + */ +export const whenDefined = name => registry.whenDefined(name) + +const upgradedEventName = 'upgraded' +const connectedEventName = 'connected' +const disconnectedEventName = 'disconnected' + +/** + * @template S + */ +export class Lib0Component extends HTMLElement { + /** + * @param {S} [state] + */ + constructor (state) { + super() + /** + * @type {S|null} + */ + this.state = /** @type {any} */ (state) + /** + * @type {any} + */ + this._internal = {} + } + + /** + * @param {S} _state + * @param {boolean} [_forceStateUpdate] Force that the state is rerendered even if state didn't change + */ + setState (_state, _forceStateUpdate = true) {} + + /** + * @param {any} _stateUpdate + */ + updateState (_stateUpdate) { } +} + +/** + * @param {any} val + * @param {"json"|"string"|"number"} type + * @return {string} + */ +const encodeAttrVal = (val, type) => { + if (type === 'json') { + val = json.stringify(val) + } + return val + '' +} + +/** + * @param {any} val + * @param {"json"|"string"|"number"|"bool"} type + * @return {any} + */ +const parseAttrVal = (val, type) => { + switch (type) { + case 'json': + return json.parse(val) + case 'number': + return Number.parseFloat(val) + case 'string': + return val + case 'bool': + return val != null + default: + return null + } +} + +/** + * @typedef {Object} CONF + * @property {string?} [CONF.template] Template for the shadow dom. + * @property {string} [CONF.style] shadow dom style. Is only used when + * `CONF.template` is defined + * @property {S} [CONF.state] Initial component state. + * @property {function(S,S|null,Lib0Component):void} [CONF.onStateChange] Called when + * the state changes. + * @property {Object} [CONF.childStates] maps from + * CSS-selector to transformer function. The first element that matches the + * CSS-selector receives state updates via the transformer function. + * @property {Object} [CONF.attrs] + * attrs-keys and state-keys should be camelCase, but the DOM uses kebap-case. I.e. + * `attrs = { myAttr: 4 }` is represeted as `` in the DOM + * @property {Object):boolean|void>} [CONF.listeners] Maps from dom-event-name + * to event listener. + * @property {function(S, S, Lib0Component):Object} [CONF.slots] Fill slots + * automatically when state changes. Maps from slot-name to slot-html. + * @template S + */ + +/** + * @template T + * @param {string} name + * @param {CONF} cnf + * @return {typeof Lib0Component} + */ +export const createComponent = (name, { template, style = '', state: defaultState, onStateChange = () => {}, childStates = { }, attrs = {}, listeners = {}, slots = () => ({}) }) => { + /** + * Maps from camelCase attribute name to kebap-case attribute name. + * @type {Object} + */ + const normalizedAttrs = {} + for (const key in attrs) { + normalizedAttrs[string.fromCamelCase(key, '-')] = key + } + const templateElement = template + ? /** @type {HTMLTemplateElement} */ (dom.parseElement(` + + `)) + : null + + class _Lib0Component extends HTMLElement { + /** + * @param {T} [state] + */ + constructor (state) { + super() + /** + * @type {Array<{d:Lib0Component, s:function(any, any):Object}>} + */ + this._childStates = [] + /** + * @type {Object} + */ + this._slots = {} + this._init = false + /** + * @type {any} + */ + this._internal = {} + /** + * @type {any} + */ + this.state = state || null + this.connected = false + // init shadow dom + if (templateElement) { + const shadow = /** @type {ShadowRoot} */ (this.attachShadow({ mode: 'open' })) + shadow.appendChild(templateElement.content.cloneNode(true)) + // fill child states + for (const key in childStates) { + this._childStates.push({ + d: /** @type {Lib0Component} */ (dom.querySelector(/** @type {any} */ (shadow), key)), + s: childStates[key] + }) + } + } + dom.emitCustomEvent(this, upgradedEventName, { bubbles: true }) + } + + connectedCallback () { + this.connected = true + if (!this._init) { + this._init = true + const shadow = this.shadowRoot + if (shadow) { + dom.addEventListener(shadow, upgradedEventName, event => { + this.setState(this.state, true) + event.stopPropagation() + }) + } + /** + * @type {Object} + */ + const startState = this.state || object.assign({}, defaultState) + if (attrs) { + for (const key in attrs) { + const normalizedKey = string.fromCamelCase(key, '-') + const val = parseAttrVal(this.getAttribute(normalizedKey), attrs[key]) + if (val) { + startState[key] = val + } + } + } + // add event listeners + for (const key in listeners) { + dom.addEventListener(shadow || this, key, event => { + if (listeners[key](/** @type {CustomEvent} */ (event), this) !== false) { + event.stopPropagation() + event.preventDefault() + return false + } + }) + } + // first setState call + this.state = null + this.setState(startState) + } + dom.emitCustomEvent(/** @type {any} */ (this.shadowRoot || this), connectedEventName, { bubbles: true }) + } + + disconnectedCallback () { + this.connected = false + dom.emitCustomEvent(/** @type {any} */ (this.shadowRoot || this), disconnectedEventName, { bubbles: true }) + this.setState(null) + } + + static get observedAttributes () { + return object.keys(normalizedAttrs) + } + + /** + * @param {string} name + * @param {string} oldVal + * @param {string} newVal + * + * @private + */ + attributeChangedCallback (name, oldVal, newVal) { + const curState = /** @type {any} */ (this.state) + const camelAttrName = normalizedAttrs[name] + const type = attrs[camelAttrName] + const parsedVal = parseAttrVal(newVal, type) + if (curState && (type !== 'json' || json.stringify(curState[camelAttrName]) !== newVal) && curState[camelAttrName] !== parsedVal && !number.isNaN(parsedVal)) { + this.updateState({ [camelAttrName]: parsedVal }) + } + } + + /** + * @param {any} stateUpdate + */ + updateState (stateUpdate) { + this.setState(object.assign({}, this.state, stateUpdate)) + } + + /** + * @param {any} state + */ + setState (state, forceStateUpdates = false) { + const prevState = this.state + this.state = state + if (this._init && (!func.equalityFlat(state, prevState) || forceStateUpdates)) { + // fill slots + if (state) { + const slotElems = slots(state, prevState, this) + for (const key in slotElems) { + const slotContent = slotElems[key] + if (this._slots[key] !== slotContent) { + this._slots[key] = slotContent + const currentSlots = /** @type {Array} */ (key !== 'default' ? array.from(dom.querySelectorAll(this, `[slot="${key}"]`)) : array.from(this.childNodes).filter(/** @param {any} child */ child => !dom.checkNodeType(child, dom.ELEMENT_NODE) || !child.hasAttribute('slot'))) + currentSlots.slice(1).map(dom.remove) + const nextSlot = dom.parseFragment(slotContent) + if (key !== 'default') { + array.from(nextSlot.children).forEach(c => c.setAttribute('slot', key)) + } + if (currentSlots.length > 0) { + dom.replaceWith(currentSlots[0], nextSlot) + } else { + dom.appendChild(this, nextSlot) + } + } + } + } + onStateChange(state, prevState, this) + if (state != null) { + this._childStates.forEach(cnf => { + const d = cnf.d + if (d.updateState) { + d.updateState(cnf.s(state, this)) + } + }) + } + for (const key in attrs) { + const normalizedKey = string.fromCamelCase(key, '-') + if (state == null) { + this.removeAttribute(normalizedKey) + } else { + const stateVal = state[key] + const attrsType = attrs[key] + if (!prevState || prevState[key] !== stateVal) { + if (attrsType === 'bool') { + if (stateVal) { + this.setAttribute(normalizedKey, '') + } else { + this.removeAttribute(normalizedKey) + } + } else if (stateVal == null && (attrsType === 'string' || attrsType === 'number')) { + this.removeAttribute(normalizedKey) + } else { + this.setAttribute(normalizedKey, encodeAttrVal(stateVal, attrsType)) + } + } + } + } + } + } + } + define(name, _Lib0Component) + // @ts-ignore + return _Lib0Component +} + +/** + * @param {function} definer function that defines a component when executed + */ +export const createComponentDefiner = definer => { + /** + * @type {any} + */ + let defined = null + return () => { + if (!defined) { + defined = definer() + } + return defined + } +} + +export const defineListComponent = createComponentDefiner(() => { + const ListItem = createComponent('lib0-list-item', { + template: '', + slots: state => ({ + content: `
${state}
` + }) + }) + return createComponent('lib0-list', { + state: { list: /** @type {Array} */ ([]), Item: ListItem }, + onStateChange: (state, prevState, component) => { + if (state == null) { + return + } + const { list = /** @type {Array} */ ([]), Item = ListItem } = state + // @todo deep compare here by providing another parameter to simpleDiffArray + let { index, remove, insert } = diff.simpleDiffArray(prevState ? prevState.list : [], list, func.equalityFlat) + if (remove === 0 && insert.length === 0) { + return + } + let child = /** @type {Lib0Component} */ (component.firstChild) + while (index-- > 0) { + child = /** @type {Lib0Component} */ (child.nextElementSibling) + } + let insertStart = 0 + while (insertStart < insert.length && remove-- > 0) { + // update existing state + child.setState(insert[insertStart++]) + child = /** @type {Lib0Component} */ (child.nextElementSibling) + } + while (remove-- > 0) { + // remove remaining + const prevChild = child + child = /** @type {Lib0Component} */ (child.nextElementSibling) + component.removeChild(prevChild) + } + // insert remaining + component.insertBefore(dom.fragment(insert.slice(insertStart).map(/** @param {any} insState */ insState => { + const el = new Item() + el.setState(insState) + return el + })), child) + } + }) +}) + +export const defineLazyLoadingComponent = createComponentDefiner(() => createComponent('lib0-lazy', { + state: /** @type {{component:null|String,import:null|function():Promise,state:null|object}} */ ({ + component: null, import: null, state: null + }), + attrs: { + component: 'string' + }, + onStateChange: ({ component, state, import: getImport }, prevState, componentEl) => { + if (component !== null) { + if (getImport) { + getImport() + } + if (!prevState || component !== prevState.component) { + const el = /** @type {any} */ (dom.createElement(component)) + componentEl.innerHTML = '' + componentEl.insertBefore(el, null) + } + const el = /** @type {any} */ (componentEl.firstElementChild) + // @todo generalize setting state and check if setState is defined + if (el.setState) { + el.setState(state) + } + } + } +})) diff --git a/nodejs/node_modules/lib0/conditions.d.ts b/nodejs/node_modules/lib0/conditions.d.ts new file mode 100644 index 00000000..0ed4306a --- /dev/null +++ b/nodejs/node_modules/lib0/conditions.d.ts @@ -0,0 +1,2 @@ +export function undefinedToNull(v: T | null | undefined): T | null; +//# sourceMappingURL=conditions.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/conditions.d.ts.map b/nodejs/node_modules/lib0/conditions.d.ts.map new file mode 100644 index 00000000..700db839 --- /dev/null +++ b/nodejs/node_modules/lib0/conditions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"conditions.d.ts","sourceRoot":"","sources":["conditions.js"],"names":[],"mappings":"AAYO,sEAAuD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/conditions.js b/nodejs/node_modules/lib0/conditions.js new file mode 100644 index 00000000..f348e8af --- /dev/null +++ b/nodejs/node_modules/lib0/conditions.js @@ -0,0 +1,13 @@ +/** + * Often used conditions. + * + * @module conditions + */ + +/** + * @template T + * @param {T|null|undefined} v + * @return {T|null} + */ +/* c8 ignore next */ +export const undefinedToNull = v => v === undefined ? null : v diff --git a/nodejs/node_modules/lib0/coverage/tmp/coverage-45503-1710701602083-0.json b/nodejs/node_modules/lib0/coverage/tmp/coverage-45503-1710701602083-0.json new file mode 100644 index 00000000..02da5240 --- /dev/null +++ b/nodejs/node_modules/lib0/coverage/tmp/coverage-45503-1710701602083-0.json @@ -0,0 +1 @@ +{"result":[{"scriptId":"6","url":"node:internal/per_context/primordials","functions":[{"functionName":"SafeIterator","ranges":[{"startOffset":9499,"endOffset":9570,"count":44762}],"isBlockCoverage":true},{"functionName":"next","ranges":[{"startOffset":9575,"endOffset":9624,"count":95521}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9629,"endOffset":9674,"count":44292}],"isBlockCoverage":true},{"functionName":"desc.value","ranges":[{"startOffset":11239,"endOffset":11306,"count":470}],"isBlockCoverage":true},{"functionName":"SafeMap","ranges":[{"startOffset":11964,"endOffset":11992,"count":111}],"isBlockCoverage":false},{"functionName":"SafeWeakMap","ranges":[{"startOffset":12136,"endOffset":12164,"count":1}],"isBlockCoverage":false},{"functionName":"SafeSet","ranges":[{"startOffset":12293,"endOffset":12321,"count":142}],"isBlockCoverage":false},{"functionName":"SafeFinalizationRegistry","ranges":[{"startOffset":12745,"endOffset":12801,"count":2}],"isBlockCoverage":true},{"functionName":"SafeWeakRef","ranges":[{"startOffset":12954,"endOffset":12992,"count":2}],"isBlockCoverage":true},{"functionName":"SafePromise","ranges":[{"startOffset":13140,"endOffset":13182,"count":540}],"isBlockCoverage":true},{"functionName":"primordials.SafePromisePrototypeFinally","ranges":[{"startOffset":13686,"endOffset":13960,"count":90}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":13831,"endOffset":13955,"count":90}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":13861,"endOffset":13910,"count":90}],"isBlockCoverage":true},{"functionName":"primordials.SafePromiseAllReturnArrayLike","ranges":[{"startOffset":15280,"endOffset":15836,"count":92}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":15315,"endOffset":15835,"count":92},{"startOffset":15485,"endOffset":15504,"count":15},{"startOffset":15577,"endOffset":15831,"count":285},{"startOffset":15615,"endOffset":15638,"count":0},{"startOffset":15831,"endOffset":15834,"count":285}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":15706,"endOffset":15815,"count":285},{"startOffset":15788,"endOffset":15807,"count":77}],"isBlockCoverage":true},{"functionName":"primordials.SafePromiseAllReturnVoid","ranges":[{"startOffset":16178,"endOffset":16580,"count":185}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":16213,"endOffset":16579,"count":185},{"startOffset":16310,"endOffset":16320,"count":31},{"startOffset":16367,"endOffset":16575,"count":570},{"startOffset":16405,"endOffset":16428,"count":285},{"startOffset":16429,"endOffset":16442,"count":285},{"startOffset":16575,"endOffset":16578,"count":570}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":16496,"endOffset":16559,"count":570},{"startOffset":16541,"endOffset":16551,"count":154}],"isBlockCoverage":true}]},{"scriptId":"7","url":"node:internal/per_context/domexception","functions":[{"functionName":"DOMException","ranges":[{"startOffset":1102,"endOffset":1728,"count":2},{"startOffset":1232,"endOffset":1724,"count":1}],"isBlockCoverage":true}]},{"scriptId":"9","url":"node:internal/bootstrap/realm","functions":[{"functionName":"internalBinding","ranges":[{"startOffset":6005,"endOffset":6267,"count":76}],"isBlockCoverage":false},{"functionName":"getOwn","ranges":[{"startOffset":6427,"endOffset":6581,"count":154},{"startOffset":6563,"endOffset":6578,"count":0}],"isBlockCoverage":true},{"functionName":"canBeRequiredByUsers","ranges":[{"startOffset":9394,"endOffset":9469,"count":4}],"isBlockCoverage":true},{"functionName":"canBeRequiredWithoutScheme","ranges":[{"startOffset":9480,"endOffset":9574,"count":15}],"isBlockCoverage":true},{"functionName":"getCanBeRequiredByUsersWithoutSchemeList","ranges":[{"startOffset":10193,"endOffset":10302,"count":1}],"isBlockCoverage":true},{"functionName":"compileForPublicLoader","ranges":[{"startOffset":10460,"endOffset":11172,"count":2},{"startOffset":10541,"endOffset":10733,"count":0},{"startOffset":11056,"endOffset":11060,"count":0}],"isBlockCoverage":true},{"functionName":"getESMFacade","ranges":[{"startOffset":11176,"endOffset":11938,"count":4},{"startOffset":11214,"endOffset":11937,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":11675,"endOffset":11778,"count":2}],"isBlockCoverage":true},{"functionName":"syncExports","ranges":[{"startOffset":12234,"endOffset":12578,"count":4},{"startOffset":12353,"endOffset":12568,"count":154},{"startOffset":12430,"endOffset":12439,"count":0}],"isBlockCoverage":true},{"functionName":"compileForInternalLoader","ranges":[{"startOffset":12582,"endOffset":13404,"count":1649}],"isBlockCoverage":false},{"functionName":"requireBuiltin","ranges":[{"startOffset":13599,"endOffset":13964,"count":1649}],"isBlockCoverage":false}]},{"scriptId":"10","url":"node:internal/errors","functions":[{"functionName":"hideStackFrames","ranges":[{"startOffset":13191,"endOffset":13456,"count":3}],"isBlockCoverage":false}]},{"scriptId":"11","url":"node:internal/assert","functions":[{"functionName":"assert","ranges":[{"startOffset":157,"endOffset":307,"count":663},{"startOffset":205,"endOffset":305,"count":0}],"isBlockCoverage":true}]},{"scriptId":"12","url":"node:internal/bootstrap/node","functions":[{"functionName":"get","ranges":[{"startOffset":3830,"endOffset":3880,"count":34}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":3886,"endOffset":3944,"count":2}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4086,"endOffset":4122,"count":2}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":4128,"endOffset":4547,"count":2},{"startOffset":4187,"endOffset":4469,"count":1},{"startOffset":4252,"endOffset":4266,"count":0},{"startOffset":4267,"endOffset":4315,"count":0},{"startOffset":4317,"endOffset":4352,"count":0},{"startOffset":4469,"endOffset":4518,"count":1}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":12772,"endOffset":12808,"count":11}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":13678,"endOffset":13713,"count":25728}],"isBlockCoverage":true}]},{"scriptId":"13","url":"node:internal/timers","functions":[{"functionName":"","ranges":[{"startOffset":4385,"endOffset":4410,"count":1}],"isBlockCoverage":true},{"functionName":"initAsyncResource","ranges":[{"startOffset":5548,"endOffset":5826,"count":24},{"startOffset":5774,"endOffset":5824,"count":0}],"isBlockCoverage":true},{"functionName":"Timeout","ranges":[{"startOffset":5932,"endOffset":6978,"count":24},{"startOffset":6054,"endOffset":6077,"count":20},{"startOffset":6080,"endOffset":6432,"count":4},{"startOffset":6113,"endOffset":6358,"count":0},{"startOffset":6789,"endOffset":6796,"count":7},{"startOffset":6797,"endOffset":6803,"count":17}],"isBlockCoverage":true},{"functionName":"TimersList","ranges":[{"startOffset":7720,"endOffset":8026,"count":23}],"isBlockCoverage":true},{"functionName":"incRefCount","ranges":[{"startOffset":9403,"endOffset":9569,"count":24},{"startOffset":9458,"endOffset":9567,"count":13}],"isBlockCoverage":true},{"functionName":"decRefCount","ranges":[{"startOffset":9571,"endOffset":9738,"count":8},{"startOffset":9626,"endOffset":9736,"count":6}],"isBlockCoverage":true},{"functionName":"insert","ranges":[{"startOffset":10887,"endOffset":11626,"count":135},{"startOffset":11218,"endOffset":11599,"count":23},{"startOffset":11453,"endOffset":11595,"count":16}],"isBlockCoverage":true},{"functionName":"compareTimersLists","ranges":[{"startOffset":12483,"endOffset":12688,"count":111},{"startOffset":12585,"endOffset":12665,"count":6},{"startOffset":12614,"endOffset":12624,"count":0},{"startOffset":12665,"endOffset":12687,"count":105}],"isBlockCoverage":true},{"functionName":"setPosition","ranges":[{"startOffset":12690,"endOffset":12761,"count":150}],"isBlockCoverage":true},{"functionName":"processTimers","ranges":[{"startOffset":15013,"endOffset":15503,"count":126},{"startOffset":15213,"endOffset":15485,"count":247},{"startOffset":15244,"endOffset":15349,"count":115},{"startOffset":15327,"endOffset":15340,"count":0},{"startOffset":15349,"endOffset":15387,"count":132},{"startOffset":15387,"endOffset":15402,"count":6},{"startOffset":15402,"endOffset":15447,"count":126},{"startOffset":15447,"endOffset":15485,"count":131},{"startOffset":15485,"endOffset":15502,"count":10}],"isBlockCoverage":true},{"functionName":"listOnTimeout","ranges":[{"startOffset":15507,"endOffset":18081,"count":131},{"startOffset":15710,"endOffset":17536,"count":242},{"startOffset":15931,"endOffset":16159,"count":111},{"startOffset":16159,"endOffset":16199,"count":131},{"startOffset":16199,"endOffset":16214,"count":0},{"startOffset":16214,"endOffset":16416,"count":131},{"startOffset":16416,"endOffset":16651,"count":0},{"startOffset":16651,"endOffset":16762,"count":131},{"startOffset":16762,"endOffset":16884,"count":116},{"startOffset":16884,"endOffset":16998,"count":131},{"startOffset":16998,"endOffset":17066,"count":0},{"startOffset":17075,"endOffset":17503,"count":131},{"startOffset":17111,"endOffset":17139,"count":116},{"startOffset":17141,"endOffset":17250,"count":111},{"startOffset":17250,"endOffset":17495,"count":20},{"startOffset":17319,"endOffset":17495,"count":15},{"startOffset":17464,"endOffset":17485,"count":0},{"startOffset":17503,"endOffset":17536,"count":131},{"startOffset":17536,"endOffset":18006,"count":20},{"startOffset":18006,"endOffset":18077,"count":15}],"isBlockCoverage":true}]},{"scriptId":"14","url":"node:internal/async_hooks","functions":[{"functionName":"newAsyncId","ranges":[{"startOffset":14549,"endOffset":14619,"count":57}],"isBlockCoverage":true},{"functionName":"getDefaultTriggerAsyncId","ranges":[{"startOffset":14994,"endOffset":15284,"count":57},{"startOffset":15250,"endOffset":15283,"count":0}],"isBlockCoverage":true},{"functionName":"hasHooks","ranges":[{"startOffset":16096,"endOffset":16159,"count":601}],"isBlockCoverage":true},{"functionName":"enabledHooksExist","ranges":[{"startOffset":16161,"endOffset":16220,"count":163}],"isBlockCoverage":true},{"functionName":"initHooksExist","ranges":[{"startOffset":16222,"endOffset":16277,"count":57}],"isBlockCoverage":true},{"functionName":"destroyHooksExist","ranges":[{"startOffset":16338,"endOffset":16399,"count":55}],"isBlockCoverage":true},{"functionName":"emitBeforeScript","ranges":[{"startOffset":16890,"endOffset":17066,"count":163},{"startOffset":17038,"endOffset":17064,"count":0}],"isBlockCoverage":true},{"functionName":"emitAfterScript","ranges":[{"startOffset":17069,"endOffset":17189,"count":163},{"startOffset":17133,"endOffset":17158,"count":0}],"isBlockCoverage":true},{"functionName":"pushAsyncContext","ranges":[{"startOffset":17534,"endOffset":18104,"count":163},{"startOffset":17754,"endOffset":17804,"count":0}],"isBlockCoverage":true},{"functionName":"popAsyncContext","ranges":[{"startOffset":18169,"endOffset":18780,"count":163},{"startOffset":18285,"endOffset":18298,"count":0},{"startOffset":18377,"endOffset":18483,"count":0}],"isBlockCoverage":true}]},{"scriptId":"15","url":"node:internal/validators","functions":[{"functionName":"parseFileMode","ranges":[{"startOffset":1629,"endOffset":1940,"count":90},{"startOffset":1722,"endOffset":1890,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2186,"endOffset":2567,"count":1},{"startOffset":2306,"endOffset":2360,"count":0},{"startOffset":2400,"endOffset":2454,"count":0},{"startOffset":2497,"endOffset":2563,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2811,"endOffset":3274,"count":18},{"startOffset":2983,"endOffset":3051,"count":0},{"startOffset":3085,"endOffset":3153,"count":0},{"startOffset":3190,"endOffset":3270,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3512,"endOffset":3944,"count":98},{"startOffset":3582,"endOffset":3646,"count":0},{"startOffset":3678,"endOffset":3742,"count":0},{"startOffset":3766,"endOffset":3769,"count":0},{"startOffset":3866,"endOffset":3942,"count":0}],"isBlockCoverage":true},{"functionName":"validateString","ranges":[{"startOffset":4097,"endOffset":4229,"count":6971}],"isBlockCoverage":false},{"functionName":"validateNumber","ranges":[{"startOffset":4430,"endOffset":4896,"count":459748},{"startOffset":4528,"endOffset":4582,"count":0},{"startOffset":4603,"endOffset":4617,"count":90},{"startOffset":4635,"endOffset":4649,"count":90},{"startOffset":4672,"endOffset":4686,"count":459658},{"startOffset":4688,"endOffset":4709,"count":90},{"startOffset":4712,"endOffset":4894,"count":0}],"isBlockCoverage":true},{"functionName":"validateBoolean","ranges":[{"startOffset":5571,"endOffset":5706,"count":1},{"startOffset":5649,"endOffset":5704,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6054,"endOffset":7073,"count":861},{"startOffset":6145,"endOffset":6385,"count":291},{"startOffset":6196,"endOffset":6268,"count":0},{"startOffset":6307,"endOffset":6379,"count":0},{"startOffset":6385,"endOffset":7069,"count":570},{"startOffset":6498,"endOffset":6515,"count":568},{"startOffset":6517,"endOffset":6589,"count":0},{"startOffset":6687,"endOffset":6709,"count":0},{"startOffset":6711,"endOffset":6783,"count":0},{"startOffset":6939,"endOffset":6989,"count":0},{"startOffset":6991,"endOffset":7063,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8027,"endOffset":8305,"count":11},{"startOffset":8089,"endOffset":8152,"count":0},{"startOffset":8185,"endOffset":8303,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12047,"endOffset":12264,"count":10},{"startOffset":12094,"endOffset":12190,"count":0},{"startOffset":12192,"endOffset":12262,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12464,"endOffset":12580,"count":1761}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":14312,"endOffset":14522,"count":116450},{"startOffset":14452,"endOffset":14520,"count":0}],"isBlockCoverage":true}]},{"scriptId":"16","url":"node:internal/util","functions":[{"functionName":"toUSVString","ranges":[{"startOffset":1790,"endOffset":2102,"count":284},{"startOffset":2059,"endOffset":2101,"count":0}],"isBlockCoverage":true},{"functionName":"isError","ranges":[{"startOffset":2289,"endOffset":2539,"count":1}],"isBlockCoverage":true},{"functionName":"getDeprecationWarningEmitter","ranges":[{"startOffset":2696,"endOffset":3345,"count":3}],"isBlockCoverage":false},{"functionName":"shouldEmitWarning","ranges":[{"startOffset":2795,"endOffset":2805,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2842,"endOffset":3342,"count":0}],"isBlockCoverage":false},{"functionName":"deprecate","ranges":[{"startOffset":4094,"endOffset":5092,"count":3}],"isBlockCoverage":false},{"functionName":"deprecated","ranges":[{"startOffset":4518,"endOffset":4704,"count":0}],"isBlockCoverage":false},{"functionName":"assertCrypto","ranges":[{"startOffset":5362,"endOffset":5436,"count":1},{"startOffset":5408,"endOffset":5434,"count":0}],"isBlockCoverage":true},{"functionName":"cachedResult","ranges":[{"startOffset":8159,"endOffset":8315,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8210,"endOffset":8312,"count":0}],"isBlockCoverage":false},{"functionName":"getCWDURL","ranges":[{"startOffset":10282,"endOffset":10792,"count":1},{"startOffset":10610,"endOffset":10659,"count":0}],"isBlockCoverage":true},{"functionName":"promisify","ranges":[{"startOffset":11158,"endOffset":13019,"count":8},{"startOffset":11278,"endOffset":11334,"count":1},{"startOffset":11421,"endOffset":11698,"count":0},{"startOffset":12805,"endOffset":12967,"count":23}],"isBlockCoverage":true},{"functionName":"fn","ranges":[{"startOffset":11898,"endOffset":12417,"count":16}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":11944,"endOffset":12411,"count":16}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":11998,"endOffset":12361,"count":16},{"startOffset":12037,"endOffset":12078,"count":0},{"startOffset":12119,"endOffset":12139,"count":8},{"startOffset":12141,"endOffset":12306,"count":8},{"startOffset":12238,"endOffset":12272,"count":16},{"startOffset":12306,"endOffset":12353,"count":8}],"isBlockCoverage":true},{"functionName":"join","ranges":[{"startOffset":13114,"endOffset":13436,"count":9},{"startOffset":13275,"endOffset":13386,"count":16}],"isBlockCoverage":true},{"functionName":"defineOperation","ranges":[{"startOffset":15693,"endOffset":15894,"count":1}],"isBlockCoverage":false},{"functionName":"exposeInterface","ranges":[{"startOffset":15946,"endOffset":16166,"count":1}],"isBlockCoverage":false},{"functionName":"defineLazyProperties","ranges":[{"startOffset":16665,"endOffset":17598,"count":1}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":16884,"endOffset":17027,"count":3}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":17130,"endOffset":17326,"count":3}],"isBlockCoverage":true},{"functionName":"defineReplaceableLazyAttribute","ranges":[{"startOffset":17600,"endOffset":18500,"count":1}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":17812,"endOffset":18048,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":18153,"endOffset":18224,"count":0}],"isBlockCoverage":false},{"functionName":"exposeLazyInterfaces","ranges":[{"startOffset":18502,"endOffset":18602,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":18793,"endOffset":18921,"count":2}],"isBlockCoverage":true},{"functionName":"setOwnProperty","ranges":[{"startOffset":19546,"endOffset":19736,"count":46319}],"isBlockCoverage":true},{"functionName":"setupCoverageHooks","ranges":[{"startOffset":22094,"endOffset":22771,"count":1},{"startOffset":22564,"endOffset":22741,"count":0}],"isBlockCoverage":true},{"functionName":"guessHandleType","ranges":[{"startOffset":22844,"endOffset":22941,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":22943,"endOffset":23487,"count":2}],"isBlockCoverage":false},{"functionName":"WeakReference","ranges":[{"startOffset":23018,"endOffset":23085,"count":2}],"isBlockCoverage":true},{"functionName":"incRef","ranges":[{"startOffset":23089,"endOffset":23307,"count":0}],"isBlockCoverage":false},{"functionName":"decRef","ranges":[{"startOffset":23311,"endOffset":23439,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":23443,"endOffset":23485,"count":0}],"isBlockCoverage":false}]},{"scriptId":"17","url":"node:internal/options","functions":[{"functionName":"getCLIOptionsFromBinding","ranges":[{"startOffset":464,"endOffset":598,"count":66},{"startOffset":521,"endOffset":575,"count":1}],"isBlockCoverage":true},{"functionName":"getEmbedderOptions","ranges":[{"startOffset":733,"endOffset":877,"count":4},{"startOffset":789,"endOffset":849,"count":1}],"isBlockCoverage":true},{"functionName":"refreshOptions","ranges":[{"startOffset":879,"endOffset":960,"count":1}],"isBlockCoverage":true},{"functionName":"getOptionValue","ranges":[{"startOffset":962,"endOffset":1228,"count":66},{"startOffset":1084,"endOffset":1185,"count":8},{"startOffset":1185,"endOffset":1225,"count":58}],"isBlockCoverage":true}]},{"scriptId":"18","url":"node:internal/util/types","functions":[{"functionName":"isTypedArray","ranges":[{"startOffset":131,"endOffset":234,"count":459389}],"isBlockCoverage":true},{"functionName":"isUint8Array","ranges":[{"startOffset":236,"endOffset":342,"count":2443769}],"isBlockCoverage":true},{"functionName":"isFloat32Array","ranges":[{"startOffset":1008,"endOffset":1118,"count":459384}],"isBlockCoverage":true},{"functionName":"isFloat64Array","ranges":[{"startOffset":1120,"endOffset":1230,"count":459384}],"isBlockCoverage":true}]},{"scriptId":"19","url":"node:internal/linkedlist","functions":[{"functionName":"peek","ranges":[{"startOffset":133,"endOffset":225,"count":262},{"startOffset":186,"endOffset":198,"count":20},{"startOffset":198,"endOffset":224,"count":242}],"isBlockCoverage":true},{"functionName":"remove","ranges":[{"startOffset":260,"endOffset":487,"count":163},{"startOffset":306,"endOffset":358,"count":158},{"startOffset":382,"endOffset":434,"count":158}],"isBlockCoverage":true},{"functionName":"append","ranges":[{"startOffset":543,"endOffset":995,"count":135},{"startOffset":594,"endOffset":611,"count":111},{"startOffset":613,"endOffset":636,"count":24}],"isBlockCoverage":true},{"functionName":"isEmpty","ranges":[{"startOffset":997,"endOffset":1057,"count":8}],"isBlockCoverage":true}]},{"scriptId":"20","url":"node:internal/priority_queue","functions":[{"functionName":"insert","ranges":[{"startOffset":692,"endOffset":875,"count":23},{"startOffset":826,"endOffset":843,"count":0}],"isBlockCoverage":true},{"functionName":"peek","ranges":[{"startOffset":879,"endOffset":917,"count":257}],"isBlockCoverage":true},{"functionName":"percolateDown","ranges":[{"startOffset":978,"endOffset":1642,"count":121},{"startOffset":1192,"endOffset":1551,"count":101},{"startOffset":1258,"endOffset":1305,"count":0},{"startOffset":1420,"endOffset":1426,"count":95},{"startOffset":1426,"endOffset":1551,"count":6}],"isBlockCoverage":true},{"functionName":"percolateUp","ranges":[{"startOffset":1646,"endOffset":2134,"count":23},{"startOffset":1821,"endOffset":2043,"count":10},{"startOffset":1915,"endOffset":2043,"count":0}],"isBlockCoverage":true},{"functionName":"removeAt","ranges":[{"startOffset":2138,"endOffset":2468,"count":22},{"startOffset":2296,"endOffset":2310,"count":10},{"startOffset":2312,"endOffset":2464,"count":10},{"startOffset":2332,"endOffset":2382,"count":0},{"startOffset":2392,"endOffset":2414,"count":0}],"isBlockCoverage":true},{"functionName":"shift","ranges":[{"startOffset":2472,"endOffset":2626,"count":15},{"startOffset":2573,"endOffset":2580,"count":0}],"isBlockCoverage":true}]},{"scriptId":"21","url":"node:internal/util/inspect","functions":[{"functionName":"isUndetectableObject","ranges":[{"startOffset":3640,"endOffset":3690,"count":9},{"startOffset":3672,"endOffset":3690,"count":0}],"isBlockCoverage":true},{"functionName":"inspect","ranges":[{"startOffset":9009,"endOffset":11035,"count":9},{"startOffset":9861,"endOffset":10057,"count":0},{"startOffset":10127,"endOffset":10163,"count":0},{"startOffset":10268,"endOffset":10802,"count":0},{"startOffset":10831,"endOffset":10862,"count":0},{"startOffset":10898,"endOffset":10928,"count":0},{"startOffset":10965,"endOffset":10996,"count":0}],"isBlockCoverage":true},{"functionName":"stylizeNoColor","ranges":[{"startOffset":17181,"endOffset":17227,"count":54}],"isBlockCoverage":true},{"functionName":"getEmptyFormatArray","ranges":[{"startOffset":17306,"endOffset":17353,"count":4}],"isBlockCoverage":true},{"functionName":"isInstanceof","ranges":[{"startOffset":17355,"endOffset":17473,"count":9},{"startOffset":17442,"endOffset":17471,"count":0}],"isBlockCoverage":true},{"functionName":"getConstructorName","ranges":[{"startOffset":17475,"endOffset":18744,"count":9},{"startOffset":17591,"endOffset":17619,"count":0},{"startOffset":17621,"endOffset":18260,"count":18},{"startOffset":17731,"endOffset":17780,"count":9},{"startOffset":17781,"endOffset":17820,"count":9},{"startOffset":17821,"endOffset":17867,"count":9},{"startOffset":17869,"endOffset":18152,"count":9},{"startOffset":17906,"endOffset":17993,"count":0},{"startOffset":17995,"endOffset":18102,"count":0},{"startOffset":18152,"endOffset":18256,"count":9},{"startOffset":18260,"endOffset":18413,"count":0},{"startOffset":18415,"endOffset":18743,"count":0}],"isBlockCoverage":true},{"functionName":"getPrefix","ranges":[{"startOffset":20766,"endOffset":21153,"count":6},{"startOffset":20854,"endOffset":21022,"count":0},{"startOffset":21041,"endOffset":21063,"count":5},{"startOffset":21065,"endOffset":21116,"count":0}],"isBlockCoverage":true},{"functionName":"getKeys","ranges":[{"startOffset":21190,"endOffset":22181,"count":4},{"startOffset":21312,"endOffset":21438,"count":0},{"startOffset":21787,"endOffset":21967,"count":0},{"startOffset":21998,"endOffset":22160,"count":0}],"isBlockCoverage":true},{"functionName":"filter","ranges":[{"startOffset":22021,"endOffset":22077,"count":0}],"isBlockCoverage":false},{"functionName":"getCtxStyle","ranges":[{"startOffset":22183,"endOffset":22446,"count":1},{"startOffset":22280,"endOffset":22396,"count":0}],"isBlockCoverage":true},{"functionName":"formatValue","ranges":[{"startOffset":23080,"endOffset":25837,"count":18},{"startOffset":23218,"endOffset":23254,"count":9},{"startOffset":23255,"endOffset":23292,"count":9},{"startOffset":23294,"endOffset":23375,"count":9},{"startOffset":23375,"endOffset":23420,"count":0},{"startOffset":23420,"endOffset":23696,"count":9},{"startOffset":23696,"endOffset":23912,"count":0},{"startOffset":23912,"endOffset":25213,"count":9},{"startOffset":24160,"endOffset":24266,"count":0},{"startOffset":24267,"endOffset":24414,"count":0},{"startOffset":24416,"endOffset":25209,"count":0},{"startOffset":25213,"endOffset":25403,"count":9},{"startOffset":25403,"endOffset":25776,"count":0},{"startOffset":25776,"endOffset":25836,"count":9}],"isBlockCoverage":true},{"functionName":"formatRaw","ranges":[{"startOffset":25839,"endOffset":36684,"count":9},{"startOffset":25949,"endOffset":26001,"count":0},{"startOffset":26003,"endOffset":26029,"count":0},{"startOffset":26194,"endOffset":26220,"count":0},{"startOffset":26222,"endOffset":26255,"count":0},{"startOffset":26437,"endOffset":26613,"count":5},{"startOffset":26483,"endOffset":26522,"count":0},{"startOffset":26615,"endOffset":26634,"count":4},{"startOffset":26775,"endOffset":26791,"count":0},{"startOffset":27073,"endOffset":27096,"count":4},{"startOffset":27098,"endOffset":30072,"count":5},{"startOffset":27153,"endOffset":27647,"count":0},{"startOffset":27671,"endOffset":28149,"count":0},{"startOffset":28173,"endOffset":28652,"count":0},{"startOffset":28821,"endOffset":28993,"count":0},{"startOffset":29188,"endOffset":29208,"count":0},{"startOffset":29209,"endOffset":29227,"count":0},{"startOffset":29237,"endOffset":29260,"count":0},{"startOffset":29530,"endOffset":30068,"count":0},{"startOffset":30091,"endOffset":34033,"count":4},{"startOffset":30195,"endOffset":30480,"count":3},{"startOffset":30233,"endOffset":30279,"count":0},{"startOffset":30301,"endOffset":30375,"count":0},{"startOffset":30404,"endOffset":30431,"count":0},{"startOffset":30433,"endOffset":30474,"count":0},{"startOffset":30480,"endOffset":34029,"count":1},{"startOffset":30519,"endOffset":30683,"count":0},{"startOffset":30710,"endOffset":31172,"count":0},{"startOffset":31197,"endOffset":31627,"count":0},{"startOffset":31653,"endOffset":31800,"count":0},{"startOffset":31835,"endOffset":32522,"count":0},{"startOffset":32551,"endOffset":32762,"count":0},{"startOffset":32790,"endOffset":32894,"count":0},{"startOffset":32922,"endOffset":33066,"count":0},{"startOffset":33094,"endOffset":33238,"count":0},{"startOffset":33280,"endOffset":33460,"count":0},{"startOffset":33495,"endOffset":33653,"count":0},{"startOffset":33689,"endOffset":33716,"count":0},{"startOffset":33718,"endOffset":33961,"count":0},{"startOffset":34066,"endOffset":34087,"count":0},{"startOffset":34089,"endOffset":34317,"count":0},{"startOffset":34718,"endOffset":34776,"count":0},{"startOffset":34781,"endOffset":34971,"count":0},{"startOffset":35006,"endOffset":35396,"count":0},{"startOffset":35434,"endOffset":35886,"count":0},{"startOffset":36643,"endOffset":36668,"count":0}],"isBlockCoverage":true},{"functionName":"groupArrayElements","ranges":[{"startOffset":47152,"endOffset":51491,"count":2},{"startOffset":47337,"endOffset":47440,"count":0},{"startOffset":47804,"endOffset":47975,"count":26},{"startOffset":47955,"endOffset":47971,"count":4},{"startOffset":48524,"endOffset":48541,"count":0},{"startOffset":49707,"endOffset":49735,"count":0},{"startOffset":49824,"endOffset":50082,"count":10},{"startOffset":49910,"endOffset":49997,"count":26},{"startOffset":49962,"endOffset":49989,"count":12},{"startOffset":50201,"endOffset":50354,"count":26},{"startOffset":50244,"endOffset":50275,"count":0},{"startOffset":50277,"endOffset":50346,"count":0},{"startOffset":50477,"endOffset":51345,"count":6},{"startOffset":50664,"endOffset":50975,"count":20},{"startOffset":51262,"endOffset":51303,"count":0},{"startOffset":51390,"endOffset":51450,"count":0}],"isBlockCoverage":true},{"functionName":"formatNumber","ranges":[{"startOffset":52684,"endOffset":53472,"count":45},{"startOffset":52875,"endOffset":52915,"count":0},{"startOffset":52957,"endOffset":53471,"count":0}],"isBlockCoverage":true},{"functionName":"formatPrimitive","ranges":[{"startOffset":53692,"endOffset":55097,"count":9},{"startOffset":53768,"endOffset":54683,"count":0},{"startOffset":54774,"endOffset":55096,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":54481,"endOffset":54520,"count":0}],"isBlockCoverage":false},{"functionName":"formatTypedArray","ranges":[{"startOffset":58811,"endOffset":59840,"count":5},{"startOffset":59131,"endOffset":59149,"count":0},{"startOffset":59189,"endOffset":59273,"count":36},{"startOffset":59295,"endOffset":59350,"count":0},{"startOffset":59373,"endOffset":59821,"count":0}],"isBlockCoverage":true},{"functionName":"formatProperty","ranges":[{"startOffset":64395,"endOffset":66968,"count":9},{"startOffset":64602,"endOffset":64648,"count":0},{"startOffset":64723,"endOffset":64746,"count":0},{"startOffset":64752,"endOffset":64755,"count":0},{"startOffset":64862,"endOffset":64914,"count":0},{"startOffset":64916,"endOffset":64992,"count":0},{"startOffset":65028,"endOffset":66255,"count":0},{"startOffset":66283,"endOffset":66304,"count":0},{"startOffset":66336,"endOffset":66526,"count":0},{"startOffset":66557,"endOffset":66590,"count":0},{"startOffset":66627,"endOffset":66769,"count":0},{"startOffset":66870,"endOffset":66931,"count":0}],"isBlockCoverage":true},{"functionName":"isBelowBreakLength","ranges":[{"startOffset":66970,"endOffset":67928,"count":7},{"startOffset":67523,"endOffset":67536,"count":0},{"startOffset":67579,"endOffset":67784,"count":19},{"startOffset":67601,"endOffset":67661,"count":0},{"startOffset":67753,"endOffset":67780,"count":2},{"startOffset":67784,"endOffset":67886,"count":5},{"startOffset":67886,"endOffset":67925,"count":0}],"isBlockCoverage":true},{"functionName":"reduceToSingleString","ranges":[{"startOffset":67930,"endOffset":70831,"count":9},{"startOffset":68432,"endOffset":68446,"count":5},{"startOffset":68448,"endOffset":68514,"count":2},{"startOffset":69188,"endOffset":69822,"count":7},{"startOffset":69570,"endOffset":69814,"count":5},{"startOffset":69712,"endOffset":69724,"count":0},{"startOffset":69828,"endOffset":69976,"count":4},{"startOffset":69976,"endOffset":69988,"count":0},{"startOffset":69989,"endOffset":69993,"count":4},{"startOffset":70101,"endOffset":70642,"count":0},{"startOffset":70643,"endOffset":70652,"count":0},{"startOffset":70653,"endOffset":70700,"count":0}],"isBlockCoverage":true},{"functionName":"formatWithOptions","ranges":[{"startOffset":72612,"endOffset":72804,"count":558}],"isBlockCoverage":true},{"functionName":"formatWithOptionsInternal","ranges":[{"startOffset":73174,"endOffset":77198,"count":558},{"startOffset":73338,"endOffset":77001,"count":11},{"startOffset":73367,"endOffset":73394,"count":5},{"startOffset":73394,"endOffset":73481,"count":6},{"startOffset":73481,"endOffset":76840,"count":29},{"startOffset":73537,"endOffset":76834,"count":0},{"startOffset":76840,"endOffset":76864,"count":6},{"startOffset":76864,"endOffset":76997,"count":0},{"startOffset":77001,"endOffset":77029,"count":553},{"startOffset":77029,"endOffset":77182,"count":16},{"startOffset":77112,"endOffset":77144,"count":9},{"startOffset":77145,"endOffset":77152,"count":7},{"startOffset":77182,"endOffset":77197,"count":553}],"isBlockCoverage":true},{"functionName":"getStringWidth","ranges":[{"startOffset":78203,"endOffset":78794,"count":26},{"startOffset":78309,"endOffset":78359,"count":0},{"startOffset":78401,"endOffset":78772,"count":64},{"startOffset":78607,"endOffset":78731,"count":0},{"startOffset":78762,"endOffset":78765,"count":0}],"isBlockCoverage":true}]},{"scriptId":"22","url":"node:internal/util/debuglog","functions":[{"functionName":"initializeDebugEnv","ranges":[{"startOffset":503,"endOffset":976,"count":1},{"startOffset":595,"endOffset":932,"count":0}],"isBlockCoverage":true},{"functionName":"testEnabled","ranges":[{"startOffset":870,"endOffset":927,"count":0}],"isBlockCoverage":false},{"functionName":"testEnabled","ranges":[{"startOffset":958,"endOffset":969,"count":5}],"isBlockCoverage":true},{"functionName":"noop","ranges":[{"startOffset":1404,"endOffset":1412,"count":606}],"isBlockCoverage":true},{"functionName":"debuglogImpl","ranges":[{"startOffset":1533,"endOffset":2091,"count":5},{"startOffset":1608,"endOffset":2063,"count":3},{"startOffset":1627,"endOffset":2016,"count":0}],"isBlockCoverage":true},{"functionName":"debug","ranges":[{"startOffset":1716,"endOffset":2009,"count":0}],"isBlockCoverage":false},{"functionName":"debuglog","ranges":[{"startOffset":2311,"endOffset":3337,"count":5}],"isBlockCoverage":false},{"functionName":"init","ranges":[{"startOffset":2342,"endOffset":2438,"count":5}],"isBlockCoverage":true},{"functionName":"debug","ranges":[{"startOffset":2453,"endOffset":2847,"count":5},{"startOffset":2700,"endOffset":2730,"count":3},{"startOffset":2737,"endOffset":2776,"count":2},{"startOffset":2783,"endOffset":2837,"count":0}],"isBlockCoverage":true},{"functionName":"test","ranges":[{"startOffset":2877,"endOffset":2946,"count":0}],"isBlockCoverage":false},{"functionName":"logger","ranges":[{"startOffset":2965,"endOffset":3160,"count":5},{"startOffset":3013,"endOffset":3043,"count":3},{"startOffset":3050,"endOffset":3089,"count":2},{"startOffset":3096,"endOffset":3150,"count":0}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":3231,"endOffset":3265,"count":0}],"isBlockCoverage":false}]},{"scriptId":"23","url":"node:events","functions":[{"functionName":"EventEmitter","ranges":[{"startOffset":6505,"endOffset":6574,"count":92}],"isBlockCoverage":false},{"functionName":"checkListener","ranges":[{"startOffset":8025,"endOffset":8103,"count":1680}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":8211,"endOffset":8259,"count":5}],"isBlockCoverage":true},{"functionName":"EventEmitter.init","ranges":[{"startOffset":9901,"endOffset":10569,"count":92}],"isBlockCoverage":false},{"functionName":"emit","ranges":[{"startOffset":13366,"endOffset":15669,"count":94}],"isBlockCoverage":false},{"functionName":"_addListener","ranges":[{"startOffset":15672,"endOffset":17566,"count":562}],"isBlockCoverage":false},{"functionName":"addListener","ranges":[{"startOffset":17744,"endOffset":17836,"count":562}],"isBlockCoverage":false},{"functionName":"_onceWrap","ranges":[{"startOffset":18495,"endOffset":18736,"count":558}],"isBlockCoverage":true},{"functionName":"once","ranges":[{"startOffset":18927,"endOffset":19053,"count":558}],"isBlockCoverage":true},{"functionName":"removeListener","ranges":[{"startOffset":19663,"endOffset":21068,"count":560},{"startOffset":19812,"endOffset":19824,"count":0},{"startOffset":19897,"endOffset":19909,"count":1},{"startOffset":19909,"endOffset":19939,"count":559},{"startOffset":19939,"endOffset":19968,"count":558},{"startOffset":19970,"endOffset":20341,"count":559},{"startOffset":20035,"endOffset":20082,"count":558},{"startOffset":20082,"endOffset":20333,"count":1},{"startOffset":20117,"endOffset":20174,"count":0},{"startOffset":20341,"endOffset":21042,"count":0},{"startOffset":21042,"endOffset":21067,"count":559}],"isBlockCoverage":true},{"functionName":"listenerCount","ranges":[{"startOffset":24379,"endOffset":25084,"count":558},{"startOffset":24562,"endOffset":24708,"count":0},{"startOffset":24744,"endOffset":25065,"count":0}],"isBlockCoverage":true}]},{"scriptId":"24","url":"node:buffer","functions":[{"functionName":"createPool","ranges":[{"startOffset":4069,"endOffset":4228,"count":34}],"isBlockCoverage":false},{"functionName":"alignPool","ranges":[{"startOffset":4244,"endOffset":4366,"count":1809}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":8258,"endOffset":8286,"count":1}],"isBlockCoverage":true},{"functionName":"from","ranges":[{"startOffset":8544,"endOffset":9509,"count":7122}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":11456,"endOffset":11516,"count":90}],"isBlockCoverage":true},{"functionName":"allocUnsafeSlow","ranges":[{"startOffset":12359,"endOffset":12448,"count":90}],"isBlockCoverage":true},{"functionName":"fromStringFast","ranges":[{"startOffset":13082,"endOffset":13628,"count":2289}],"isBlockCoverage":false},{"functionName":"fromString","ranges":[{"startOffset":13630,"endOffset":14057,"count":4416}],"isBlockCoverage":false},{"functionName":"fromArrayBuffer","ranges":[{"startOffset":14059,"endOffset":14756,"count":15273},{"startOffset":14178,"endOffset":14203,"count":8},{"startOffset":14203,"endOffset":14299,"count":15265},{"startOffset":14280,"endOffset":14295,"count":0},{"startOffset":14376,"endOffset":14421,"count":0},{"startOffset":14451,"endOffset":14480,"count":8},{"startOffset":14480,"endOffset":14703,"count":15265},{"startOffset":14577,"endOffset":14668,"count":15042},{"startOffset":14617,"endOffset":14662,"count":0},{"startOffset":14668,"endOffset":14699,"count":223}],"isBlockCoverage":true},{"functionName":"base64ByteLength","ranges":[{"startOffset":17288,"endOffset":17556,"count":10240},{"startOffset":17410,"endOffset":17418,"count":2966},{"startOffset":17494,"endOffset":17502,"count":1459}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":17691,"endOffset":17755,"count":1}],"isBlockCoverage":false},{"functionName":"byteLength","ranges":[{"startOffset":19633,"endOffset":19684,"count":10240}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":19697,"endOffset":19763,"count":10240}],"isBlockCoverage":true},{"functionName":"slice","ranges":[{"startOffset":19776,"endOffset":19824,"count":15042}],"isBlockCoverage":true},{"functionName":"getEncodingOps","ranges":[{"startOffset":21083,"endOffset":22907,"count":25505},{"startOffset":21170,"endOffset":21469,"count":0},{"startOffset":21474,"endOffset":21893,"count":0},{"startOffset":21898,"endOffset":22052,"count":0},{"startOffset":22057,"endOffset":22213,"count":0},{"startOffset":22292,"endOffset":22318,"count":0},{"startOffset":22378,"endOffset":22490,"count":0},{"startOffset":22500,"endOffset":22599,"count":0},{"startOffset":22604,"endOffset":22736,"count":0},{"startOffset":22741,"endOffset":22901,"count":0}],"isBlockCoverage":true},{"functionName":"toString","ranges":[{"startOffset":24311,"endOffset":24890,"count":15265},{"startOffset":24383,"endOffset":24431,"count":0},{"startOffset":24483,"endOffset":24493,"count":0},{"startOffset":24523,"endOffset":24533,"count":0},{"startOffset":24582,"endOffset":24594,"count":0},{"startOffset":24610,"endOffset":24631,"count":0},{"startOffset":24657,"endOffset":24667,"count":223},{"startOffset":24667,"endOffset":24703,"count":15042},{"startOffset":24703,"endOffset":24737,"count":0},{"startOffset":24737,"endOffset":24808,"count":15042},{"startOffset":24808,"endOffset":24849,"count":0},{"startOffset":24849,"endOffset":24889,"count":15042}],"isBlockCoverage":true}]},{"scriptId":"25","url":"node:internal/buffer","functions":[{"functionName":"FastBuffer","ranges":[{"startOffset":26365,"endOffset":26465,"count":1615}],"isBlockCoverage":false},{"functionName":"markAsUntransferable","ranges":[{"startOffset":29764,"endOffset":30013,"count":34}],"isBlockCoverage":false},{"functionName":"createUnsafeBuffer","ranges":[{"startOffset":30291,"endOffset":30427,"count":124}],"isBlockCoverage":false},{"functionName":"reconnectZeroFillToggle","ranges":[{"startOffset":30682,"endOffset":30754,"count":1}],"isBlockCoverage":true}]},{"scriptId":"26","url":"node:internal/worker/js_transferable","functions":[{"functionName":"makeTransferable","ranges":[{"startOffset":1313,"endOffset":1968,"count":45},{"startOffset":1442,"endOffset":1453,"count":0},{"startOffset":1688,"endOffset":1850,"count":0}],"isBlockCoverage":true}]},{"scriptId":"27","url":"node:internal/process/per_thread","functions":[{"functionName":"refreshHrtimeBuffer","ranges":[{"startOffset":1373,"endOffset":1831,"count":1}],"isBlockCoverage":false},{"functionName":"exit","ranges":[{"startOffset":4774,"endOffset":5913,"count":1}],"isBlockCoverage":true},{"functionName":"toggleTraceCategoryState","ranges":[{"startOffset":11955,"endOffset":12285,"count":1},{"startOffset":12035,"endOffset":12210,"count":0},{"startOffset":12242,"endOffset":12283,"count":0}],"isBlockCoverage":true}]},{"scriptId":"28","url":"node:internal/process/task_queues","functions":[{"functionName":"hasTickScheduled","ranges":[{"startOffset":982,"endOffset":1057,"count":11}],"isBlockCoverage":true},{"functionName":"setHasTickScheduled","ranges":[{"startOffset":1059,"endOffset":1145,"count":65},{"startOffset":1135,"endOffset":1138,"count":33},{"startOffset":1139,"endOffset":1142,"count":32}],"isBlockCoverage":true},{"functionName":"runNextTicks","ranges":[{"startOffset":1247,"endOffset":1443,"count":6},{"startOffset":1345,"endOffset":1372,"count":5},{"startOffset":1372,"endOffset":1396,"count":3},{"startOffset":1402,"endOffset":1409,"count":3},{"startOffset":1409,"endOffset":1442,"count":2}],"isBlockCoverage":true},{"functionName":"processTicksAndRejections","ranges":[{"startOffset":1445,"endOffset":2424,"count":32},{"startOffset":1748,"endOffset":1781,"count":0},{"startOffset":1914,"endOffset":1956,"count":0},{"startOffset":1969,"endOffset":2020,"count":0},{"startOffset":2033,"endOffset":2093,"count":0},{"startOffset":2106,"endOffset":2133,"count":0},{"startOffset":2217,"endOffset":2238,"count":0}],"isBlockCoverage":true},{"functionName":"nextTick","ranges":[{"startOffset":2568,"endOffset":3442,"count":33},{"startOffset":2669,"endOffset":2676,"count":0},{"startOffset":2724,"endOffset":2738,"count":0},{"startOffset":2785,"endOffset":2836,"count":0},{"startOffset":2841,"endOffset":2906,"count":0},{"startOffset":2911,"endOffset":3054,"count":0},{"startOffset":3354,"endOffset":3414,"count":0}],"isBlockCoverage":true}]},{"scriptId":"29","url":"node:internal/process/promises","functions":[{"functionName":"setHasRejectionToWarn","ranges":[{"startOffset":2155,"endOffset":2245,"count":41},{"startOffset":2235,"endOffset":2238,"count":9},{"startOffset":2239,"endOffset":2242,"count":32}],"isBlockCoverage":true},{"functionName":"hasRejectionToWarn","ranges":[{"startOffset":2247,"endOffset":2326,"count":9}],"isBlockCoverage":true},{"functionName":"getUnhandledRejectionsMode","ranges":[{"startOffset":2466,"endOffset":2999,"count":1},{"startOffset":2622,"endOffset":2675,"count":0},{"startOffset":2680,"endOffset":2737,"count":0},{"startOffset":2802,"endOffset":2855,"count":0},{"startOffset":2860,"endOffset":2940,"count":0},{"startOffset":2945,"endOffset":2993,"count":0}],"isBlockCoverage":true},{"functionName":"promiseRejectHandler","ranges":[{"startOffset":3001,"endOffset":3570,"count":18},{"startOffset":3101,"endOffset":3166,"count":1},{"startOffset":3189,"endOffset":3278,"count":9},{"startOffset":3283,"endOffset":3366,"count":9},{"startOffset":3371,"endOffset":3466,"count":0},{"startOffset":3471,"endOffset":3564,"count":0}],"isBlockCoverage":true},{"functionName":"unhandledRejection","ranges":[{"startOffset":3997,"endOffset":4557,"count":9}],"isBlockCoverage":true},{"functionName":"emit","ranges":[{"startOffset":4059,"endOffset":4253,"count":0}],"isBlockCoverage":false},{"functionName":"handledRejection","ranges":[{"startOffset":4559,"endOffset":5390,"count":9},{"startOffset":4762,"endOffset":5270,"count":0},{"startOffset":5315,"endOffset":5353,"count":0},{"startOffset":5359,"endOffset":5388,"count":0}],"isBlockCoverage":true},{"functionName":"processPromiseRejections","ranges":[{"startOffset":6672,"endOffset":9849,"count":32},{"startOffset":6830,"endOffset":7009,"count":0},{"startOffset":7074,"endOffset":9753,"count":9},{"startOffset":7264,"endOffset":8519,"count":0},{"startOffset":8528,"endOffset":8635,"count":0},{"startOffset":8644,"endOffset":8809,"count":0},{"startOffset":8818,"endOffset":9253,"count":0},{"startOffset":9262,"endOffset":9540,"count":0},{"startOffset":9555,"endOffset":9753,"count":0}],"isBlockCoverage":true}]},{"scriptId":"30","url":"node:internal/fixed_queue","functions":[{"functionName":"isEmpty","ranges":[{"startOffset":3077,"endOffset":3129,"count":129}],"isBlockCoverage":true},{"functionName":"isFull","ranges":[{"startOffset":3133,"endOffset":3200,"count":33}],"isBlockCoverage":true},{"functionName":"push","ranges":[{"startOffset":3204,"endOffset":3291,"count":33}],"isBlockCoverage":true},{"functionName":"shift","ranges":[{"startOffset":3295,"endOffset":3510,"count":64},{"startOffset":3388,"endOffset":3509,"count":32}],"isBlockCoverage":true},{"functionName":"isEmpty","ranges":[{"startOffset":3630,"endOffset":3677,"count":65}],"isBlockCoverage":true},{"functionName":"push","ranges":[{"startOffset":3681,"endOffset":3945,"count":33},{"startOffset":3722,"endOffset":3915,"count":0}],"isBlockCoverage":true},{"functionName":"shift","ranges":[{"startOffset":3949,"endOffset":4204,"count":64},{"startOffset":4064,"endOffset":4183,"count":0}],"isBlockCoverage":true}]},{"scriptId":"32","url":"node:timers","functions":[{"functionName":"","ranges":[{"startOffset":1819,"endOffset":1844,"count":1}],"isBlockCoverage":true},{"functionName":"unenroll","ranges":[{"startOffset":2343,"endOffset":3527,"count":8},{"startOffset":2396,"endOffset":2403,"count":0},{"startOffset":2463,"endOffset":2509,"count":0},{"startOffset":2600,"endOffset":2638,"count":0},{"startOffset":2644,"endOffset":2679,"count":0},{"startOffset":3254,"endOffset":3396,"count":7}],"isBlockCoverage":true},{"functionName":"setTimeout","ranges":[{"startOffset":4229,"endOffset":4886,"count":17},{"startOffset":4396,"endOffset":4403,"count":1},{"startOffset":4433,"endOffset":4474,"count":0},{"startOffset":4479,"endOffset":4526,"count":0},{"startOffset":4531,"endOffset":4752,"count":0}],"isBlockCoverage":true},{"functionName":"clearTimeout","ranges":[{"startOffset":5206,"endOffset":5572,"count":9},{"startOffset":5270,"endOffset":5337,"count":8},{"startOffset":5337,"endOffset":5370,"count":1},{"startOffset":5370,"endOffset":5398,"count":0},{"startOffset":5400,"endOffset":5570,"count":1},{"startOffset":5489,"endOffset":5566,"count":0}],"isBlockCoverage":true},{"functionName":"setInterval","ranges":[{"startOffset":5809,"endOffset":6468,"count":7},{"startOffset":5978,"endOffset":5985,"count":0},{"startOffset":6015,"endOffset":6056,"count":0},{"startOffset":6061,"endOffset":6108,"count":0},{"startOffset":6113,"endOffset":6334,"count":0}],"isBlockCoverage":true},{"functionName":"clearInterval","ranges":[{"startOffset":6565,"endOffset":6863,"count":6}],"isBlockCoverage":true}]},{"scriptId":"33","url":"node:internal/process/execution","functions":[{"functionName":"tryGetCwd","ranges":[{"startOffset":894,"endOffset":1224,"count":1},{"startOffset":955,"endOffset":1222,"count":0}],"isBlockCoverage":true}]},{"scriptId":"34","url":"node:path","functions":[{"functionName":"isPosixPathSeparator","ranges":[{"startOffset":1825,"endOffset":1902,"count":21739}],"isBlockCoverage":true},{"functionName":"normalizeString","ranges":[{"startOffset":2137,"endOffset":4085,"count":596},{"startOffset":2354,"endOffset":4069,"count":21739},{"startOffset":2387,"endOffset":2429,"count":21143},{"startOffset":2429,"endOffset":2520,"count":596},{"startOffset":2478,"endOffset":2520,"count":0},{"startOffset":2520,"endOffset":2553,"count":21143},{"startOffset":2553,"endOffset":3970,"count":3623},{"startOffset":2585,"endOffset":2598,"count":3025},{"startOffset":2600,"endOffset":2625,"count":599},{"startOffset":2625,"endOffset":3927,"count":3024},{"startOffset":2647,"endOffset":3682,"count":2},{"startOffset":2703,"endOffset":2777,"count":0},{"startOffset":2778,"endOffset":2852,"count":0},{"startOffset":3006,"endOffset":3082,"count":0},{"startOffset":3363,"endOffset":3532,"count":0},{"startOffset":3542,"endOffset":3674,"count":0},{"startOffset":3682,"endOffset":3927,"count":3022},{"startOffset":3728,"endOffset":3797,"count":2426},{"startOffset":3797,"endOffset":3872,"count":596},{"startOffset":3927,"endOffset":3970,"count":3621},{"startOffset":3970,"endOffset":4065,"count":17520},{"startOffset":3998,"endOffset":4012,"count":699},{"startOffset":4014,"endOffset":4035,"count":9},{"startOffset":4035,"endOffset":4065,"count":17511}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":33760,"endOffset":33779,"count":1}],"isBlockCoverage":true},{"functionName":"resolve","ranges":[{"startOffset":33904,"endOffset":34827,"count":596},{"startOffset":34027,"endOffset":34047,"count":1199},{"startOffset":34054,"endOffset":34381,"count":604},{"startOffset":34082,"endOffset":34091,"count":603},{"startOffset":34092,"endOffset":34104,"count":1},{"startOffset":34207,"endOffset":34234,"count":0},{"startOffset":34766,"endOffset":34816,"count":0},{"startOffset":34817,"endOffset":34822,"count":0}],"isBlockCoverage":true},{"functionName":"isAbsolute","ranges":[{"startOffset":35573,"endOffset":35729,"count":91}],"isBlockCoverage":true},{"functionName":"toNamespacedPath","ranges":[{"startOffset":38728,"endOffset":38804,"count":481}],"isBlockCoverage":true}]},{"scriptId":"38","url":"node:internal/source_map/source_map_cache","functions":[{"functionName":"getSourceMapsEnabled","ranges":[{"startOffset":1596,"endOffset":1659,"count":90}],"isBlockCoverage":true},{"functionName":"setSourceMapsEnabled","ranges":[{"startOffset":1661,"endOffset":2203,"count":1},{"startOffset":1769,"endOffset":1924,"count":0}],"isBlockCoverage":true},{"functionName":"extractSourceMapURLMagicComment","ranges":[{"startOffset":2807,"endOffset":3250,"count":90},{"startOffset":3128,"endOffset":3156,"count":0},{"startOffset":3204,"endOffset":3249,"count":0}],"isBlockCoverage":true},{"functionName":"maybeCacheSourceMap","ranges":[{"startOffset":3252,"endOffset":5023,"count":90},{"startOffset":3454,"endOffset":3474,"count":0},{"startOffset":3477,"endOffset":3484,"count":0},{"startOffset":3618,"endOffset":3742,"count":0},{"startOffset":3950,"endOffset":4122,"count":0},{"startOffset":4123,"endOffset":4137,"count":0},{"startOffset":4164,"endOffset":5021,"count":0}],"isBlockCoverage":true}]},{"scriptId":"39","url":"node:internal/url","functions":[{"functionName":"","ranges":[{"startOffset":3462,"endOffset":4251,"count":1271}],"isBlockCoverage":false},{"functionName":"get hasPort","ranges":[{"startOffset":4030,"endOffset":4095,"count":0}],"isBlockCoverage":false},{"functionName":"get hasSearch","ranges":[{"startOffset":4099,"endOffset":4174,"count":1958}],"isBlockCoverage":true},{"functionName":"get hasHash","ranges":[{"startOffset":4178,"endOffset":4249,"count":1958}],"isBlockCoverage":true},{"functionName":"isURL","ranges":[{"startOffset":21271,"endOffset":21396,"count":1075},{"startOffset":21322,"endOffset":21338,"count":789},{"startOffset":21339,"endOffset":21365,"count":789},{"startOffset":21366,"endOffset":21392,"count":789}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":21398,"endOffset":29204,"count":1695}],"isBlockCoverage":false},{"functionName":"URL","ranges":[{"startOffset":21461,"endOffset":21761,"count":1695},{"startOffset":21532,"endOffset":21580,"count":0},{"startOffset":21669,"endOffset":21700,"count":891}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":21765,"endOffset":22485,"count":0}],"isBlockCoverage":false},{"functionName":"#updateContext","ranges":[{"startOffset":22489,"endOffset":23396,"count":2233},{"startOffset":23205,"endOffset":23392,"count":0}],"isBlockCoverage":true},{"functionName":"toString","ranges":[{"startOffset":23400,"endOffset":23447,"count":608}],"isBlockCoverage":true},{"functionName":"get href","ranges":[{"startOffset":23451,"endOffset":23498,"count":1255}],"isBlockCoverage":true},{"functionName":"set href","ranges":[{"startOffset":23502,"endOffset":23715,"count":0}],"isBlockCoverage":false},{"functionName":"get origin","ranges":[{"startOffset":23733,"endOffset":24602,"count":0}],"isBlockCoverage":false},{"functionName":"get protocol","ranges":[{"startOffset":24606,"endOffset":24710,"count":3160}],"isBlockCoverage":true},{"functionName":"set protocol","ranges":[{"startOffset":24714,"endOffset":24887,"count":0}],"isBlockCoverage":false},{"functionName":"get username","ranges":[{"startOffset":24891,"endOffset":25118,"count":0}],"isBlockCoverage":false},{"functionName":"set username","ranges":[{"startOffset":25122,"endOffset":25295,"count":0}],"isBlockCoverage":false},{"functionName":"get password","ranges":[{"startOffset":25299,"endOffset":25522,"count":0}],"isBlockCoverage":false},{"functionName":"set password","ranges":[{"startOffset":25526,"endOffset":25699,"count":0}],"isBlockCoverage":false},{"functionName":"get host","ranges":[{"startOffset":25703,"endOffset":26134,"count":0}],"isBlockCoverage":false},{"functionName":"set host","ranges":[{"startOffset":26138,"endOffset":26303,"count":0}],"isBlockCoverage":false},{"functionName":"get hostname","ranges":[{"startOffset":26307,"endOffset":26589,"count":699},{"startOffset":26473,"endOffset":26498,"count":0}],"isBlockCoverage":true},{"functionName":"set hostname","ranges":[{"startOffset":26593,"endOffset":26766,"count":0}],"isBlockCoverage":false},{"functionName":"get port","ranges":[{"startOffset":26770,"endOffset":26878,"count":0}],"isBlockCoverage":false},{"functionName":"set port","ranges":[{"startOffset":26882,"endOffset":27047,"count":0}],"isBlockCoverage":false},{"functionName":"get pathname","ranges":[{"startOffset":27051,"endOffset":27343,"count":1674},{"startOffset":27117,"endOffset":27167,"count":0},{"startOffset":27200,"endOffset":27248,"count":0}],"isBlockCoverage":true},{"functionName":"set pathname","ranges":[{"startOffset":27347,"endOffset":27520,"count":0}],"isBlockCoverage":false},{"functionName":"get search","ranges":[{"startOffset":27524,"endOffset":27859,"count":284},{"startOffset":27587,"endOffset":27858,"count":0}],"isBlockCoverage":true},{"functionName":"set search","ranges":[{"startOffset":27863,"endOffset":28040,"count":284}],"isBlockCoverage":true},{"functionName":"get searchParams","ranges":[{"startOffset":28058,"endOffset":28357,"count":0}],"isBlockCoverage":false},{"functionName":"get hash","ranges":[{"startOffset":28361,"endOffset":28576,"count":284},{"startOffset":28405,"endOffset":28467,"count":0},{"startOffset":28493,"endOffset":28575,"count":0}],"isBlockCoverage":true},{"functionName":"set hash","ranges":[{"startOffset":28580,"endOffset":28745,"count":284}],"isBlockCoverage":true},{"functionName":"toJSON","ranges":[{"startOffset":28749,"endOffset":28794,"count":0}],"isBlockCoverage":false},{"functionName":"canParse","ranges":[{"startOffset":28805,"endOffset":29202,"count":0}],"isBlockCoverage":false},{"functionName":"getPathFromURLPosix","ranges":[{"startOffset":38290,"endOffset":38811,"count":699},{"startOffset":38353,"endOffset":38409,"count":0},{"startOffset":38487,"endOffset":38770,"count":24951},{"startOffset":38518,"endOffset":38766,"count":0}],"isBlockCoverage":true},{"functionName":"fileURLToPath","ranges":[{"startOffset":38813,"endOffset":39152,"count":699},{"startOffset":38880,"endOffset":38901,"count":0},{"startOffset":38931,"endOffset":38995,"count":0},{"startOffset":39033,"endOffset":39074,"count":0},{"startOffset":39094,"endOffset":39121,"count":0}],"isBlockCoverage":true},{"functionName":"encodePathChars","ranges":[{"startOffset":39965,"endOffset":40741,"count":301},{"startOffset":40058,"endOffset":40129,"count":0},{"startOffset":40257,"endOffset":40330,"count":0},{"startOffset":40388,"endOffset":40459,"count":0},{"startOffset":40517,"endOffset":40595,"count":0},{"startOffset":40653,"endOffset":40720,"count":0}],"isBlockCoverage":true},{"functionName":"pathToFileURL","ranges":[{"startOffset":40743,"endOffset":42720,"count":301},{"startOffset":40794,"endOffset":40840,"count":0},{"startOffset":40842,"endOffset":41607,"count":0},{"startOffset":41889,"endOffset":41950,"count":300},{"startOffset":41910,"endOffset":41949,"count":0},{"startOffset":41952,"endOffset":42003,"count":1},{"startOffset":42009,"endOffset":42025,"count":1},{"startOffset":42481,"endOffset":42553,"count":0},{"startOffset":42610,"endOffset":42678,"count":0}],"isBlockCoverage":true},{"functionName":"toPathIfFileURL","ranges":[{"startOffset":42722,"endOffset":42859,"count":376},{"startOffset":42797,"endOffset":42818,"count":286},{"startOffset":42818,"endOffset":42858,"count":90}],"isBlockCoverage":true}]},{"scriptId":"44","url":"node:internal/console/constructor","functions":[{"functionName":"lazyUtilColors","ranges":[{"startOffset":1875,"endOffset":1975,"count":558}],"isBlockCoverage":true},{"functionName":"value","ranges":[{"startOffset":5832,"endOffset":6477,"count":1}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":6041,"endOffset":6136,"count":1670},{"startOffset":6074,"endOffset":6097,"count":1}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":6148,"endOffset":6178,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":6308,"endOffset":6407,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":6419,"endOffset":6449,"count":0}],"isBlockCoverage":false},{"functionName":"value","ranges":[{"startOffset":6569,"endOffset":7977,"count":1}],"isBlockCoverage":true},{"functionName":"value","ranges":[{"startOffset":8069,"endOffset":9521,"count":558},{"startOffset":8295,"endOffset":8309,"count":0},{"startOffset":8383,"endOffset":8409,"count":0},{"startOffset":8448,"endOffset":8643,"count":419},{"startOffset":8501,"endOffset":8596,"count":4},{"startOffset":8701,"endOffset":8729,"count":0},{"startOffset":9167,"endOffset":9451,"count":0}],"isBlockCoverage":true},{"functionName":"value","ranges":[{"startOffset":9616,"endOffset":10026,"count":558},{"startOffset":9830,"endOffset":9951,"count":0},{"startOffset":9972,"endOffset":9994,"count":0}],"isBlockCoverage":true},{"functionName":"value","ranges":[{"startOffset":10119,"endOffset":10299,"count":558}],"isBlockCoverage":true},{"functionName":"createWriteErrorHandler","ranges":[{"startOffset":10662,"endOffset":11551,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":10730,"endOffset":11548,"count":554},{"startOffset":11000,"endOffset":11018,"count":0},{"startOffset":11041,"endOffset":11079,"count":0},{"startOffset":11081,"endOffset":11544,"count":0}],"isBlockCoverage":true},{"functionName":"log","ranges":[{"startOffset":11580,"endOffset":11667,"count":558}],"isBlockCoverage":true},{"functionName":"group","ranges":[{"startOffset":14706,"endOffset":14891,"count":182},{"startOffset":14748,"endOffset":14797,"count":0}],"isBlockCoverage":true},{"functionName":"groupEnd","ranges":[{"startOffset":14896,"endOffset":15065,"count":182}],"isBlockCoverage":true},{"functionName":"initializeGlobalConsole","ranges":[{"startOffset":20425,"endOffset":21464,"count":1},{"startOffset":20793,"endOffset":21463,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":21359,"endOffset":21460,"count":0}],"isBlockCoverage":false}]},{"scriptId":"46","url":"node:internal/process/permission","functions":[{"functionName":"isEnabled","ranges":[{"startOffset":315,"endOffset":559,"count":91},{"startOffset":375,"endOffset":520,"count":1}],"isBlockCoverage":true}]},{"scriptId":"47","url":"node:internal/event_target","functions":[{"functionName":"isEvent","ranges":[{"startOffset":2362,"endOffset":2434,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2436,"endOffset":7033,"count":1}],"isBlockCoverage":false},{"functionName":"Event","ranges":[{"startOffset":2752,"endOffset":3234,"count":1},{"startOffset":2834,"endOffset":2869,"count":0},{"startOffset":3128,"endOffset":3165,"count":0}],"isBlockCoverage":true},{"functionName":"initEvent","ranges":[{"startOffset":3343,"endOffset":3629,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":3633,"endOffset":4148,"count":0}],"isBlockCoverage":false},{"functionName":"stopImmediatePropagation","ranges":[{"startOffset":4152,"endOffset":4275,"count":0}],"isBlockCoverage":false},{"functionName":"preventDefault","ranges":[{"startOffset":4279,"endOffset":4403,"count":0}],"isBlockCoverage":false},{"functionName":"get target","ranges":[{"startOffset":4444,"endOffset":4555,"count":0}],"isBlockCoverage":false},{"functionName":"get currentTarget","ranges":[{"startOffset":4596,"endOffset":4714,"count":0}],"isBlockCoverage":false},{"functionName":"get srcElement","ranges":[{"startOffset":4755,"endOffset":4870,"count":0}],"isBlockCoverage":false},{"functionName":"get type","ranges":[{"startOffset":4906,"endOffset":5013,"count":1},{"startOffset":4949,"endOffset":4985,"count":0}],"isBlockCoverage":true},{"functionName":"get cancelable","ranges":[{"startOffset":5050,"endOffset":5168,"count":0}],"isBlockCoverage":false},{"functionName":"get defaultPrevented","ranges":[{"startOffset":5205,"endOffset":5355,"count":1},{"startOffset":5260,"endOffset":5296,"count":0},{"startOffset":5325,"endOffset":5350,"count":0}],"isBlockCoverage":true},{"functionName":"get timeStamp","ranges":[{"startOffset":5391,"endOffset":5507,"count":0}],"isBlockCoverage":false},{"functionName":"composedPath","ranges":[{"startOffset":5725,"endOffset":5872,"count":0}],"isBlockCoverage":false},{"functionName":"get returnValue","ranges":[{"startOffset":5909,"endOffset":6056,"count":0}],"isBlockCoverage":false},{"functionName":"get bubbles","ranges":[{"startOffset":6093,"endOffset":6205,"count":0}],"isBlockCoverage":false},{"functionName":"get composed","ranges":[{"startOffset":6242,"endOffset":6356,"count":0}],"isBlockCoverage":false},{"functionName":"get eventPhase","ranges":[{"startOffset":6392,"endOffset":6549,"count":0}],"isBlockCoverage":false},{"functionName":"get cancelBubble","ranges":[{"startOffset":6586,"endOffset":6714,"count":0}],"isBlockCoverage":false},{"functionName":"set cancelBubble","ranges":[{"startOffset":6751,"endOffset":6900,"count":0}],"isBlockCoverage":false},{"functionName":"stopPropagation","ranges":[{"startOffset":6904,"endOffset":7031,"count":0}],"isBlockCoverage":false},{"functionName":"Listener","ranges":[{"startOffset":10864,"endOffset":12328,"count":10},{"startOffset":11199,"endOffset":11218,"count":0},{"startOffset":11242,"endOffset":11264,"count":0},{"startOffset":11288,"endOffset":11310,"count":0},{"startOffset":11346,"endOffset":11370,"count":8},{"startOffset":11391,"endOffset":11410,"count":0},{"startOffset":11448,"endOffset":11484,"count":0},{"startOffset":11556,"endOffset":12012,"count":0},{"startOffset":12125,"endOffset":12324,"count":0}],"isBlockCoverage":true},{"functionName":"Listener.callback","ranges":[{"startOffset":12155,"endOffset":12285,"count":0}],"isBlockCoverage":false},{"functionName":"get capture","ranges":[{"startOffset":12395,"endOffset":12461,"count":2}],"isBlockCoverage":true},{"functionName":"get weak","ranges":[{"startOffset":12616,"endOffset":12676,"count":14}],"isBlockCoverage":true},{"functionName":"set removed","ranges":[{"startOffset":12845,"endOffset":12962,"count":12},{"startOffset":12887,"endOffset":12914,"count":2},{"startOffset":12914,"endOffset":12958,"count":10}],"isBlockCoverage":true},{"functionName":"same","ranges":[{"startOffset":12966,"endOffset":13133,"count":2},{"startOffset":13025,"endOffset":13048,"count":0}],"isBlockCoverage":true},{"functionName":"remove","ranges":[{"startOffset":13137,"endOffset":13394,"count":2},{"startOffset":13262,"endOffset":13297,"count":0},{"startOffset":13348,"endOffset":13390,"count":0}],"isBlockCoverage":true},{"functionName":"initEventTarget","ranges":[{"startOffset":13398,"endOffset":13617,"count":5}],"isBlockCoverage":true},{"functionName":"EventTarget","ranges":[{"startOffset":13860,"endOffset":13906,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":13910,"endOffset":14715,"count":10},{"startOffset":14071,"endOffset":14119,"count":0},{"startOffset":14121,"endOffset":14711,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":14718,"endOffset":14769,"count":2}],"isBlockCoverage":true},{"functionName":"addEventListener","ranges":[{"startOffset":15158,"endOffset":17876,"count":10},{"startOffset":15253,"endOffset":15295,"count":0},{"startOffset":15332,"endOffset":15379,"count":0},{"startOffset":15771,"endOffset":16224,"count":0},{"startOffset":16288,"endOffset":16672,"count":0},{"startOffset":17235,"endOffset":17425,"count":0},{"startOffset":17427,"endOffset":17875,"count":0}],"isBlockCoverage":true},{"functionName":"signal.addEventListener.__proto__","ranges":[{"startOffset":16503,"endOffset":16577,"count":0}],"isBlockCoverage":false},{"functionName":"removeEventListener","ranges":[{"startOffset":18034,"endOffset":18875,"count":2},{"startOffset":18132,"endOffset":18174,"count":0},{"startOffset":18211,"endOffset":18258,"count":0},{"startOffset":18307,"endOffset":18314,"count":0},{"startOffset":18513,"endOffset":18520,"count":0},{"startOffset":18835,"endOffset":18871,"count":0}],"isBlockCoverage":true},{"functionName":"dispatchEvent","ranges":[{"startOffset":19542,"endOffset":20003,"count":1},{"startOffset":19601,"endOffset":19643,"count":0},{"startOffset":19680,"endOffset":19716,"count":0},{"startOffset":19759,"endOffset":19815,"count":0},{"startOffset":19858,"endOffset":19900,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":20007,"endOffset":22303,"count":1},{"startOffset":20453,"endOffset":20479,"count":0},{"startOffset":20581,"endOffset":22299,"count":0}],"isBlockCoverage":true},{"functionName":"createEvent","ranges":[{"startOffset":20075,"endOffset":20275,"count":0}],"isBlockCoverage":false},{"functionName":"iterationCondition","ranges":[{"startOffset":20658,"endOffset":20823,"count":0}],"isBlockCoverage":false},{"functionName":"initNodeEventTarget","ranges":[{"startOffset":23112,"endOffset":23175,"count":2}],"isBlockCoverage":true},{"functionName":"off","ranges":[{"startOffset":24399,"endOffset":24592,"count":2},{"startOffset":24470,"endOffset":24516,"count":0}],"isBlockCoverage":true},{"functionName":"on","ranges":[{"startOffset":25117,"endOffset":25322,"count":8},{"startOffset":25178,"endOffset":25224,"count":0}],"isBlockCoverage":true},{"functionName":"validateEventListener","ranges":[{"startOffset":27187,"endOffset":27559,"count":12},{"startOffset":27267,"endOffset":27319,"count":0},{"startOffset":27343,"endOffset":27558,"count":0}],"isBlockCoverage":true},{"functionName":"validateEventListenerOptions","ranges":[{"startOffset":27561,"endOffset":28148,"count":10},{"startOffset":27650,"endOffset":27678,"count":0},{"startOffset":27708,"endOffset":27728,"count":0}],"isBlockCoverage":true},{"functionName":"isEventTarget","ranges":[{"startOffset":28453,"endOffset":28529,"count":13}],"isBlockCoverage":true},{"functionName":"isNodeEventTarget","ranges":[{"startOffset":28531,"endOffset":28615,"count":10}],"isBlockCoverage":true},{"functionName":"makeEventHandler","ranges":[{"startOffset":29016,"endOffset":29425,"count":2}],"isBlockCoverage":true},{"functionName":"eventHandler","ranges":[{"startOffset":29197,"endOffset":29366,"count":0}],"isBlockCoverage":false},{"functionName":"defineEventHandler","ranges":[{"startOffset":29427,"endOffset":30893,"count":6}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":29587,"endOffset":29723,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":29822,"endOffset":30660,"count":2},{"startOffset":29981,"endOffset":30495,"count":0}],"isBlockCoverage":true},{"functionName":"EventEmitterMixin","ranges":[{"startOffset":30921,"endOffset":31611,"count":1},{"startOffset":31352,"endOffset":31514,"count":18}],"isBlockCoverage":true},{"functionName":"MixedEventEmitter","ranges":[{"startOffset":30990,"endOffset":31131,"count":90}],"isBlockCoverage":true}]},{"scriptId":"49","url":"node:internal/webidl","functions":[{"functionName":"DOMString","ranges":[{"startOffset":4438,"endOffset":4568,"count":12},{"startOffset":4491,"endOffset":4545,"count":0}],"isBlockCoverage":true}]},{"scriptId":"52","url":"node:internal/bootstrap/switches/is_main_thread","functions":[{"functionName":"createWritableStdioStream","ranges":[{"startOffset":1424,"endOffset":3026,"count":2},{"startOffset":1576,"endOffset":1710,"count":0},{"startOffset":1716,"endOffset":1910,"count":0},{"startOffset":2217,"endOffset":2245,"count":0},{"startOffset":2247,"endOffset":2468,"count":0},{"startOffset":2651,"endOffset":2905,"count":0}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":2841,"endOffset":2888,"count":0}],"isBlockCoverage":false},{"functionName":"addCleanup","ranges":[{"startOffset":3639,"endOffset":3730,"count":2},{"startOffset":3693,"endOffset":3728,"count":0}],"isBlockCoverage":true},{"functionName":"getStdout","ranges":[{"startOffset":3732,"endOffset":4424,"count":2},{"startOffset":3769,"endOffset":4017,"count":1},{"startOffset":4017,"endOffset":4075,"count":0},{"startOffset":4075,"endOffset":4423,"count":1}],"isBlockCoverage":true},{"functionName":"cleanupStdout","ranges":[{"startOffset":4090,"endOffset":4268,"count":0}],"isBlockCoverage":false},{"functionName":"getStderr","ranges":[{"startOffset":4426,"endOffset":5117,"count":1},{"startOffset":4463,"endOffset":4477,"count":0},{"startOffset":4711,"endOffset":4769,"count":0}],"isBlockCoverage":true},{"functionName":"cleanupStderr","ranges":[{"startOffset":4783,"endOffset":4961,"count":0}],"isBlockCoverage":false}]},{"scriptId":"53","url":"node:internal/v8/startup_snapshot","functions":[{"functionName":"isBuildingSnapshot","ranges":[{"startOffset":433,"endOffset":504,"count":6}],"isBlockCoverage":false},{"functionName":"runDeserializeCallbacks","ranges":[{"startOffset":831,"endOffset":1004,"count":1},{"startOffset":910,"endOffset":1002,"count":0}],"isBlockCoverage":true}]},{"scriptId":"54","url":"node:internal/process/signal","functions":[{"functionName":"isSignal","ranges":[{"startOffset":238,"endOffset":334,"count":2}],"isBlockCoverage":false},{"functionName":"startListeningIfSignal","ranges":[{"startOffset":398,"endOffset":904,"count":2}],"isBlockCoverage":false},{"functionName":"stopListeningIfSignal","ranges":[{"startOffset":906,"endOffset":1101,"count":1},{"startOffset":1008,"endOffset":1044,"count":0},{"startOffset":1046,"endOffset":1099,"count":0}],"isBlockCoverage":true}]},{"scriptId":"55","url":"node:fs","functions":[{"functionName":"isFileType","ranges":[{"startOffset":5155,"endOffset":5415,"count":838},{"startOffset":5354,"endOffset":5374,"count":102}],"isBlockCoverage":true},{"functionName":"splitRoot","ranges":[{"startOffset":68408,"endOffset":68618,"count":91},{"startOffset":68475,"endOffset":68598,"count":182},{"startOffset":68553,"endOffset":68592,"count":91},{"startOffset":68598,"endOffset":68617,"count":0}],"isBlockCoverage":true},{"functionName":"encodeRealpathResult","ranges":[{"startOffset":68623,"endOffset":68910,"count":91},{"startOffset":68708,"endOffset":68738,"count":0},{"startOffset":68758,"endOffset":68909,"count":0}],"isBlockCoverage":true},{"functionName":"nextPart","ranges":[{"startOffset":69316,"endOffset":69391,"count":470}],"isBlockCoverage":true},{"functionName":"realpathSync","ranges":[{"startOffset":69565,"endOffset":73384,"count":286},{"startOffset":69689,"endOffset":69707,"count":0},{"startOffset":69868,"endOffset":69903,"count":195},{"startOffset":69903,"endOffset":70465,"count":91},{"startOffset":70465,"endOffset":70655,"count":0},{"startOffset":70655,"endOffset":70792,"count":91},{"startOffset":70792,"endOffset":73311,"count":470},{"startOffset":70904,"endOffset":71035,"count":91},{"startOffset":71035,"endOffset":71193,"count":379},{"startOffset":71310,"endOffset":71447,"count":368},{"startOffset":71401,"endOffset":71425,"count":0},{"startOffset":71447,"endOffset":71513,"count":102},{"startOffset":71550,"endOffset":71599,"count":0},{"startOffset":71599,"endOffset":72788,"count":102},{"startOffset":71895,"endOffset":71920,"count":0},{"startOffset":72049,"endOffset":72708,"count":0},{"startOffset":72752,"endOffset":72782,"count":0},{"startOffset":72788,"endOffset":73103,"count":0},{"startOffset":73105,"endOffset":73307,"count":0},{"startOffset":73311,"endOffset":73325,"count":91}],"isBlockCoverage":true}]},{"scriptId":"57","url":"node:internal/encoding","functions":[{"functionName":"validateEncoder","ranges":[{"startOffset":1343,"endOffset":1468,"count":2444458},{"startOffset":1424,"endOffset":1466,"count":0}],"isBlockCoverage":true},{"functionName":"validateDecoder","ranges":[{"startOffset":1470,"endOffset":1595,"count":2081627},{"startOffset":1551,"endOffset":1593,"count":0}],"isBlockCoverage":true},{"functionName":"getEncodingFromLabel","ranges":[{"startOffset":9392,"endOffset":9571,"count":2},{"startOffset":9503,"endOffset":9570,"count":0}],"isBlockCoverage":true},{"functionName":"TextEncoder","ranges":[{"startOffset":9595,"endOffset":9641,"count":1}],"isBlockCoverage":false},{"functionName":"encode","ranges":[{"startOffset":9716,"endOffset":9808,"count":1065}],"isBlockCoverage":true},{"functionName":"encodeInto","ranges":[{"startOffset":9812,"endOffset":10218,"count":2443393},{"startOffset":9939,"endOffset":9998,"count":0}],"isBlockCoverage":true},{"functionName":"TextDecoder","ranges":[{"startOffset":11266,"endOffset":12149,"count":2},{"startOffset":11522,"endOffset":11569,"count":0},{"startOffset":11653,"endOffset":11676,"count":1},{"startOffset":11677,"endOffset":11680,"count":1},{"startOffset":11717,"endOffset":11745,"count":1},{"startOffset":11746,"endOffset":11749,"count":1},{"startOffset":12100,"endOffset":12143,"count":0}],"isBlockCoverage":true},{"functionName":"decode","ranges":[{"startOffset":12426,"endOffset":12957,"count":2081627},{"startOffset":12661,"endOffset":12956,"count":0}],"isBlockCoverage":true}]},{"scriptId":"60","url":"node:internal/fs/utils","functions":[{"functionName":"assertEncoding","ranges":[{"startOffset":3699,"endOffset":3899,"count":286},{"startOffset":3750,"endOffset":3781,"count":0},{"startOffset":3783,"endOffset":3897,"count":0}],"isBlockCoverage":true},{"functionName":"getOptions","ranges":[{"startOffset":7505,"endOffset":8131,"count":376},{"startOffset":7589,"endOffset":7621,"count":286},{"startOffset":7623,"endOffset":7655,"count":90},{"startOffset":7655,"endOffset":7692,"count":286},{"startOffset":7692,"endOffset":7810,"count":0},{"startOffset":7810,"endOffset":7932,"count":286},{"startOffset":7849,"endOffset":7932,"count":0},{"startOffset":7932,"endOffset":8046,"count":286},{"startOffset":8046,"endOffset":8110,"count":0},{"startOffset":8110,"endOffset":8130,"count":286}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8859,"endOffset":9455,"count":376},{"startOffset":9089,"endOffset":9109,"count":0},{"startOffset":9179,"endOffset":9247,"count":0},{"startOffset":9266,"endOffset":9454,"count":0}],"isBlockCoverage":true},{"functionName":"stringToFlags","ranges":[{"startOffset":15850,"endOffset":17106,"count":90},{"startOffset":15931,"endOffset":15986,"count":0},{"startOffset":16009,"endOffset":16035,"count":0},{"startOffset":16092,"endOffset":16103,"count":0},{"startOffset":16125,"endOffset":16162,"count":0},{"startOffset":16167,"endOffset":16193,"count":0},{"startOffset":16198,"endOffset":16210,"count":0},{"startOffset":16232,"endOffset":16268,"count":0},{"startOffset":16274,"endOffset":16321,"count":0},{"startOffset":16326,"endOffset":16337,"count":0},{"startOffset":16359,"endOffset":16416,"count":0},{"startOffset":16422,"endOffset":16468,"count":0},{"startOffset":16473,"endOffset":16484,"count":0},{"startOffset":16506,"endOffset":16561,"count":0},{"startOffset":16567,"endOffset":16615,"count":0},{"startOffset":16620,"endOffset":16631,"count":0},{"startOffset":16653,"endOffset":16711,"count":0},{"startOffset":16716,"endOffset":16727,"count":0},{"startOffset":16749,"endOffset":16807,"count":0},{"startOffset":16813,"endOffset":16860,"count":0},{"startOffset":16865,"endOffset":16876,"count":0},{"startOffset":16898,"endOffset":16954,"count":0},{"startOffset":16959,"endOffset":16970,"count":0},{"startOffset":16992,"endOffset":17048,"count":0},{"startOffset":17052,"endOffset":17105,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":18968,"endOffset":19238,"count":376},{"startOffset":19030,"endOffset":19052,"count":0},{"startOffset":19054,"endOffset":19140,"count":0},{"startOffset":19216,"endOffset":19236,"count":0}],"isBlockCoverage":true},{"functionName":"possiblyTransformPath","ranges":[{"startOffset":19609,"endOffset":20115,"count":90},{"startOffset":19678,"endOffset":20098,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":20158,"endOffset":20316,"count":90}],"isBlockCoverage":true}]},{"scriptId":"63","url":"node:internal/modules/cjs/loader","functions":[{"functionName":"get hasLoadedAnyUserCJSModule","ranges":[{"startOffset":2188,"endOffset":2257,"count":1}],"isBlockCoverage":true},{"functionName":"stat","ranges":[{"startOffset":5254,"endOffset":5668,"count":1},{"startOffset":5352,"endOffset":5450,"count":0},{"startOffset":5523,"endOffset":5537,"count":0},{"startOffset":5539,"endOffset":5649,"count":0}],"isBlockCoverage":true},{"functionName":"initializeCJS","ranges":[{"startOffset":10692,"endOffset":11192,"count":1}],"isBlockCoverage":true},{"functionName":"Module._findPath","ranges":[{"startOffset":18056,"endOffset":22152,"count":1},{"startOffset":18189,"endOffset":18252,"count":0},{"startOffset":18385,"endOffset":18408,"count":0},{"startOffset":18630,"endOffset":18984,"count":0},{"startOffset":19066,"endOffset":19522,"count":0},{"startOffset":19567,"endOffset":19721,"count":0},{"startOffset":19935,"endOffset":20031,"count":0},{"startOffset":20038,"endOffset":20061,"count":0},{"startOffset":20089,"endOffset":20229,"count":0},{"startOffset":20414,"endOffset":20603,"count":0},{"startOffset":20657,"endOffset":21297,"count":0},{"startOffset":21388,"endOffset":21594,"count":0},{"startOffset":21620,"endOffset":21631,"count":0},{"startOffset":21633,"endOffset":21859,"count":0},{"startOffset":21955,"endOffset":22151,"count":0}],"isBlockCoverage":true},{"functionName":"Module._initPaths","ranges":[{"startOffset":49685,"endOffset":50650,"count":1},{"startOffset":49726,"endOffset":49751,"count":0},{"startOffset":49803,"endOffset":49826,"count":0},{"startOffset":50034,"endOffset":50076,"count":0},{"startOffset":50375,"endOffset":50517,"count":0}],"isBlockCoverage":true}]},{"scriptId":"64","url":"node:internal/modules/helpers","functions":[{"functionName":"","ranges":[{"startOffset":1032,"endOffset":1057,"count":1}],"isBlockCoverage":true},{"functionName":"toRealPath","ranges":[{"startOffset":1526,"endOffset":1658,"count":2}],"isBlockCoverage":true},{"functionName":"initializeCjsConditions","ranges":[{"startOffset":1774,"endOffset":2166,"count":1},{"startOffset":1953,"endOffset":1957,"count":0}],"isBlockCoverage":true},{"functionName":"loadBuiltinModule","ranges":[{"startOffset":2587,"endOffset":2967,"count":2},{"startOffset":2676,"endOffset":2693,"count":0}],"isBlockCoverage":true},{"functionName":"normalizeReferrerURL","ranges":[{"startOffset":9023,"endOffset":9211,"count":90},{"startOffset":9130,"endOffset":9176,"count":0}],"isBlockCoverage":true}]},{"scriptId":"65","url":"node:internal/modules/package_json_reader","functions":[{"functionName":"read","ranges":[{"startOffset":1112,"endOffset":3862,"count":326},{"startOffset":1208,"endOffset":1245,"count":322},{"startOffset":1245,"endOffset":1922,"count":4},{"startOffset":1922,"endOffset":1931,"count":0},{"startOffset":1932,"endOffset":1946,"count":0},{"startOffset":1947,"endOffset":1969,"count":4},{"startOffset":1993,"endOffset":3812,"count":1},{"startOffset":2061,"endOffset":2657,"count":0},{"startOffset":3189,"endOffset":3235,"count":0},{"startOffset":3602,"endOffset":3655,"count":0},{"startOffset":3705,"endOffset":3808,"count":0},{"startOffset":3812,"endOffset":3861,"count":4}],"isBlockCoverage":true},{"functionName":"readPackage","ranges":[{"startOffset":3930,"endOffset":4020,"count":1}],"isBlockCoverage":true},{"functionName":"readPackageScope","ranges":[{"startOffset":4237,"endOffset":5057,"count":1},{"startOffset":4673,"endOffset":4719,"count":0},{"startOffset":4721,"endOffset":4748,"count":0},{"startOffset":4815,"endOffset":4842,"count":0},{"startOffset":4994,"endOffset":5056,"count":0}],"isBlockCoverage":true}]},{"scriptId":"66","url":"node:internal/modules/esm/utils","functions":[{"functionName":"getDefaultConditions","ranges":[{"startOffset":936,"endOffset":1042,"count":285}],"isBlockCoverage":true},{"functionName":"getDefaultConditionsSet","ranges":[{"startOffset":1172,"endOffset":1287,"count":284}],"isBlockCoverage":true},{"functionName":"initializeDefaultConditions","ranges":[{"startOffset":1437,"endOffset":1819,"count":1},{"startOffset":1620,"endOffset":1624,"count":0}],"isBlockCoverage":true},{"functionName":"getConditionsSet","ranges":[{"startOffset":1889,"endOffset":2248,"count":284},{"startOffset":2002,"endOffset":2210,"count":0}],"isBlockCoverage":true},{"functionName":"registerModule","ranges":[{"startOffset":4391,"endOffset":4934,"count":90},{"startOffset":4596,"endOffset":4809,"count":0}],"isBlockCoverage":true},{"functionName":"importModuleDynamicallyCallback","ranges":[{"startOffset":6757,"endOffset":7304,"count":2},{"startOffset":7124,"endOffset":7303,"count":0}],"isBlockCoverage":true},{"functionName":"initializeESM","ranges":[{"startOffset":7616,"endOffset":8002,"count":1}],"isBlockCoverage":true},{"functionName":"forceDefaultLoader","ranges":[{"startOffset":8130,"endOffset":8193,"count":1}],"isBlockCoverage":true}]},{"scriptId":"67","url":"node:internal/process/pre_execution","functions":[{"functionName":"prepareMainThreadExecution","ranges":[{"startOffset":1107,"endOffset":1291,"count":1}],"isBlockCoverage":true},{"functionName":"prepareExecution","ranges":[{"startOffset":2268,"endOffset":4462,"count":1},{"startOffset":3229,"endOffset":3333,"count":0},{"startOffset":4221,"endOffset":4383,"count":0}],"isBlockCoverage":true},{"functionName":"setupSymbolDisposePolyfill","ranges":[{"startOffset":4464,"endOffset":5199,"count":1}],"isBlockCoverage":true},{"functionName":"setupUserModules","ranges":[{"startOffset":5201,"endOffset":5779,"count":1}],"isBlockCoverage":true},{"functionName":"refreshRuntimeOptions","ranges":[{"startOffset":5781,"endOffset":5837,"count":1}],"isBlockCoverage":true},{"functionName":"patchProcessObject","ranges":[{"startOffset":6264,"endOffset":8694,"count":1},{"startOffset":7342,"endOffset":7394,"count":0}],"isBlockCoverage":true},{"functionName":"addReadOnlyProcessAlias","ranges":[{"startOffset":8696,"endOffset":8977,"count":13},{"startOffset":8817,"endOffset":8975,"count":1}],"isBlockCoverage":true},{"functionName":"setupWarningHandler","ranges":[{"startOffset":8979,"endOffset":9499,"count":1},{"startOffset":9354,"endOffset":9493,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9383,"endOffset":9485,"count":0}],"isBlockCoverage":false},{"functionName":"setupUndici","ranges":[{"startOffset":9574,"endOffset":10954,"count":1},{"startOffset":9644,"endOffset":9661,"count":0},{"startOffset":10853,"endOffset":10952,"count":0}],"isBlockCoverage":true},{"functionName":"lazyUndici","ranges":[{"startOffset":9679,"endOffset":9824,"count":0}],"isBlockCoverage":false},{"functionName":"lazyInterface","ranges":[{"startOffset":9828,"endOffset":10069,"count":4}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":9929,"endOffset":9979,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":9987,"endOffset":10057,"count":0}],"isBlockCoverage":false},{"functionName":"fetch","ranges":[{"startOffset":10188,"endOffset":10281,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10680,"endOffset":10795,"count":0}],"isBlockCoverage":false},{"functionName":"setupWebCrypto","ranges":[{"startOffset":11058,"endOffset":12010,"count":1},{"startOffset":11193,"endOffset":11210,"count":0},{"startOffset":11699,"endOffset":12008,"count":0}],"isBlockCoverage":true},{"functionName":"cryptoThisCheck","ranges":[{"startOffset":11384,"endOffset":11560,"count":0}],"isBlockCoverage":false},{"functionName":"get crypto","ranges":[{"startOffset":11861,"endOffset":11960,"count":0}],"isBlockCoverage":false},{"functionName":"setupCodeCoverage","ranges":[{"startOffset":12012,"endOffset":12533,"count":1}],"isBlockCoverage":true},{"functionName":"setupCustomEvent","ranges":[{"startOffset":12639,"endOffset":12916,"count":1},{"startOffset":12778,"endOffset":12795,"count":0}],"isBlockCoverage":true},{"functionName":"setupStacktracePrinterOnSigint","ranges":[{"startOffset":12918,"endOffset":13143,"count":1},{"startOffset":13020,"endOffset":13142,"count":0}],"isBlockCoverage":true},{"functionName":"initializeReport","ranges":[{"startOffset":13145,"endOffset":13394,"count":1}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":13290,"endOffset":13385,"count":0}],"isBlockCoverage":false},{"functionName":"setupDebugEnv","ranges":[{"startOffset":13396,"endOffset":13627,"count":1},{"startOffset":13547,"endOffset":13625,"count":0}],"isBlockCoverage":true},{"functionName":"initializeReportSignalHandlers","ranges":[{"startOffset":13689,"endOffset":13877,"count":1},{"startOffset":13777,"endOffset":13875,"count":0}],"isBlockCoverage":true},{"functionName":"initializeHeapSnapshotSignalHandlers","ranges":[{"startOffset":13879,"endOffset":14613,"count":1},{"startOffset":14074,"endOffset":14611,"count":0}],"isBlockCoverage":true},{"functionName":"doWriteHeapSnapshot","ranges":[{"startOffset":14187,"endOffset":14341,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":14533,"endOffset":14605,"count":0}],"isBlockCoverage":false},{"functionName":"setupTraceCategoryState","ranges":[{"startOffset":14615,"endOffset":14874,"count":1}],"isBlockCoverage":true},{"functionName":"setupInspectorHooks","ranges":[{"startOffset":14876,"endOffset":15458,"count":1}],"isBlockCoverage":true},{"functionName":"initializeDeprecations","ranges":[{"startOffset":15653,"endOffset":17605,"count":1},{"startOffset":16365,"endOffset":16667,"count":16},{"startOffset":16410,"endOffset":16642,"count":0},{"startOffset":16984,"endOffset":17181,"count":0},{"startOffset":17209,"endOffset":17603,"count":0}],"isBlockCoverage":true},{"functionName":"setupChildProcessIpcChannel","ranges":[{"startOffset":17607,"endOffset":18172,"count":1},{"startOffset":17683,"endOffset":18170,"count":0}],"isBlockCoverage":true},{"functionName":"initializeClusterIPC","ranges":[{"startOffset":18174,"endOffset":18444,"count":1},{"startOffset":18261,"endOffset":18442,"count":0}],"isBlockCoverage":true},{"functionName":"initializePermission","ranges":[{"startOffset":18446,"endOffset":20441,"count":1},{"startOffset":18588,"endOffset":20061,"count":0}],"isBlockCoverage":true},{"functionName":"binding","ranges":[{"startOffset":18612,"endOffset":18699,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":20273,"endOffset":20433,"count":4},{"startOffset":20351,"endOffset":20427,"count":0}],"isBlockCoverage":true},{"functionName":"readPolicyFromDisk","ranges":[{"startOffset":20443,"endOffset":22262,"count":1},{"startOffset":20571,"endOffset":22260,"count":0}],"isBlockCoverage":true},{"functionName":"initializeCJSLoader","ranges":[{"startOffset":22264,"endOffset":22385,"count":1}],"isBlockCoverage":true},{"functionName":"initializeESMLoader","ranges":[{"startOffset":22387,"endOffset":22970,"count":1},{"startOffset":22723,"endOffset":22968,"count":0}],"isBlockCoverage":true},{"functionName":"initializeSourceMapsHandlers","ranges":[{"startOffset":22972,"endOffset":23170,"count":1}],"isBlockCoverage":true},{"functionName":"initializeFrozenIntrinsics","ranges":[{"startOffset":23172,"endOffset":23429,"count":1},{"startOffset":23257,"endOffset":23427,"count":0}],"isBlockCoverage":true},{"functionName":"loadPreloadModules","ranges":[{"startOffset":23431,"endOffset":23779,"count":1},{"startOffset":23625,"endOffset":23777,"count":0}],"isBlockCoverage":true},{"functionName":"markBootstrapComplete","ranges":[{"startOffset":23781,"endOffset":23875,"count":1}],"isBlockCoverage":true}]},{"scriptId":"70","url":"node:internal/modules/run_main","functions":[{"functionName":"resolveMainPath","ranges":[{"startOffset":320,"endOffset":1479,"count":1},{"startOffset":494,"endOffset":598,"count":0},{"startOffset":891,"endOffset":902,"count":0},{"startOffset":1129,"endOffset":1453,"count":0}],"isBlockCoverage":true},{"functionName":"shouldUseESMLoader","ranges":[{"startOffset":1640,"endOffset":3093,"count":1},{"startOffset":1746,"endOffset":1762,"count":0},{"startOffset":2236,"endOffset":2252,"count":0},{"startOffset":2368,"endOffset":2384,"count":0},{"startOffset":2447,"endOffset":2464,"count":0},{"startOffset":2726,"endOffset":2762,"count":0},{"startOffset":2767,"endOffset":3087,"count":0}],"isBlockCoverage":true},{"functionName":"runMainESM","ranges":[{"startOffset":3224,"endOffset":3537,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3445,"endOffset":3532,"count":1}],"isBlockCoverage":true},{"functionName":"handleMainPromise","ranges":[{"startOffset":3669,"endOffset":3943,"count":1}],"isBlockCoverage":true},{"functionName":"executeUserEntryPoint","ranges":[{"startOffset":4490,"endOffset":4888,"count":1},{"startOffset":4700,"endOffset":4707,"count":0},{"startOffset":4713,"endOffset":4886,"count":0}],"isBlockCoverage":true}]},{"scriptId":"71","url":"node:internal/dns/utils","functions":[{"functionName":"initializeDns","ranges":[{"startOffset":5468,"endOffset":5854,"count":1},{"startOffset":5611,"endOffset":5721,"count":0},{"startOffset":5769,"endOffset":5853,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5794,"endOffset":5850,"count":0}],"isBlockCoverage":false}]},{"scriptId":"73","url":"node:internal/bootstrap/switches/does_own_process_state","functions":[{"functionName":"wrappedCwd","ranges":[{"startOffset":3541,"endOffset":3644,"count":3},{"startOffset":3593,"endOffset":3622,"count":1}],"isBlockCoverage":true}]},{"scriptId":"80","url":"node:internal/main/run_main_module","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1182,"count":1}],"isBlockCoverage":false}]},{"scriptId":"81","url":"node:internal/process/esm_loader","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1105,"count":1}],"isBlockCoverage":false},{"functionName":"get esmLoader","ranges":[{"startOffset":332,"endOffset":400,"count":2}],"isBlockCoverage":true},{"functionName":"loadESM","ranges":[{"startOffset":404,"endOffset":1100,"count":1},{"startOffset":568,"endOffset":761,"count":0},{"startOffset":852,"endOffset":1096,"count":0}],"isBlockCoverage":true}]},{"scriptId":"82","url":"node:internal/modules/esm/loader","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":21896,"count":1}],"isBlockCoverage":false},{"functionName":"newResolveCache","ranges":[{"startOffset":926,"endOffset":1056,"count":1}],"isBlockCoverage":true},{"functionName":"newLoadCache","ranges":[{"startOffset":1212,"endOffset":1333,"count":1}],"isBlockCoverage":true},{"functionName":"getTranslators","ranges":[{"startOffset":1495,"endOffset":1617,"count":93}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2304,"endOffset":15239,"count":1}],"isBlockCoverage":false},{"functionName":"ModuleLoader","ranges":[{"startOffset":3571,"endOffset":3764,"count":1},{"startOffset":3659,"endOffset":3716,"count":0}],"isBlockCoverage":true},{"functionName":"setCustomizations","ranges":[{"startOffset":5304,"endOffset":5548,"count":1},{"startOffset":5407,"endOffset":5489,"count":0}],"isBlockCoverage":true},{"functionName":"eval","ranges":[{"startOffset":5552,"endOffset":6555,"count":0}],"isBlockCoverage":false},{"functionName":"getModuleJob","ranges":[{"startOffset":7290,"endOffset":7525,"count":288}],"isBlockCoverage":true},{"functionName":"getModuleJobSync","ranges":[{"startOffset":7529,"endOffset":7766,"count":0}],"isBlockCoverage":false},{"functionName":"getJobFromResolveResult","ranges":[{"startOffset":7770,"endOffset":8354,"count":288},{"startOffset":8144,"endOffset":8206,"count":0},{"startOffset":8235,"endOffset":8333,"count":92}],"isBlockCoverage":true},{"functionName":"#createModuleJob","ranges":[{"startOffset":8992,"endOffset":10184,"count":92},{"startOffset":9485,"endOffset":9561,"count":0},{"startOffset":9704,"endOffset":9744,"count":1},{"startOffset":9799,"endOffset":9814,"count":0},{"startOffset":9816,"endOffset":9870,"count":0}],"isBlockCoverage":true},{"functionName":"callTranslator","ranges":[{"startOffset":9086,"endOffset":9400,"count":92},{"startOffset":9230,"endOffset":9310,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9493,"endOffset":9561,"count":0}],"isBlockCoverage":false},{"functionName":"moduleProvider","ranges":[{"startOffset":9570,"endOffset":9646,"count":92}],"isBlockCoverage":true},{"functionName":"import","ranges":[{"startOffset":10646,"endOffset":10871,"count":3}],"isBlockCoverage":true},{"functionName":"register","ranges":[{"startOffset":10937,"endOffset":11460,"count":0}],"isBlockCoverage":false},{"functionName":"resolve","ranges":[{"startOffset":11919,"endOffset":12505,"count":288},{"startOffset":12007,"endOffset":12105,"count":0},{"startOffset":12301,"endOffset":12335,"count":1},{"startOffset":12335,"endOffset":12504,"count":287}],"isBlockCoverage":true},{"functionName":"resolveSync","ranges":[{"startOffset":12663,"endOffset":12941,"count":0}],"isBlockCoverage":false},{"functionName":"defaultResolve","ranges":[{"startOffset":13153,"endOffset":13493,"count":287}],"isBlockCoverage":true},{"functionName":"load","ranges":[{"startOffset":13777,"endOffset":14081,"count":92},{"startOffset":13914,"endOffset":13968,"count":0}],"isBlockCoverage":true},{"functionName":"loadSync","ranges":[{"startOffset":14085,"endOffset":14616,"count":0}],"isBlockCoverage":false},{"functionName":"validateLoadResult","ranges":[{"startOffset":14620,"endOffset":14771,"count":92},{"startOffset":14678,"endOffset":14767,"count":0}],"isBlockCoverage":true},{"functionName":"importMetaInitialize","ranges":[{"startOffset":14775,"endOffset":15110,"count":0}],"isBlockCoverage":false},{"functionName":"forceLoadHooks","ranges":[{"startOffset":15171,"endOffset":15237,"count":1},{"startOffset":15214,"endOffset":15230,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":15293,"endOffset":17803,"count":0}],"isBlockCoverage":false},{"functionName":"createModuleLoader","ranges":[{"startOffset":18187,"endOffset":19849,"count":1},{"startOffset":18632,"endOffset":19799,"count":0}],"isBlockCoverage":true},{"functionName":"readableURIEncode","ranges":[{"startOffset":18707,"endOffset":19202,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":19522,"endOffset":19610,"count":0}],"isBlockCoverage":false},{"functionName":"getHooksProxy","ranges":[{"startOffset":19962,"endOffset":20138,"count":0}],"isBlockCoverage":false},{"functionName":"register","ranges":[{"startOffset":21422,"endOffset":21821,"count":0}],"isBlockCoverage":false}]},{"scriptId":"83","url":"node:internal/modules/esm/module_map","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3877,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":281,"endOffset":306,"count":1}],"isBlockCoverage":true},{"functionName":"ResolveCache","ranges":[{"startOffset":850,"endOffset":878,"count":1}],"isBlockCoverage":true},{"functionName":"serializeKey","ranges":[{"startOffset":1224,"endOffset":1836,"count":288},{"startOffset":1633,"endOffset":1835,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1752,"endOffset":1818,"count":0}],"isBlockCoverage":false},{"functionName":"#getModuleCachedImports","ranges":[{"startOffset":1840,"endOffset":2056,"count":575},{"startOffset":1954,"endOffset":2026,"count":78}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":2231,"endOffset":2333,"count":288}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":2473,"endOffset":2602,"count":287}],"isBlockCoverage":true},{"functionName":"has","ranges":[{"startOffset":2606,"endOffset":2710,"count":0}],"isBlockCoverage":false},{"functionName":"LoadCache","ranges":[{"startOffset":2844,"endOffset":2872,"count":1}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":2921,"endOffset":3064,"count":288},{"startOffset":3051,"endOffset":3059,"count":196}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":3067,"endOffset":3662,"count":92},{"startOffset":3286,"endOffset":3322,"count":0},{"startOffset":3324,"endOffset":3394,"count":0},{"startOffset":3478,"endOffset":3484,"count":0}],"isBlockCoverage":true},{"functionName":"has","ranges":[{"startOffset":3665,"endOffset":3822,"count":0}],"isBlockCoverage":false}]},{"scriptId":"84","url":"node:internal/modules/esm/assert","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3876,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1326,"endOffset":1364,"count":5}],"isBlockCoverage":true},{"functionName":"validateAttributes","ranges":[{"startOffset":1785,"endOffset":3160,"count":92},{"startOffset":1981,"endOffset":2108,"count":0},{"startOffset":2180,"endOffset":2325,"count":0},{"startOffset":2590,"endOffset":2650,"count":0},{"startOffset":2656,"endOffset":2764,"count":0},{"startOffset":2770,"endOffset":3154,"count":0}],"isBlockCoverage":true},{"functionName":"handleInvalidType","ranges":[{"startOffset":3392,"endOffset":3806,"count":0}],"isBlockCoverage":false}]},{"scriptId":"85","url":"node:internal/modules/esm/translators","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":19831,"count":1}],"isBlockCoverage":false},{"functionName":"lazyTypes","ranges":[{"startOffset":522,"endOffset":638,"count":180},{"startOffset":568,"endOffset":586,"count":179},{"startOffset":586,"endOffset":637,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1213,"endOffset":1238,"count":1}],"isBlockCoverage":true},{"functionName":"getSource","ranges":[{"startOffset":2004,"endOffset":2132,"count":0}],"isBlockCoverage":false},{"functionName":"initCJSParse","ranges":[{"startOffset":2428,"endOffset":2826,"count":0}],"isBlockCoverage":false},{"functionName":"assertBufferSource","ranges":[{"startOffset":3440,"endOffset":3861,"count":180},{"startOffset":3517,"endOffset":3544,"count":90},{"startOffset":3546,"endOffset":3563,"count":0},{"startOffset":3657,"endOffset":3682,"count":0},{"startOffset":3701,"endOffset":3780,"count":0},{"startOffset":3781,"endOffset":3785,"count":0}],"isBlockCoverage":true},{"functionName":"stringify","ranges":[{"startOffset":4085,"endOffset":4363,"count":90},{"startOffset":4144,"endOffset":4160,"count":0},{"startOffset":4300,"endOffset":4319,"count":1},{"startOffset":4320,"endOffset":4329,"count":89}],"isBlockCoverage":true},{"functionName":"errPath","ranges":[{"startOffset":4483,"endOffset":4628,"count":0}],"isBlockCoverage":false},{"functionName":"importModuleDynamically","ranges":[{"startOffset":5104,"endOffset":5242,"count":2}],"isBlockCoverage":true},{"functionName":"moduleStrategy","ranges":[{"startOffset":5324,"endOffset":5849,"count":90}],"isBlockCoverage":true},{"functionName":"initializeImportMeta","ranges":[{"startOffset":5738,"endOffset":5794,"count":0}],"isBlockCoverage":false},{"functionName":"enrichCJSError","ranges":[{"startOffset":6074,"endOffset":6596,"count":0}],"isBlockCoverage":false},{"functionName":"loadCJSModule","ranges":[{"startOffset":7188,"endOffset":9897,"count":0}],"isBlockCoverage":false},{"functionName":"createCJSModuleWrap","ranges":[{"startOffset":10381,"endOffset":11887,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":12047,"endOffset":12139,"count":0}],"isBlockCoverage":false},{"functionName":"commonjsStrategy","ranges":[{"startOffset":12327,"endOffset":13215,"count":0}],"isBlockCoverage":false},{"functionName":"cjsPreparseModuleExports","ranges":[{"startOffset":13404,"endOffset":15902,"count":0}],"isBlockCoverage":false},{"functionName":"builtinStrategy","ranges":[{"startOffset":16026,"endOffset":16432,"count":2},{"startOffset":16305,"endOffset":16357,"count":0}],"isBlockCoverage":true},{"functionName":"jsonStrategy","ranges":[{"startOffset":16544,"endOffset":18818,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":18884,"endOffset":19828,"count":0}],"isBlockCoverage":false}]},{"scriptId":"86","url":"node:internal/modules/esm/resolve","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":44600,"count":1}],"isBlockCoverage":false},{"functionName":"emitTrailingSlashPatternDeprecation","ranges":[{"startOffset":2708,"endOffset":3341,"count":0}],"isBlockCoverage":false},{"functionName":"emitInvalidSegmentDeprecation","ranges":[{"startOffset":3854,"endOffset":4596,"count":0}],"isBlockCoverage":false},{"functionName":"emitLegacyIndexDeprecation","ranges":[{"startOffset":5033,"endOffset":6213,"count":0}],"isBlockCoverage":false},{"functionName":"legacyMainResolve","ranges":[{"startOffset":7304,"endOffset":8064,"count":0}],"isBlockCoverage":false},{"functionName":"finalizeResolution","ranges":[{"startOffset":8848,"endOffset":10318,"count":284},{"startOffset":8984,"endOffset":9137,"count":0},{"startOffset":9199,"endOffset":9383,"count":0},{"startOffset":9472,"endOffset":9508,"count":0},{"startOffset":9574,"endOffset":9666,"count":0},{"startOffset":9689,"endOffset":9977,"count":0},{"startOffset":10223,"endOffset":10228,"count":0}],"isBlockCoverage":true},{"functionName":"importNotDefined","ranges":[{"startOffset":10732,"endOffset":10943,"count":0}],"isBlockCoverage":false},{"functionName":"exportsNotFound","ranges":[{"startOffset":11339,"endOffset":11534,"count":0}],"isBlockCoverage":false},{"functionName":"throwInvalidSubpath","ranges":[{"startOffset":12172,"endOffset":12555,"count":0}],"isBlockCoverage":false},{"functionName":"invalidPackageTarget","ranges":[{"startOffset":13011,"endOffset":13389,"count":0}],"isBlockCoverage":false},{"functionName":"resolvePackageTargetString","ranges":[{"startOffset":14745,"endOffset":17498,"count":15},{"startOffset":14914,"endOffset":14925,"count":0},{"startOffset":14926,"endOffset":14962,"count":0},{"startOffset":14964,"endOffset":15048,"count":0},{"startOffset":15098,"endOffset":15655,"count":0},{"startOffset":15747,"endOffset":16357,"count":0},{"startOffset":16576,"endOffset":16660,"count":0},{"startOffset":16704,"endOffset":17497,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":15430,"endOffset":15443,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":15956,"endOffset":15969,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":16102,"endOffset":16115,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":16839,"endOffset":16852,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":17079,"endOffset":17092,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":17432,"endOffset":17445,"count":0}],"isBlockCoverage":false},{"functionName":"isArrayIndex","ranges":[{"startOffset":17690,"endOffset":17834,"count":115},{"startOffset":17786,"endOffset":17831,"count":0}],"isBlockCoverage":true},{"functionName":"resolvePackageTarget","ranges":[{"startOffset":18629,"endOffset":20879,"count":41},{"startOffset":18822,"endOffset":18976,"count":15},{"startOffset":18976,"endOffset":20762,"count":26},{"startOffset":19008,"endOffset":19854,"count":0},{"startOffset":20007,"endOffset":20235,"count":115},{"startOffset":20065,"endOffset":20229,"count":0},{"startOffset":20278,"endOffset":20687,"count":100},{"startOffset":20335,"endOffset":20357,"count":89},{"startOffset":20359,"endOffset":20681,"count":26},{"startOffset":20630,"endOffset":20643,"count":0},{"startOffset":20687,"endOffset":20762,"count":0},{"startOffset":20762,"endOffset":20878,"count":0}],"isBlockCoverage":true},{"functionName":"isConditionalExportsMainSugar","ranges":[{"startOffset":21163,"endOffset":22106,"count":15},{"startOffset":21295,"endOffset":21311,"count":0},{"startOffset":21367,"endOffset":21384,"count":0},{"startOffset":21524,"endOffset":22075,"count":2160},{"startOffset":21634,"endOffset":21691,"count":15},{"startOffset":21691,"endOffset":22071,"count":2145},{"startOffset":21747,"endOffset":22071,"count":0}],"isBlockCoverage":true},{"functionName":"packageExportsResolve","ranges":[{"startOffset":22603,"endOffset":25178,"count":15},{"startOffset":22811,"endOffset":22848,"count":0},{"startOffset":23250,"endOffset":23324,"count":0},{"startOffset":23355,"endOffset":25177,"count":0}],"isBlockCoverage":true},{"functionName":"patternKeyCompare","ranges":[{"startOffset":25552,"endOffset":26107,"count":0}],"isBlockCoverage":false},{"functionName":"packageImportsResolve","ranges":[{"startOffset":26594,"endOffset":29051,"count":0}],"isBlockCoverage":false},{"functionName":"getPackageType","ranges":[{"startOffset":29165,"endOffset":29278,"count":284}],"isBlockCoverage":true},{"functionName":"parsePackageName","ranges":[{"startOffset":29443,"endOffset":30501,"count":15},{"startOffset":29634,"endOffset":29862,"count":0},{"startOffset":29908,"endOffset":29923,"count":0},{"startOffset":30149,"endOffset":30184,"count":0},{"startOffset":30211,"endOffset":30330,"count":0},{"startOffset":30386,"endOffset":30390,"count":0}],"isBlockCoverage":true},{"functionName":"packageResolve","ranges":[{"startOffset":30825,"endOffset":32897,"count":15},{"startOffset":30939,"endOffset":30985,"count":0},{"startOffset":31444,"endOffset":32896,"count":0}],"isBlockCoverage":true},{"functionName":"isBareSpecifier","ranges":[{"startOffset":33008,"endOffset":33118,"count":0}],"isBlockCoverage":false},{"functionName":"isRelativeSpecifier","ranges":[{"startOffset":33237,"endOffset":33516,"count":571},{"startOffset":33307,"endOffset":33498,"count":536},{"startOffset":33365,"endOffset":33381,"count":466},{"startOffset":33381,"endOffset":33494,"count":70},{"startOffset":33498,"endOffset":33515,"count":35}],"isBlockCoverage":true},{"functionName":"shouldBeTreatedAsRelativeOrAbsolutePath","ranges":[{"startOffset":33665,"endOffset":33856,"count":571},{"startOffset":33751,"endOffset":33768,"count":0},{"startOffset":33797,"endOffset":33813,"count":0}],"isBlockCoverage":true},{"functionName":"moduleResolve","ranges":[{"startOffset":34219,"endOffset":35010,"count":284},{"startOffset":34545,"endOffset":34591,"count":268},{"startOffset":34591,"endOffset":34881,"count":16},{"startOffset":34636,"endOffset":34708,"count":0},{"startOffset":34769,"endOffset":34877,"count":15},{"startOffset":34919,"endOffset":34945,"count":0}],"isBlockCoverage":true},{"functionName":"resolveAsCommonJS","ranges":[{"startOffset":35172,"endOffset":36629,"count":0}],"isBlockCoverage":false},{"functionName":"checkIfDisallowedImport","ranges":[{"startOffset":37009,"endOffset":38381,"count":287},{"startOffset":37103,"endOffset":38379,"count":286},{"startOffset":37315,"endOffset":38375,"count":0}],"isBlockCoverage":true},{"functionName":"throwIfInvalidParentURL","ranges":[{"startOffset":38521,"endOffset":38794,"count":287},{"startOffset":38598,"endOffset":38649,"count":1},{"startOffset":38649,"endOffset":38686,"count":286},{"startOffset":38686,"endOffset":38706,"count":0},{"startOffset":38708,"endOffset":38792,"count":0}],"isBlockCoverage":true},{"functionName":"defaultResolve","ranges":[{"startOffset":39418,"endOffset":43040,"count":287},{"startOffset":39566,"endOffset":39585,"count":286},{"startOffset":39575,"endOffset":39585,"count":0},{"startOffset":39587,"endOffset":40396,"count":0},{"startOffset":40438,"endOffset":40543,"count":286},{"startOffset":40500,"endOffset":40539,"count":0},{"startOffset":40627,"endOffset":40686,"count":268},{"startOffset":40686,"endOffset":40734,"count":19},{"startOffset":40734,"endOffset":41008,"count":272},{"startOffset":40912,"endOffset":41000,"count":0},{"startOffset":41015,"endOffset":41074,"count":0},{"startOffset":41079,"endOffset":41114,"count":15},{"startOffset":41448,"endOffset":41471,"count":0},{"startOffset":41536,"endOffset":41566,"count":272},{"startOffset":41568,"endOffset":41615,"count":3},{"startOffset":41615,"endOffset":41674,"count":284},{"startOffset":41674,"endOffset":42181,"count":1},{"startOffset":42134,"endOffset":42177,"count":0},{"startOffset":42181,"endOffset":42337,"count":284},{"startOffset":42337,"endOffset":42359,"count":1},{"startOffset":42360,"endOffset":42378,"count":283},{"startOffset":42391,"endOffset":42814,"count":0},{"startOffset":42814,"endOffset":43039,"count":284}],"isBlockCoverage":true},{"functionName":"decorateErrorWithCommonJSHints","ranges":[{"startOffset":43303,"endOffset":43779,"count":0}],"isBlockCoverage":false},{"functionName":"defaultResolve","ranges":[{"startOffset":44205,"endOffset":44596,"count":0}],"isBlockCoverage":false}]},{"scriptId":"87","url":"node:internal/modules/esm/package_config","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2215,"count":1}],"isBlockCoverage":false},{"functionName":"getPackageScopeConfig","ranges":[{"startOffset":1072,"endOffset":2165,"count":299},{"startOffset":1190,"endOffset":1910,"count":325},{"startOffset":1324,"endOffset":1344,"count":0},{"startOffset":1534,"endOffset":1569,"count":299},{"startOffset":1569,"endOffset":1886,"count":26},{"startOffset":1886,"endOffset":1906,"count":0},{"startOffset":1910,"endOffset":2164,"count":0}],"isBlockCoverage":true}]},{"scriptId":"88","url":"node:internal/modules/esm/get_format","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6669,"count":1}],"isBlockCoverage":false},{"functionName":"node:","ranges":[{"startOffset":953,"endOffset":984,"count":0}],"isBlockCoverage":false},{"functionName":"getDataProtocolModuleFormat","ranges":[{"startOffset":1049,"endOffset":1265,"count":0}],"isBlockCoverage":false},{"functionName":"extname","ranges":[{"startOffset":1540,"endOffset":1899,"count":284},{"startOffset":1640,"endOffset":1884,"count":852},{"startOffset":1702,"endOffset":1737,"count":0},{"startOffset":1745,"endOffset":1874,"count":284},{"startOffset":1833,"endOffset":1837,"count":0},{"startOffset":1884,"endOffset":1898,"count":0}],"isBlockCoverage":true},{"functionName":"underNodeModules","ranges":[{"startOffset":2129,"endOffset":2350,"count":0}],"isBlockCoverage":false},{"functionName":"getFileProtocolModuleFormat","ranges":[{"startOffset":2491,"endOffset":5330,"count":284},{"startOffset":2772,"endOffset":3264,"count":0},{"startOffset":3271,"endOffset":3394,"count":0},{"startOffset":3401,"endOffset":3864,"count":0},{"startOffset":3874,"endOffset":5329,"count":0}],"isBlockCoverage":true},{"functionName":"getHttpProtocolModuleFormat","ranges":[{"startOffset":5466,"endOffset":5811,"count":0}],"isBlockCoverage":false},{"functionName":"defaultGetFormatWithoutErrors","ranges":[{"startOffset":5956,"endOffset":6191,"count":284},{"startOffset":6110,"endOffset":6132,"count":0}],"isBlockCoverage":true},{"functionName":"defaultGetFormat","ranges":[{"startOffset":6336,"endOffset":6559,"count":0}],"isBlockCoverage":false}]},{"scriptId":"89","url":"node:internal/modules/esm/formats","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1798,"count":1}],"isBlockCoverage":false},{"functionName":"mimeToFormat","ranges":[{"startOffset":660,"endOffset":998,"count":0}],"isBlockCoverage":false},{"functionName":"getFormatOfExtensionlessFile","ranges":[{"startOffset":1368,"endOffset":1704,"count":0}],"isBlockCoverage":false}]},{"scriptId":"90","url":"node:internal/modules/esm/handle_process_exit","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":432,"count":1}],"isBlockCoverage":false},{"functionName":"handleProcessExit","ranges":[{"startOffset":306,"endOffset":387,"count":0}],"isBlockCoverage":false}]},{"scriptId":"91","url":"node:internal/modules/esm/module_job","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8796,"count":1}],"isBlockCoverage":false},{"functionName":"isCommonJSGlobalLikeNotDefinedError","ranges":[{"startOffset":917,"endOffset":1048,"count":0}],"isBlockCoverage":false},{"functionName":"ModuleJob","ranges":[{"startOffset":1286,"endOffset":3293,"count":92},{"startOffset":1811,"endOffset":1914,"count":0}],"isBlockCoverage":true},{"functionName":"link","ranges":[{"startOffset":2085,"endOffset":2910,"count":92}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2541,"endOffset":2746,"count":285}],"isBlockCoverage":true},{"functionName":"instantiate","ranges":[{"startOffset":3297,"endOffset":3442,"count":3},{"startOffset":3354,"endOffset":3408,"count":2}],"isBlockCoverage":true},{"functionName":"_instantiate","ranges":[{"startOffset":3446,"endOffset":7100,"count":2},{"startOffset":3906,"endOffset":4083,"count":0},{"startOffset":4140,"endOffset":6853,"count":0},{"startOffset":6900,"endOffset":7096,"count":93}],"isBlockCoverage":true},{"functionName":"addJobsToDependencyGraph","ranges":[{"startOffset":3545,"endOffset":3805,"count":287},{"startOffset":3606,"endOffset":3631,"count":194},{"startOffset":3631,"endOffset":3804,"count":93}],"isBlockCoverage":true},{"functionName":"runSync","ranges":[{"startOffset":7104,"endOffset":7504,"count":0}],"isBlockCoverage":false},{"functionName":"run","ranges":[{"startOffset":7508,"endOffset":8716,"count":3},{"startOffset":7683,"endOffset":8659,"count":0}],"isBlockCoverage":true}]},{"scriptId":"92","url":"node:internal/modules/esm/load","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7608,"count":1}],"isBlockCoverage":false},{"functionName":"getSource","ranges":[{"startOffset":1236,"endOffset":2463,"count":90},{"startOffset":1504,"endOffset":2329,"count":0},{"startOffset":2342,"endOffset":2352,"count":0},{"startOffset":2354,"endOffset":2410,"count":0}],"isBlockCoverage":true},{"functionName":"getSourceSync","ranges":[{"startOffset":2646,"endOffset":3385,"count":0}],"isBlockCoverage":false},{"functionName":"defaultLoad","ranges":[{"startOffset":3506,"endOffset":4914,"count":92},{"startOffset":3690,"endOffset":3725,"count":0},{"startOffset":3726,"endOffset":3758,"count":0},{"startOffset":3760,"endOffset":3967,"count":0},{"startOffset":4119,"endOffset":4169,"count":2},{"startOffset":4169,"endOffset":4779,"count":90},{"startOffset":4201,"endOffset":4228,"count":0},{"startOffset":4410,"endOffset":4775,"count":0}],"isBlockCoverage":true},{"functionName":"defaultLoadSync","ranges":[{"startOffset":5427,"endOffset":6067,"count":0}],"isBlockCoverage":false},{"functionName":"throwIfUnsupportedURLScheme","ranges":[{"startOffset":6255,"endOffset":6887,"count":92},{"startOffset":6485,"endOffset":6512,"count":2},{"startOffset":6513,"endOffset":6540,"count":2},{"startOffset":6541,"endOffset":6670,"count":0},{"startOffset":6675,"endOffset":6885,"count":0}],"isBlockCoverage":true},{"functionName":"throwUnknownModuleFormat","ranges":[{"startOffset":7266,"endOffset":7504,"count":0}],"isBlockCoverage":false}]},{"scriptId":"93","url":"node:internal/fs/promises","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":31007,"count":1}],"isBlockCoverage":false},{"functionName":"lazyLoadCpPromises","ranges":[{"startOffset":3200,"endOffset":3292,"count":0}],"isBlockCoverage":false},{"functionName":"lazyFsStreams","ranges":[{"startOffset":3354,"endOffset":3437,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":3439,"endOffset":9526,"count":90}],"isBlockCoverage":false},{"functionName":"FileHandle","ranges":[{"startOffset":3580,"endOffset":3757,"count":90},{"startOffset":3694,"endOffset":3698,"count":0}],"isBlockCoverage":true},{"functionName":"getAsyncId","ranges":[{"startOffset":3761,"endOffset":3818,"count":0}],"isBlockCoverage":false},{"functionName":"get fd","ranges":[{"startOffset":3822,"endOffset":3858,"count":180}],"isBlockCoverage":true},{"functionName":"appendFile","ranges":[{"startOffset":3862,"endOffset":3944,"count":0}],"isBlockCoverage":false},{"functionName":"chmod","ranges":[{"startOffset":3948,"endOffset":4004,"count":0}],"isBlockCoverage":false},{"functionName":"chown","ranges":[{"startOffset":4008,"endOffset":4072,"count":0}],"isBlockCoverage":false},{"functionName":"datasync","ranges":[{"startOffset":4076,"endOffset":4128,"count":0}],"isBlockCoverage":false},{"functionName":"sync","ranges":[{"startOffset":4132,"endOffset":4176,"count":0}],"isBlockCoverage":false},{"functionName":"read","ranges":[{"startOffset":4180,"endOffset":4289,"count":0}],"isBlockCoverage":false},{"functionName":"readv","ranges":[{"startOffset":4293,"endOffset":4374,"count":0}],"isBlockCoverage":false},{"functionName":"readFile","ranges":[{"startOffset":4378,"endOffset":4445,"count":0}],"isBlockCoverage":false},{"functionName":"readLines","ranges":[{"startOffset":4449,"endOffset":4592,"count":0}],"isBlockCoverage":false},{"functionName":"stat","ranges":[{"startOffset":4596,"endOffset":4656,"count":0}],"isBlockCoverage":false},{"functionName":"truncate","ranges":[{"startOffset":4660,"endOffset":4724,"count":0}],"isBlockCoverage":false},{"functionName":"utimes","ranges":[{"startOffset":4728,"endOffset":4802,"count":0}],"isBlockCoverage":false},{"functionName":"write","ranges":[{"startOffset":4806,"endOffset":4917,"count":0}],"isBlockCoverage":false},{"functionName":"writev","ranges":[{"startOffset":4921,"endOffset":5004,"count":0}],"isBlockCoverage":false},{"functionName":"writeFile","ranges":[{"startOffset":5008,"endOffset":5089,"count":0}],"isBlockCoverage":false},{"functionName":"close","ranges":[{"startOffset":5101,"endOffset":5893,"count":90},{"startOffset":5135,"endOffset":5173,"count":0},{"startOffset":5204,"endOffset":5245,"count":0},{"startOffset":5471,"endOffset":5832,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5413,"endOffset":5455,"count":90}],"isBlockCoverage":true},{"functionName":".SafePromisePrototypeFinally.","ranges":[{"startOffset":5556,"endOffset":5668,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":5671,"endOffset":5816,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":5898,"endOffset":5957,"count":0}],"isBlockCoverage":false},{"functionName":"readableWebStream","ranges":[{"startOffset":6152,"endOffset":7838,"count":0}],"isBlockCoverage":false},{"functionName":"createReadStream","ranges":[{"startOffset":8136,"endOffset":8287,"count":0}],"isBlockCoverage":false},{"functionName":"createWriteStream","ranges":[{"startOffset":8560,"endOffset":8714,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":8718,"endOffset":9118,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":9122,"endOffset":9175,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":9179,"endOffset":9266,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":9270,"endOffset":9303,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":9307,"endOffset":9524,"count":0}],"isBlockCoverage":false},{"functionName":"handleFdClose","ranges":[{"startOffset":9528,"endOffset":9899,"count":90}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9639,"endOffset":9698,"count":90}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9685,"endOffset":9697,"count":90}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9704,"endOffset":9891,"count":0}],"isBlockCoverage":false},{"functionName":"handleFdSync","ranges":[{"startOffset":9901,"endOffset":10184,"count":0}],"isBlockCoverage":false},{"functionName":"fsCall","ranges":[{"startOffset":10186,"endOffset":10646,"count":0}],"isBlockCoverage":false},{"functionName":"checkAborted","ranges":[{"startOffset":10648,"endOffset":10768,"count":360},{"startOffset":10692,"endOffset":10701,"count":0},{"startOffset":10707,"endOffset":10766,"count":0}],"isBlockCoverage":true},{"functionName":"writeFileHandle","ranges":[{"startOffset":10770,"endOffset":11912,"count":0}],"isBlockCoverage":false},{"functionName":"readFileHandle","ranges":[{"startOffset":11914,"endOffset":14053,"count":90},{"startOffset":12066,"endOffset":12096,"count":0},{"startOffset":12376,"endOffset":12414,"count":0},{"startOffset":12447,"endOffset":12495,"count":0},{"startOffset":12528,"endOffset":12566,"count":0},{"startOffset":12808,"endOffset":12880,"count":0},{"startOffset":13024,"endOffset":13028,"count":0},{"startOffset":13113,"endOffset":13169,"count":0},{"startOffset":13263,"endOffset":13274,"count":0},{"startOffset":13331,"endOffset":13391,"count":0},{"startOffset":13439,"endOffset":13453,"count":0},{"startOffset":13455,"endOffset":13565,"count":0},{"startOffset":13596,"endOffset":14047,"count":0}],"isBlockCoverage":true},{"functionName":"access","ranges":[{"startOffset":14206,"endOffset":14427,"count":0}],"isBlockCoverage":false},{"functionName":"cp","ranges":[{"startOffset":14429,"endOffset":14698,"count":0}],"isBlockCoverage":false},{"functionName":"copyFile","ranges":[{"startOffset":14700,"endOffset":15058,"count":0}],"isBlockCoverage":false},{"functionName":"open","ranges":[{"startOffset":15178,"endOffset":15503,"count":90}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":15505,"endOffset":16886,"count":0}],"isBlockCoverage":false},{"functionName":"readv","ranges":[{"startOffset":16888,"endOffset":17225,"count":0}],"isBlockCoverage":false},{"functionName":"write","ranges":[{"startOffset":17227,"endOffset":18476,"count":0}],"isBlockCoverage":false},{"functionName":"writev","ranges":[{"startOffset":18478,"endOffset":18920,"count":0}],"isBlockCoverage":false},{"functionName":"rename","ranges":[{"startOffset":18922,"endOffset":19228,"count":0}],"isBlockCoverage":false},{"functionName":"truncate","ranges":[{"startOffset":19230,"endOffset":19363,"count":0}],"isBlockCoverage":false},{"functionName":"ftruncate","ranges":[{"startOffset":19365,"endOffset":19524,"count":0}],"isBlockCoverage":false},{"functionName":"rm","ranges":[{"startOffset":19526,"endOffset":19730,"count":0}],"isBlockCoverage":false},{"functionName":"rmdir","ranges":[{"startOffset":19732,"endOffset":20103,"count":0}],"isBlockCoverage":false},{"functionName":"fdatasync","ranges":[{"startOffset":20105,"endOffset":20194,"count":0}],"isBlockCoverage":false},{"functionName":"fsync","ranges":[{"startOffset":20196,"endOffset":20277,"count":0}],"isBlockCoverage":false},{"functionName":"mkdir","ranges":[{"startOffset":20279,"endOffset":20756,"count":0}],"isBlockCoverage":false},{"functionName":"readdirRecursive","ranges":[{"startOffset":20758,"endOffset":22432,"count":0}],"isBlockCoverage":false},{"functionName":"readdir","ranges":[{"startOffset":22434,"endOffset":22861,"count":0}],"isBlockCoverage":false},{"functionName":"readlink","ranges":[{"startOffset":22863,"endOffset":23102,"count":0}],"isBlockCoverage":false},{"functionName":"symlink","ranges":[{"startOffset":23104,"endOffset":24171,"count":0}],"isBlockCoverage":false},{"functionName":"fstat","ranges":[{"startOffset":24173,"endOffset":24351,"count":0}],"isBlockCoverage":false},{"functionName":"lstat","ranges":[{"startOffset":24353,"endOffset":24623,"count":0}],"isBlockCoverage":false},{"functionName":"stat","ranges":[{"startOffset":24625,"endOffset":24892,"count":0}],"isBlockCoverage":false},{"functionName":"statfs","ranges":[{"startOffset":24894,"endOffset":25168,"count":0}],"isBlockCoverage":false},{"functionName":"link","ranges":[{"startOffset":25170,"endOffset":25493,"count":0}],"isBlockCoverage":false},{"functionName":"unlink","ranges":[{"startOffset":25495,"endOffset":25633,"count":0}],"isBlockCoverage":false},{"functionName":"fchmod","ranges":[{"startOffset":25635,"endOffset":25768,"count":0}],"isBlockCoverage":false},{"functionName":"chmod","ranges":[{"startOffset":25770,"endOffset":25956,"count":0}],"isBlockCoverage":false},{"functionName":"lchmod","ranges":[{"startOffset":25958,"endOffset":26186,"count":0}],"isBlockCoverage":false},{"functionName":"lchown","ranges":[{"startOffset":26188,"endOffset":26464,"count":0}],"isBlockCoverage":false},{"functionName":"fchown","ranges":[{"startOffset":26466,"endOffset":26663,"count":0}],"isBlockCoverage":false},{"functionName":"chown","ranges":[{"startOffset":26665,"endOffset":26938,"count":0}],"isBlockCoverage":false},{"functionName":"utimes","ranges":[{"startOffset":26940,"endOffset":27212,"count":0}],"isBlockCoverage":false},{"functionName":"futimes","ranges":[{"startOffset":27214,"endOffset":27413,"count":0}],"isBlockCoverage":false},{"functionName":"lutimes","ranges":[{"startOffset":27415,"endOffset":27692,"count":0}],"isBlockCoverage":false},{"functionName":"realpath","ranges":[{"startOffset":27694,"endOffset":27867,"count":0}],"isBlockCoverage":false},{"functionName":"mkdtemp","ranges":[{"startOffset":27869,"endOffset":28248,"count":0}],"isBlockCoverage":false},{"functionName":"writeFile","ranges":[{"startOffset":28250,"endOffset":29124,"count":0}],"isBlockCoverage":false},{"functionName":"isCustomIterable","ranges":[{"startOffset":29126,"endOffset":29240,"count":0}],"isBlockCoverage":false},{"functionName":"appendFile","ranges":[{"startOffset":29242,"endOffset":29483,"count":0}],"isBlockCoverage":false},{"functionName":"readFile","ranges":[{"startOffset":29485,"endOffset":29829,"count":90},{"startOffset":29602,"endOffset":29608,"count":0},{"startOffset":29649,"endOffset":29686,"count":0}],"isBlockCoverage":true},{"functionName":"_watch","ranges":[{"startOffset":29831,"endOffset":30496,"count":0}],"isBlockCoverage":false}]},{"scriptId":"94","url":"node:internal/fs/rimraf","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7454,"count":1}],"isBlockCoverage":false},{"functionName":"rimraf","ranges":[{"startOffset":1175,"endOffset":1635,"count":0}],"isBlockCoverage":false},{"functionName":"_rimraf","ranges":[{"startOffset":1638,"endOffset":2496,"count":0}],"isBlockCoverage":false},{"functionName":"fixWinEPERM","ranges":[{"startOffset":2499,"endOffset":2934,"count":0}],"isBlockCoverage":false},{"functionName":"_rmdir","ranges":[{"startOffset":2937,"endOffset":3235,"count":0}],"isBlockCoverage":false},{"functionName":"_rmchildren","ranges":[{"startOffset":3238,"endOffset":3925,"count":0}],"isBlockCoverage":false},{"functionName":"rimrafPromises","ranges":[{"startOffset":3928,"endOffset":4126,"count":0}],"isBlockCoverage":false},{"functionName":"rimrafSync","ranges":[{"startOffset":4129,"endOffset":4812,"count":0}],"isBlockCoverage":false},{"functionName":"_unlinkSync","ranges":[{"startOffset":4815,"endOffset":5444,"count":0}],"isBlockCoverage":false},{"functionName":"_rmdirSync","ranges":[{"startOffset":5447,"endOffset":6944,"count":0}],"isBlockCoverage":false},{"functionName":"fixWinEPERMSync","ranges":[{"startOffset":6947,"endOffset":7394,"count":0}],"isBlockCoverage":false}]},{"scriptId":"95","url":"node:internal/fs/dir","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8071,"count":1}],"isBlockCoverage":false},{"functionName":"Dir","ranges":[{"startOffset":1177,"endOffset":1993,"count":0}],"isBlockCoverage":false},{"functionName":"get path","ranges":[{"startOffset":1997,"endOffset":2040,"count":0}],"isBlockCoverage":false},{"functionName":"read","ranges":[{"startOffset":2044,"endOffset":2111,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2115,"endOffset":3841,"count":0}],"isBlockCoverage":false},{"functionName":"processReadResult","ranges":[{"startOffset":3845,"endOffset":4099,"count":0}],"isBlockCoverage":false},{"functionName":"readSyncRecursive","ranges":[{"startOffset":4103,"endOffset":4676,"count":0}],"isBlockCoverage":false},{"functionName":"readSync","ranges":[{"startOffset":4680,"endOffset":5656,"count":0}],"isBlockCoverage":false},{"functionName":"close","ranges":[{"startOffset":5660,"endOffset":6349,"count":0}],"isBlockCoverage":false},{"functionName":"closeSync","ranges":[{"startOffset":6353,"endOffset":6730,"count":0}],"isBlockCoverage":false},{"functionName":"entries","ranges":[{"startOffset":6734,"endOffset":6997,"count":0}],"isBlockCoverage":false},{"functionName":"opendir","ranges":[{"startOffset":7177,"endOffset":7757,"count":0}],"isBlockCoverage":false},{"functionName":"opendirSync","ranges":[{"startOffset":7759,"endOffset":8014,"count":0}],"isBlockCoverage":false}]},{"scriptId":"96","url":"node:string_decoder","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":5213,"count":1}],"isBlockCoverage":false},{"functionName":"normalizeEncoding","ranges":[{"startOffset":2129,"endOffset":2391,"count":0}],"isBlockCoverage":false},{"functionName":"StringDecoder","ranges":[{"startOffset":2705,"endOffset":2904,"count":0}],"isBlockCoverage":false},{"functionName":"write","ranges":[{"startOffset":3227,"endOffset":3612,"count":0}],"isBlockCoverage":false},{"functionName":"end","ranges":[{"startOffset":3889,"endOffset":4080,"count":0}],"isBlockCoverage":false},{"functionName":"text","ranges":[{"startOffset":4291,"endOffset":4448,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4586,"endOffset":4799,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4891,"endOffset":4954,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":5047,"endOffset":5162,"count":0}],"isBlockCoverage":false}]},{"scriptId":"97","url":"node:internal/fs/watchers","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":11242,"count":1}],"isBlockCoverage":false},{"functionName":"emitStop","ranges":[{"startOffset":1420,"endOffset":1468,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher","ranges":[{"startOffset":1470,"endOffset":1700,"count":0}],"isBlockCoverage":false},{"functionName":"onchange","ranges":[{"startOffset":1820,"endOffset":2177,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher.","ranges":[{"startOffset":2565,"endOffset":3399,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher.start","ranges":[{"startOffset":3620,"endOffset":3628,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher.stop","ranges":[{"startOffset":3874,"endOffset":4155,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher.","ranges":[{"startOffset":4244,"endOffset":4671,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher.ref","ranges":[{"startOffset":4702,"endOffset":4984,"count":0}],"isBlockCoverage":false},{"functionName":"StatWatcher.unref","ranges":[{"startOffset":5017,"endOffset":5267,"count":0}],"isBlockCoverage":false},{"functionName":"FSWatcher","ranges":[{"startOffset":5271,"endOffset":6239,"count":0}],"isBlockCoverage":false},{"functionName":"FSWatcher.","ranges":[{"startOffset":6776,"endOffset":7686,"count":0}],"isBlockCoverage":false},{"functionName":"FSWatcher.start","ranges":[{"startOffset":7903,"endOffset":7911,"count":0}],"isBlockCoverage":false},{"functionName":"FSWatcher.close","ranges":[{"startOffset":8034,"endOffset":8371,"count":0}],"isBlockCoverage":false},{"functionName":"FSWatcher.ref","ranges":[{"startOffset":8400,"endOffset":8469,"count":0}],"isBlockCoverage":false},{"functionName":"FSWatcher.unref","ranges":[{"startOffset":8500,"endOffset":8571,"count":0}],"isBlockCoverage":false},{"functionName":"emitCloseNT","ranges":[{"startOffset":8574,"endOffset":8626,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":8850,"endOffset":8886,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":8890,"endOffset":8931,"count":0}],"isBlockCoverage":false},{"functionName":"watch","ranges":[{"startOffset":8967,"endOffset":11110,"count":0}],"isBlockCoverage":false}]},{"scriptId":"98","url":"node:internal/fs/recursive_watch","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7634,"count":1}],"isBlockCoverage":false},{"functionName":"lazyLoadFsPromises","ranges":[{"startOffset":812,"endOffset":919,"count":0}],"isBlockCoverage":false},{"functionName":"lazyLoadFsSync","ranges":[{"startOffset":921,"endOffset":1007,"count":0}],"isBlockCoverage":false},{"functionName":"traverse","ranges":[{"startOffset":1037,"endOffset":1618,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1620,"endOffset":7580,"count":0}],"isBlockCoverage":false}]},{"scriptId":"99","url":"node:internal/streams/utils","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8934,"count":1}],"isBlockCoverage":false},{"functionName":"isReadableNodeStream","ranges":[{"startOffset":1117,"endOffset":1534,"count":0}],"isBlockCoverage":false},{"functionName":"isWritableNodeStream","ranges":[{"startOffset":1536,"endOffset":1756,"count":0}],"isBlockCoverage":false},{"functionName":"isDuplexNodeStream","ranges":[{"startOffset":1758,"endOffset":1957,"count":0}],"isBlockCoverage":false},{"functionName":"isNodeStream","ranges":[{"startOffset":1959,"endOffset":2230,"count":0}],"isBlockCoverage":false},{"functionName":"isReadableStream","ranges":[{"startOffset":2232,"endOffset":2446,"count":0}],"isBlockCoverage":false},{"functionName":"isWritableStream","ranges":[{"startOffset":2448,"endOffset":2616,"count":0}],"isBlockCoverage":false},{"functionName":"isTransformStream","ranges":[{"startOffset":2618,"endOffset":2785,"count":0}],"isBlockCoverage":false},{"functionName":"isWebStream","ranges":[{"startOffset":2787,"endOffset":2899,"count":0}],"isBlockCoverage":false},{"functionName":"isIterable","ranges":[{"startOffset":2901,"endOffset":3231,"count":0}],"isBlockCoverage":false},{"functionName":"isDestroyed","ranges":[{"startOffset":3233,"endOffset":3496,"count":0}],"isBlockCoverage":false},{"functionName":"isWritableEnded","ranges":[{"startOffset":3520,"endOffset":3811,"count":0}],"isBlockCoverage":false},{"functionName":"isWritableFinished","ranges":[{"startOffset":3839,"endOffset":4236,"count":0}],"isBlockCoverage":false},{"functionName":"isReadableEnded","ranges":[{"startOffset":4265,"endOffset":4566,"count":0}],"isBlockCoverage":false},{"functionName":"isReadableFinished","ranges":[{"startOffset":4591,"endOffset":4939,"count":0}],"isBlockCoverage":false},{"functionName":"isReadable","ranges":[{"startOffset":4941,"endOffset":5241,"count":0}],"isBlockCoverage":false},{"functionName":"isWritable","ranges":[{"startOffset":5243,"endOffset":5540,"count":0}],"isBlockCoverage":false},{"functionName":"isFinished","ranges":[{"startOffset":5542,"endOffset":5856,"count":0}],"isBlockCoverage":false},{"functionName":"isWritableErrored","ranges":[{"startOffset":5858,"endOffset":6070,"count":0}],"isBlockCoverage":false},{"functionName":"isReadableErrored","ranges":[{"startOffset":6072,"endOffset":6284,"count":0}],"isBlockCoverage":false},{"functionName":"isClosed","ranges":[{"startOffset":6286,"endOffset":6791,"count":0}],"isBlockCoverage":false},{"functionName":"isOutgoingMessage","ranges":[{"startOffset":6793,"endOffset":7045,"count":0}],"isBlockCoverage":false},{"functionName":"isServerResponse","ranges":[{"startOffset":7047,"endOffset":7174,"count":0}],"isBlockCoverage":false},{"functionName":"isServerRequest","ranges":[{"startOffset":7176,"endOffset":7364,"count":0}],"isBlockCoverage":false},{"functionName":"willEmitClose","ranges":[{"startOffset":7366,"endOffset":7704,"count":0}],"isBlockCoverage":false},{"functionName":"isDisturbed","ranges":[{"startOffset":7706,"endOffset":7851,"count":0}],"isBlockCoverage":false},{"functionName":"isErrored","ranges":[{"startOffset":7853,"endOffset":8158,"count":0}],"isBlockCoverage":false}]},{"scriptId":"100","url":"node:internal/readline/interface","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":39029,"count":1}],"isBlockCoverage":false},{"functionName":"InterfaceConstructor","ranges":[{"startOffset":3781,"endOffset":9286,"count":0}],"isBlockCoverage":false},{"functionName":"Interface","ranges":[{"startOffset":9527,"endOffset":9627,"count":0}],"isBlockCoverage":false},{"functionName":"get columns","ranges":[{"startOffset":9630,"endOffset":9742,"count":0}],"isBlockCoverage":false},{"functionName":"setPrompt","ranges":[{"startOffset":9851,"endOffset":9902,"count":0}],"isBlockCoverage":false},{"functionName":"getPrompt","ranges":[{"startOffset":9996,"endOffset":10039,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10043,"endOffset":10234,"count":0}],"isBlockCoverage":false},{"functionName":"prompt","ranges":[{"startOffset":10373,"endOffset":10627,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10631,"endOffset":10938,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10942,"endOffset":11184,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":11188,"endOffset":11275,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":11279,"endOffset":11447,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":11451,"endOffset":11648,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":11652,"endOffset":12830,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":12834,"endOffset":13839,"count":0}],"isBlockCoverage":false},{"functionName":"close","ranges":[{"startOffset":13923,"endOffset":14094,"count":0}],"isBlockCoverage":false},{"functionName":"pause","ranges":[{"startOffset":14175,"endOffset":14306,"count":0}],"isBlockCoverage":false},{"functionName":"resume","ranges":[{"startOffset":14398,"endOffset":14534,"count":0}],"isBlockCoverage":false},{"functionName":"write","ranges":[{"startOffset":14805,"endOffset":14964,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":14968,"endOffset":16702,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":16706,"endOffset":17375,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":17379,"endOffset":17778,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":17782,"endOffset":19990,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":19994,"endOffset":20455,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":20459,"endOffset":20717,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":20721,"endOffset":21203,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":21207,"endOffset":21688,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":21692,"endOffset":22452,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":22456,"endOffset":22883,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":22887,"endOffset":23165,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":23169,"endOffset":23427,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":23431,"endOffset":23691,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":23695,"endOffset":23850,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":23854,"endOffset":24529,"count":0}],"isBlockCoverage":false},{"functionName":"clearLine","ranges":[{"startOffset":24533,"endOffset":24682,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":24686,"endOffset":24840,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":24844,"endOffset":25031,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":25035,"endOffset":25343,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":25347,"endOffset":25655,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":26090,"endOffset":26724,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":26728,"endOffset":27436,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":27511,"endOffset":28451,"count":0}],"isBlockCoverage":false},{"functionName":"getCursorPos","ranges":[{"startOffset":28628,"endOffset":28797,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":28916,"endOffset":29473,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":29510,"endOffset":37760,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":38068,"endOffset":38448,"count":0}],"isBlockCoverage":false}]},{"scriptId":"101","url":"node:internal/readline/utils","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":12396,"count":1}],"isBlockCoverage":false},{"functionName":"CSI","ranges":[{"startOffset":385,"endOffset":579,"count":4},{"startOffset":544,"endOffset":559,"count":0}],"isBlockCoverage":true},{"functionName":"charLengthLeft","ranges":[{"startOffset":958,"endOffset":1220,"count":0}],"isBlockCoverage":false},{"functionName":"charLengthAt","ranges":[{"startOffset":1222,"endOffset":1484,"count":0}],"isBlockCoverage":false},{"functionName":"emitKeys","ranges":[{"startOffset":2213,"endOffset":11840,"count":0}],"isBlockCoverage":false},{"functionName":"commonPrefix","ranges":[{"startOffset":11870,"endOffset":12283,"count":0}],"isBlockCoverage":false}]},{"scriptId":"102","url":"node:internal/readline/callbacks","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2754,"count":1}],"isBlockCoverage":false},{"functionName":"cursorTo","ranges":[{"startOffset":460,"endOffset":1146,"count":0}],"isBlockCoverage":false},{"functionName":"moveCursor","ranges":[{"startOffset":1210,"endOffset":1722,"count":0}],"isBlockCoverage":false},{"functionName":"clearLine","ranges":[{"startOffset":1869,"endOffset":2272,"count":0}],"isBlockCoverage":false},{"functionName":"clearScreenDown","ranges":[{"startOffset":2349,"endOffset":2672,"count":0}],"isBlockCoverage":false}]},{"scriptId":"103","url":"file:///home/dmonad/ylabs/lib0/test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2191,"count":1},{"startOffset":1688,"endOffset":1727,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2098,"endOffset":2189,"count":1},{"startOffset":2179,"endOffset":2182,"count":0}],"isBlockCoverage":true}]},{"scriptId":"104","url":"file:///home/dmonad/ylabs/lib0/testing.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":26843,"count":1},{"startOffset":1830,"endOffset":1876,"count":0},{"startOffset":3110,"endOffset":3140,"count":0},{"startOffset":3215,"endOffset":3239,"count":0}],"isBlockCoverage":true},{"functionName":"TestCase","ranges":[{"startOffset":1985,"endOffset":2357,"count":137}],"isBlockCoverage":true},{"functionName":"resetSeed","ranges":[{"startOffset":2361,"endOffset":2423,"count":114970}],"isBlockCoverage":true},{"functionName":"get seed","ranges":[{"startOffset":2482,"endOffset":2674,"count":87972},{"startOffset":2633,"endOffset":2642,"count":0}],"isBlockCoverage":true},{"functionName":"get prng","ranges":[{"startOffset":2820,"endOffset":2963,"count":107168},{"startOffset":2888,"endOffset":2937,"count":87969}],"isBlockCoverage":true},{"functionName":"run","ranges":[{"startOffset":3483,"endOffset":6191,"count":137},{"startOffset":3741,"endOffset":3762,"count":0},{"startOffset":4069,"endOffset":4108,"count":0},{"startOffset":4272,"endOffset":4635,"count":115107},{"startOffset":4338,"endOffset":4363,"count":27},{"startOffset":4355,"endOffset":4363,"count":23},{"startOffset":4370,"endOffset":4407,"count":6},{"startOffset":4522,"endOffset":4537,"count":114987},{"startOffset":4538,"endOffset":4576,"count":114987},{"startOffset":4578,"endOffset":4606,"count":114970},{"startOffset":4606,"endOffset":4631,"count":137},{"startOffset":4656,"endOffset":4694,"count":114970},{"startOffset":4774,"endOffset":4806,"count":6},{"startOffset":4808,"endOffset":4837,"count":0},{"startOffset":5068,"endOffset":5196,"count":0},{"startOffset":5274,"endOffset":5278,"count":102},{"startOffset":5279,"endOffset":5301,"count":35},{"startOffset":5331,"endOffset":5346,"count":17},{"startOffset":5352,"endOffset":5641,"count":17},{"startOffset":5646,"endOffset":5688,"count":120},{"startOffset":5709,"endOffset":6041,"count":6},{"startOffset":5857,"endOffset":6012,"count":0},{"startOffset":6041,"endOffset":6172,"count":131}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4985,"endOffset":5000,"count":1311793}],"isBlockCoverage":true},{"functionName":"describe","ranges":[{"startOffset":6545,"endOffset":6626,"count":149}],"isBlockCoverage":true},{"functionName":"info","ranges":[{"startOffset":6894,"endOffset":6920,"count":77}],"isBlockCoverage":true},{"functionName":"group","ranges":[{"startOffset":7480,"endOffset":7591,"count":30}],"isBlockCoverage":true},{"functionName":"groupAsync","ranges":[{"startOffset":8088,"endOffset":8211,"count":15}],"isBlockCoverage":true},{"functionName":"measureTime","ranges":[{"startOffset":8709,"endOffset":8954,"count":178}],"isBlockCoverage":true},{"functionName":"measureTimeAsync","ranges":[{"startOffset":9491,"endOffset":9748,"count":12}],"isBlockCoverage":true},{"functionName":"compareArrays","ranges":[{"startOffset":9894,"endOffset":10083,"count":73},{"startOffset":9959,"endOffset":9976,"count":1},{"startOffset":9976,"endOffset":10015,"count":72},{"startOffset":10015,"endOffset":10067,"count":606811},{"startOffset":10042,"endOffset":10063,"count":1},{"startOffset":10067,"endOffset":10082,"count":71}],"isBlockCoverage":true},{"functionName":"compareStrings","ranges":[{"startOffset":10233,"endOffset":10500,"count":25788},{"startOffset":10281,"endOffset":10498,"count":1}],"isBlockCoverage":true},{"functionName":"compareObjects","ranges":[{"startOffset":10676,"endOffset":10744,"count":13},{"startOffset":10732,"endOffset":10742,"count":3}],"isBlockCoverage":true},{"functionName":"compareValues","ranges":[{"startOffset":10888,"endOffset":11043,"count":99088},{"startOffset":10935,"endOffset":11027,"count":3},{"startOffset":11027,"endOffset":11042,"count":99085}],"isBlockCoverage":true},{"functionName":"_failMessage","ranges":[{"startOffset":11175,"endOffset":11293,"count":11},{"startOffset":11231,"endOffset":11252,"count":5},{"startOffset":11257,"endOffset":11291,"count":6}],"isBlockCoverage":true},{"functionName":"_compare","ranges":[{"startOffset":11475,"endOffset":13987,"count":125864},{"startOffset":11646,"endOffset":11658,"count":124575},{"startOffset":11660,"endOffset":11708,"count":1290},{"startOffset":11708,"endOffset":11748,"count":124574},{"startOffset":11748,"endOffset":11814,"count":1},{"startOffset":11814,"endOffset":11867,"count":124573},{"startOffset":11867,"endOffset":11940,"count":1},{"startOffset":11992,"endOffset":12249,"count":25348},{"startOffset":12052,"endOffset":12126,"count":2},{"startOffset":12126,"endOffset":12157,"count":25346},{"startOffset":12157,"endOffset":12172,"count":5495137},{"startOffset":12179,"endOffset":12231,"count":5469791},{"startOffset":12231,"endOffset":12249,"count":25346},{"startOffset":12254,"endOffset":12567,"count":3},{"startOffset":12295,"endOffset":12384,"count":1},{"startOffset":12384,"endOffset":12567,"count":2},{"startOffset":12572,"endOffset":13003,"count":5},{"startOffset":12613,"endOffset":12702,"count":1},{"startOffset":12702,"endOffset":13003,"count":4},{"startOffset":13008,"endOffset":13449,"count":721},{"startOffset":13070,"endOffset":13164,"count":1},{"startOffset":13164,"endOffset":13449,"count":720},{"startOffset":13454,"endOffset":13718,"count":698},{"startOffset":13499,"endOffset":13592,"count":1},{"startOffset":13592,"endOffset":13718,"count":697},{"startOffset":13750,"endOffset":13940,"count":97798},{"startOffset":13827,"endOffset":13940,"count":0},{"startOffset":13944,"endOffset":13986,"count":124559}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12421,"endOffset":12548,"count":3},{"startOffset":12459,"endOffset":12540,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12739,"endOffset":12984,"count":8},{"startOffset":12782,"endOffset":12895,"count":1},{"startOffset":12895,"endOffset":12983,"count":7}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":13189,"endOffset":13436,"count":886},{"startOffset":13248,"endOffset":13351,"count":2},{"startOffset":13351,"endOffset":13435,"count":884}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":13629,"endOffset":13705,"count":52402}],"isBlockCoverage":true},{"functionName":"compare","ranges":[{"startOffset":14162,"endOffset":14264,"count":72571}],"isBlockCoverage":true},{"functionName":"assert","ranges":[{"startOffset":14456,"endOffset":14567,"count":736030},{"startOffset":14497,"endOffset":14565,"count":1},{"startOffset":14541,"endOffset":14557,"count":0}],"isBlockCoverage":true},{"functionName":"promiseRejected","ranges":[{"startOffset":14652,"endOffset":14756,"count":4},{"startOffset":14686,"endOffset":14691,"count":1},{"startOffset":14691,"endOffset":14719,"count":3},{"startOffset":14719,"endOffset":14755,"count":1}],"isBlockCoverage":true},{"functionName":"fails","ranges":[{"startOffset":14846,"endOffset":14990,"count":26},{"startOffset":14873,"endOffset":14956,"count":25},{"startOffset":14956,"endOffset":14989,"count":1}],"isBlockCoverage":true},{"functionName":"failsAsync","ranges":[{"startOffset":15093,"endOffset":15249,"count":5},{"startOffset":15127,"endOffset":15132,"count":1},{"startOffset":15132,"endOffset":15215,"count":4},{"startOffset":15215,"endOffset":15248,"count":1}],"isBlockCoverage":true},{"functionName":"runTests","ranges":[{"startOffset":15370,"endOffset":16817,"count":1},{"startOffset":15811,"endOffset":16301,"count":35},{"startOffset":15873,"endOffset":16297,"count":138},{"startOffset":15963,"endOffset":16291,"count":137},{"startOffset":16057,"endOffset":16078,"count":274},{"startOffset":16614,"endOffset":16775,"count":0}],"isBlockCoverage":true},{"functionName":"filterTest","ranges":[{"startOffset":15450,"endOffset":15525,"count":276},{"startOffset":15490,"endOffset":15525,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":15568,"endOffset":15677,"count":35}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":15591,"endOffset":15656,"count":138},{"startOffset":15649,"endOffset":15652,"count":137},{"startOffset":15653,"endOffset":15656,"count":1}],"isBlockCoverage":true},{"functionName":"fail","ranges":[{"startOffset":16930,"endOffset":17037,"count":25}],"isBlockCoverage":true},{"functionName":"skip","ranges":[{"startOffset":17185,"endOffset":17261,"count":20},{"startOffset":17216,"endOffset":17259,"count":6}],"isBlockCoverage":true}]},{"scriptId":"105","url":"file:///home/dmonad/ylabs/lib0/array.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2809,"count":1}],"isBlockCoverage":true},{"functionName":"testIsarrayPerformance","ranges":[{"startOffset":144,"endOffset":960,"count":1},{"startOffset":259,"endOffset":356,"count":100000},{"startOffset":282,"endOffset":352,"count":50000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":418,"endOffset":606,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":474,"endOffset":561,"count":100000},{"startOffset":520,"endOffset":555,"count":50000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":661,"endOffset":842,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":717,"endOffset":797,"count":100000},{"startOffset":756,"endOffset":791,"count":50000}],"isBlockCoverage":true},{"functionName":"testAppend","ranges":[{"startOffset":1023,"endOffset":1139,"count":1}],"isBlockCoverage":true},{"functionName":"testBasic","ranges":[{"startOffset":1201,"endOffset":1313,"count":1}],"isBlockCoverage":true},{"functionName":"testflatten","ranges":[{"startOffset":1377,"endOffset":1470,"count":1}],"isBlockCoverage":true},{"functionName":"testFolding","ranges":[{"startOffset":1534,"endOffset":1983,"count":1}],"isBlockCoverage":true},{"functionName":"testcase","ranges":[{"startOffset":1597,"endOffset":1937,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1744,"endOffset":1750,"count":101}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1756,"endOffset":1905,"count":101}],"isBlockCoverage":true},{"functionName":"testEvery","ranges":[{"startOffset":2045,"endOffset":2249,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2106,"endOffset":2117,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2149,"endOffset":2159,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2189,"endOffset":2201,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2232,"endOffset":2245,"count":3}],"isBlockCoverage":true},{"functionName":"testIsArray","ranges":[{"startOffset":2313,"endOffset":2527,"count":1}],"isBlockCoverage":true},{"functionName":"testUnique","ranges":[{"startOffset":2590,"endOffset":2808,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2751,"endOffset":2760,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2798,"endOffset":2804,"count":0}],"isBlockCoverage":false}]},{"scriptId":"106","url":"file:///home/dmonad/ylabs/lib0/broadcastchannel.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":666,"count":1}],"isBlockCoverage":true},{"functionName":"testBroadcastChannel","ranges":[{"startOffset":149,"endOffset":665,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":277,"endOffset":336,"count":2}],"isBlockCoverage":true}]},{"scriptId":"107","url":"file:///home/dmonad/ylabs/lib0/hash/rabin.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6821,"count":1}],"isBlockCoverage":true},{"functionName":"testPolynomialBasics","ranges":[{"startOffset":430,"endOffset":629,"count":1}],"isBlockCoverage":true},{"functionName":"testIrreducibleInput","ranges":[{"startOffset":702,"endOffset":1186,"count":1}],"isBlockCoverage":true},{"functionName":"testIrreducibleSpread","ranges":[{"startOffset":1260,"endOffset":1576,"count":1}],"isBlockCoverage":true},{"functionName":"getSpreadAverage","ranges":[{"startOffset":1662,"endOffset":2037,"count":1},{"startOffset":1762,"endOffset":1985,"count":30126},{"startOffset":1887,"endOffset":1981,"count":1000}],"isBlockCoverage":true},{"functionName":"testGenerateIrreducibles","ranges":[{"startOffset":2114,"endOffset":2990,"count":1}],"isBlockCoverage":true},{"functionName":"testIrreducibleGen","ranges":[{"startOffset":2193,"endOffset":2492,"count":5}],"isBlockCoverage":true},{"functionName":"_testFingerprintCompatiblityK","ranges":[{"startOffset":3085,"endOffset":5634,"count":5},{"startOffset":3548,"endOffset":3607,"count":1500},{"startOffset":3890,"endOffset":3911,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3408,"endOffset":3516,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3713,"endOffset":3808,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3757,"endOffset":3803,"count":1500}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4023,"endOffset":4281,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4067,"endOffset":4276,"count":1500},{"startOffset":4195,"endOffset":4232,"count":195000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4447,"endOffset":4705,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4491,"endOffset":4700,"count":1500},{"startOffset":4619,"endOffset":4656,"count":195000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5034,"endOffset":5290,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5078,"endOffset":5285,"count":1500},{"startOffset":5204,"endOffset":5241,"count":195000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5465,"endOffset":5589,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5509,"endOffset":5584,"count":1500}],"isBlockCoverage":true},{"functionName":"testFingerprintCompatiblity","ranges":[{"startOffset":5713,"endOffset":5922,"count":1}],"isBlockCoverage":true},{"functionName":"testConflicts","ranges":[{"startOffset":5987,"endOffset":6820,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6152,"endOffset":6274,"count":1},{"startOffset":6192,"endOffset":6270,"count":100}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6396,"endOffset":6575,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6421,"endOffset":6570,"count":100}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6524,"endOffset":6539,"count":87}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6625,"endOffset":6644,"count":87}],"isBlockCoverage":true}]},{"scriptId":"108","url":"file:///home/dmonad/ylabs/lib0/hash/sha256.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":5855,"count":1}],"isBlockCoverage":true},{"functionName":"testSelfReferencingHash","ranges":[{"startOffset":460,"endOffset":661,"count":1}],"isBlockCoverage":true},{"functionName":"testSha256Basics","ranges":[{"startOffset":730,"endOffset":2682,"count":1}],"isBlockCoverage":true},{"functionName":"test","ranges":[{"startOffset":904,"endOffset":1306,"count":8},{"startOffset":966,"endOffset":994,"count":1},{"startOffset":995,"endOffset":1001,"count":7}],"isBlockCoverage":true},{"functionName":"testLargeValue","ranges":[{"startOffset":2827,"endOffset":3848,"count":1},{"startOffset":3081,"endOffset":3847,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3194,"endOffset":3506,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":3565,"endOffset":3610,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":3681,"endOffset":3780,"count":0}],"isBlockCoverage":false},{"functionName":"testRepeatSha256Hashing","ranges":[{"startOffset":3923,"endOffset":4257,"count":4},{"startOffset":3970,"endOffset":4000,"count":2},{"startOffset":4001,"endOffset":4035,"count":2}],"isBlockCoverage":true},{"functionName":"testBenchmarkSha256","ranges":[{"startOffset":4329,"endOffset":5854,"count":1},{"startOffset":5725,"endOffset":5853,"count":0}],"isBlockCoverage":true},{"functionName":"bench","ranges":[{"startOffset":4419,"endOffset":5614,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4484,"endOffset":5613,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4564,"endOffset":4594,"count":20000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4634,"endOffset":4775,"count":2},{"startOffset":4676,"endOffset":4769,"count":20000},{"startOffset":4744,"endOffset":4761,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4890,"endOffset":5042,"count":2},{"startOffset":4934,"endOffset":5034,"count":20000},{"startOffset":5007,"endOffset":5024,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5105,"endOffset":5279,"count":2},{"startOffset":5153,"endOffset":5273,"count":20000},{"startOffset":5248,"endOffset":5265,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5334,"endOffset":5608,"count":2},{"startOffset":5453,"endOffset":5524,"count":20000},{"startOffset":5585,"endOffset":5602,"count":0}],"isBlockCoverage":true}]},{"scriptId":"109","url":"file:///home/dmonad/ylabs/lib0/crypto.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":14615,"count":1}],"isBlockCoverage":true},{"functionName":"testJwt","ranges":[{"startOffset":365,"endOffset":1736,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1668,"endOffset":1733,"count":1},{"startOffset":1729,"endOffset":1732,"count":0}],"isBlockCoverage":true},{"functionName":"testEncryption","ranges":[{"startOffset":1802,"endOffset":3083,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1965,"endOffset":2146,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2176,"endOffset":2384,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2429,"endOffset":2722,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2466,"endOffset":2717,"count":1},{"startOffset":2684,"endOffset":2716,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2768,"endOffset":3080,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2805,"endOffset":3075,"count":1},{"startOffset":2981,"endOffset":3074,"count":0}],"isBlockCoverage":true},{"functionName":"testReapeatEncryption","ranges":[{"startOffset":3156,"endOffset":3880,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3476,"endOffset":3537,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3580,"endOffset":3642,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3781,"endOffset":3848,"count":1}],"isBlockCoverage":true},{"functionName":"testImportExport","ranges":[{"startOffset":3948,"endOffset":6327,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4078,"endOffset":4351,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4392,"endOffset":4665,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4704,"endOffset":5290,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5329,"endOffset":5710,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5752,"endOffset":6324,"count":1}],"isBlockCoverage":true},{"functionName":"testEncryptionPerformance","ranges":[{"startOffset":6404,"endOffset":7430,"count":1},{"startOffset":6776,"endOffset":6827,"count":1000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6622,"endOffset":6683,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6976,"endOffset":7101,"count":1},{"startOffset":7032,"endOffset":7097,"count":1000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7251,"endOffset":7394,"count":1},{"startOffset":7316,"endOffset":7390,"count":1000}],"isBlockCoverage":true},{"functionName":"testConsistentKeyGeneration","ranges":[{"startOffset":7510,"endOffset":13906,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7571,"endOffset":8015,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8065,"endOffset":9247,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9295,"endOffset":13903,"count":1}],"isBlockCoverage":true},{"functionName":"testSigning","ranges":[{"startOffset":13969,"endOffset":14614,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":14055,"endOffset":14611,"count":1}],"isBlockCoverage":true}]},{"scriptId":"110","url":"file:///home/dmonad/ylabs/lib0/logging.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1216,"count":1}],"isBlockCoverage":true},{"functionName":"testLogging","ranges":[{"startOffset":64,"endOffset":829,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":712,"endOffset":781,"count":1}],"isBlockCoverage":true},{"functionName":"testModuleLogger","ranges":[{"startOffset":863,"endOffset":1215,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1064,"endOffset":1114,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1163,"endOffset":1212,"count":0}],"isBlockCoverage":false}]},{"scriptId":"111","url":"file:///home/dmonad/ylabs/lib0/string.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2402,"count":1}],"isBlockCoverage":true},{"functionName":"testUtilities","ranges":[{"startOffset":170,"endOffset":306,"count":1}],"isBlockCoverage":true},{"functionName":"testLowercaseTransformation","ranges":[{"startOffset":385,"endOffset":689,"count":1}],"isBlockCoverage":true},{"functionName":"testRepeatStringUtf8Encoding","ranges":[{"startOffset":769,"endOffset":1191,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":942,"endOffset":1002,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1048,"endOffset":1114,"count":3}],"isBlockCoverage":true},{"functionName":"testRepeatStringUtf8Decoding","ranges":[{"startOffset":1271,"endOffset":1712,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1463,"endOffset":1523,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1569,"endOffset":1635,"count":4}],"isBlockCoverage":true},{"functionName":"testBomEncodingDecoding","ranges":[{"startOffset":1787,"endOffset":2192,"count":1}],"isBlockCoverage":true},{"functionName":"testSplice","ranges":[{"startOffset":2254,"endOffset":2401,"count":1}],"isBlockCoverage":true}]},{"scriptId":"112","url":"file:///home/dmonad/ylabs/lib0/encoding.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":29920,"count":1},{"startOffset":1276,"endOffset":1328,"count":0}],"isBlockCoverage":true},{"functionName":"genAnyLookupTable.val","ranges":[{"startOffset":454,"endOffset":534,"count":649}],"isBlockCoverage":true},{"functionName":"genAnyLookupTable.val","ranges":[{"startOffset":550,"endOffset":567,"count":2490}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":583,"endOffset":595,"count":2598}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":611,"endOffset":683,"count":2464}],"isBlockCoverage":true},{"functionName":"genAnyLookupTable.val","ranges":[{"startOffset":699,"endOffset":722,"count":2434}],"isBlockCoverage":true},{"functionName":"genAnyLookupTable.val","ranges":[{"startOffset":746,"endOffset":758,"count":2539}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":774,"endOffset":787,"count":2554}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":803,"endOffset":831,"count":2659}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":847,"endOffset":932,"count":2572}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":948,"endOffset":1089,"count":2495}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1042,"endOffset":1088,"count":17392}],"isBlockCoverage":true},{"functionName":"genAnyLookupTable","ranges":[{"startOffset":1105,"endOffset":1157,"count":2517}],"isBlockCoverage":true},{"functionName":"genAny","ranges":[{"startOffset":1428,"endOffset":1593,"count":25971},{"startOffset":1508,"endOffset":1541,"count":18971},{"startOffset":1542,"endOffset":1561,"count":7000}],"isBlockCoverage":true},{"functionName":"testGolangBinaryEncodingCompatibility","ranges":[{"startOffset":1854,"endOffset":3062,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2686,"endOffset":3059,"count":20},{"startOffset":3006,"endOffset":3055,"count":58}],"isBlockCoverage":true},{"functionName":"test","ranges":[{"startOffset":3258,"endOffset":3892,"count":53734},{"startOffset":3695,"endOffset":3809,"count":15}],"isBlockCoverage":true},{"functionName":"testVarString","ranges":[{"startOffset":3945,"endOffset":4221,"count":7147}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4009,"endOffset":4059,"count":7147}],"isBlockCoverage":true},{"functionName":"testVerifyLen","ranges":[{"startOffset":4252,"endOffset":4541,"count":1}],"isBlockCoverage":true},{"functionName":"testStringEncodingPerformanceNativeVsPolyfill","ranges":[{"startOffset":4604,"endOffset":6397,"count":1},{"startOffset":4694,"endOffset":4715,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4786,"endOffset":5006,"count":1},{"startOffset":4886,"endOffset":5002,"count":20}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5077,"endOffset":5293,"count":1},{"startOffset":5177,"endOffset":5289,"count":20}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5511,"endOffset":5784,"count":1},{"startOffset":5611,"endOffset":5780,"count":100000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5860,"endOffset":6127,"count":1},{"startOffset":5960,"endOffset":6123,"count":100000}],"isBlockCoverage":true},{"functionName":"testDecodingPerformanceNativeVsPolyfill","ranges":[{"startOffset":6454,"endOffset":8369,"count":1},{"startOffset":6577,"endOffset":6598,"count":10000},{"startOffset":6734,"endOffset":6868,"count":10000},{"startOffset":6913,"endOffset":6968,"count":1000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7144,"endOffset":7297,"count":1},{"startOffset":7241,"endOffset":7293,"count":30000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7378,"endOffset":7524,"count":1},{"startOffset":7475,"endOffset":7520,"count":30000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7601,"endOffset":7759,"count":1},{"startOffset":7703,"endOffset":7755,"count":1000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7840,"endOffset":8000,"count":1},{"startOffset":7942,"endOffset":7996,"count":1000}],"isBlockCoverage":true},{"functionName":"testStringDecodingPerformance","ranges":[{"startOffset":8416,"endOffset":10517,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8710,"endOffset":9191,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8821,"endOffset":8924,"count":1},{"startOffset":8863,"endOffset":8918,"count":2000000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9058,"endOffset":9186,"count":1},{"startOffset":9121,"endOffset":9180,"count":2000000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9277,"endOffset":10300,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9481,"endOffset":9840,"count":1},{"startOffset":9540,"endOffset":9743,"count":2000000},{"startOffset":9661,"endOffset":9735,"count":100000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":10046,"endOffset":10295,"count":1},{"startOffset":10163,"endOffset":10289,"count":2000000}],"isBlockCoverage":true},{"functionName":"testAnyEncodeUnknowns","ranges":[{"startOffset":10591,"endOffset":11010,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":10770,"endOffset":10778,"count":0}],"isBlockCoverage":false},{"functionName":"testAnyEncodeDate","ranges":[{"startOffset":11080,"endOffset":11179,"count":1}],"isBlockCoverage":true},{"functionName":"testEncodeMax32bitUint","ranges":[{"startOffset":11254,"endOffset":11349,"count":1}],"isBlockCoverage":true},{"functionName":"testVarUintEncoding","ranges":[{"startOffset":11421,"endOffset":11969,"count":1}],"isBlockCoverage":true},{"functionName":"testVarIntEncoding","ranges":[{"startOffset":12040,"endOffset":12676,"count":1}],"isBlockCoverage":true},{"functionName":"testRepeatVarUintEncoding","ranges":[{"startOffset":12753,"endOffset":12894,"count":10061}],"isBlockCoverage":true},{"functionName":"testRepeatVarUintEncoding53bit","ranges":[{"startOffset":12976,"endOffset":13127,"count":9400}],"isBlockCoverage":true},{"functionName":"testRepeatVarIntEncoding","ranges":[{"startOffset":13203,"endOffset":13358,"count":8957}],"isBlockCoverage":true},{"functionName":"testRepeatVarIntEncoding53bit","ranges":[{"startOffset":13439,"endOffset":13608,"count":8456}],"isBlockCoverage":true},{"functionName":"testRepeanntAnyEncoding","ranges":[{"startOffset":13683,"endOffset":13790,"count":1}],"isBlockCoverage":true},{"functionName":"testRepeatPeekVarUintEncoding","ranges":[{"startOffset":13871,"endOffset":14011,"count":9122}],"isBlockCoverage":true},{"functionName":"testRepeatPeekVarIntEncoding","ranges":[{"startOffset":14091,"endOffset":14260,"count":7722}],"isBlockCoverage":true},{"functionName":"testAnyVsJsonEncoding","ranges":[{"startOffset":14333,"endOffset":15025,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":14386,"endOffset":14416,"count":5000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":14455,"endOffset":14696,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":14741,"endOffset":15022,"count":1}],"isBlockCoverage":true},{"functionName":"testStringEncoding","ranges":[{"startOffset":15096,"endOffset":15331,"count":1}],"isBlockCoverage":true},{"functionName":"testRepeatStringEncoding","ranges":[{"startOffset":15407,"endOffset":15455,"count":7139}],"isBlockCoverage":true},{"functionName":"testSetMethods","ranges":[{"startOffset":15522,"endOffset":16118,"count":1}],"isBlockCoverage":true},{"functionName":"strictComparison","ranges":[{"startOffset":16251,"endOffset":16268,"count":6947}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":16700,"endOffset":16751,"count":1059}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":16791,"endOffset":16826,"count":1059}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":16952,"endOffset":17008,"count":988}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":17110,"endOffset":17150,"count":1034}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":17262,"endOffset":17303,"count":980}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":17415,"endOffset":17456,"count":1015}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":17595,"endOffset":17636,"count":999}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":17757,"endOffset":17814,"count":989}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":17929,"endOffset":17980,"count":976}],"isBlockCoverage":true},{"functionName":"gen","ranges":[{"startOffset":18092,"endOffset":18164,"count":954}],"isBlockCoverage":true},{"functionName":"testRepeatRandomWrites","ranges":[{"startOffset":18371,"endOffset":19277,"count":1},{"startOffset":18591,"endOffset":18810,"count":10000},{"startOffset":19111,"endOffset":19213,"count":10000}],"isBlockCoverage":true},{"functionName":"testWriteUint8ArrayOverflow","ranges":[{"startOffset":19357,"endOffset":19861,"count":1},{"startOffset":19554,"endOffset":19574,"count":400},{"startOffset":19780,"endOffset":19820,"count":399}],"isBlockCoverage":true},{"functionName":"testSetOnOverflow","ranges":[{"startOffset":19931,"endOffset":20851,"count":1},{"startOffset":20402,"endOffset":20436,"count":98}],"isBlockCoverage":true},{"functionName":"testCloneDecoder","ranges":[{"startOffset":20920,"endOffset":21451,"count":1}],"isBlockCoverage":true},{"functionName":"testWriteBinaryEncoder","ranges":[{"startOffset":21526,"endOffset":21941,"count":1}],"isBlockCoverage":true},{"functionName":"testOverflowStringDecoding","ranges":[{"startOffset":22019,"endOffset":22387,"count":1}],"isBlockCoverage":true},{"functionName":"testRleEncoder","ranges":[{"startOffset":22454,"endOffset":22964,"count":1},{"startOffset":22574,"endOffset":22691,"count":100},{"startOffset":22629,"endOffset":22687,"count":4950},{"startOffset":22818,"endOffset":22962,"count":100},{"startOffset":22887,"endOffset":22958,"count":4950}],"isBlockCoverage":true},{"functionName":"testRleIntDiffEncoder","ranges":[{"startOffset":23038,"endOffset":23525,"count":1},{"startOffset":23146,"endOffset":23263,"count":200},{"startOffset":23201,"endOffset":23259,"count":4950},{"startOffset":23379,"endOffset":23523,"count":200},{"startOffset":23448,"endOffset":23519,"count":4950}],"isBlockCoverage":true},{"functionName":"testUintOptRleEncoder","ranges":[{"startOffset":23599,"endOffset":24072,"count":1},{"startOffset":23705,"endOffset":23822,"count":100},{"startOffset":23760,"endOffset":23818,"count":4950},{"startOffset":23926,"endOffset":24070,"count":100},{"startOffset":23995,"endOffset":24066,"count":4950}],"isBlockCoverage":true},{"functionName":"testIncUintOptRleEncoder","ranges":[{"startOffset":24149,"endOffset":24628,"count":1},{"startOffset":24258,"endOffset":24375,"count":100},{"startOffset":24313,"endOffset":24371,"count":4950},{"startOffset":24482,"endOffset":24626,"count":100},{"startOffset":24551,"endOffset":24622,"count":4950}],"isBlockCoverage":true},{"functionName":"testIntDiffRleEncoder","ranges":[{"startOffset":24702,"endOffset":25183,"count":1},{"startOffset":24812,"endOffset":24929,"count":200},{"startOffset":24867,"endOffset":24925,"count":4950},{"startOffset":25037,"endOffset":25181,"count":200},{"startOffset":25106,"endOffset":25177,"count":4950}],"isBlockCoverage":true},{"functionName":"testIntEncoders","ranges":[{"startOffset":25250,"endOffset":26531,"count":1},{"startOffset":25395,"endOffset":25602,"count":10000},{"startOffset":25421,"endOffset":25543,"count":5055},{"startOffset":25543,"endOffset":25598,"count":4945}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":25759,"endOffset":25827,"count":1}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":25884,"endOffset":25957,"count":1}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":26015,"endOffset":26089,"count":1}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":26149,"endOffset":26225,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":26254,"endOffset":26528,"count":4},{"startOffset":26455,"endOffset":26494,"count":40000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":26296,"endOffset":26317,"count":40000}],"isBlockCoverage":true},{"functionName":"testIntDiffEncoder","ranges":[{"startOffset":26602,"endOffset":26888,"count":1},{"startOffset":26707,"endOffset":26733,"count":200},{"startOffset":26846,"endOffset":26886,"count":200}],"isBlockCoverage":true},{"functionName":"testStringDecoder","ranges":[{"startOffset":26957,"endOffset":27577,"count":1},{"startOffset":27053,"endOffset":27295,"count":1000},{"startOffset":27116,"endOffset":27215,"count":10},{"startOffset":27239,"endOffset":27291,"count":10},{"startOffset":27384,"endOffset":27417,"count":1030},{"startOffset":27528,"endOffset":27575,"count":1030}],"isBlockCoverage":true},{"functionName":"testLargeNumberEncoding","ranges":[{"startOffset":27652,"endOffset":28624,"count":1}],"isBlockCoverage":true},{"functionName":"testInvalidVarIntEncoding","ranges":[{"startOffset":28702,"endOffset":28948,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":28826,"endOffset":28870,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":28900,"endOffset":28945,"count":1}],"isBlockCoverage":true},{"functionName":"testTerminatedEncodering","ranges":[{"startOffset":29025,"endOffset":29919,"count":1}],"isBlockCoverage":true}]},{"scriptId":"113","url":"file:///home/dmonad/ylabs/lib0/diff.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":5061,"count":1}],"isBlockCoverage":true},{"functionName":"runDiffTest","ranges":[{"startOffset":344,"endOffset":923,"count":13}],"isBlockCoverage":true},{"functionName":"testDiffing","ranges":[{"startOffset":986,"endOffset":2202,"count":1}],"isBlockCoverage":true},{"functionName":"testRepeatDiffing","ranges":[{"startOffset":2271,"endOffset":2495,"count":11455}],"isBlockCoverage":true},{"functionName":"testSimpleDiffWithCursor","ranges":[{"startOffset":2571,"endOffset":4638,"count":1}],"isBlockCoverage":true},{"functionName":"testArrayDiffing","ranges":[{"startOffset":4706,"endOffset":5060,"count":1}],"isBlockCoverage":true}]},{"scriptId":"114","url":"file:///home/dmonad/ylabs/lib0/testing.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4754,"count":1}],"isBlockCoverage":true},{"functionName":"nottestingNotTested","ranges":[{"startOffset":271,"endOffset":376,"count":0}],"isBlockCoverage":false},{"functionName":"testAssertTyping","ranges":[{"startOffset":410,"endOffset":677,"count":1},{"startOffset":466,"endOffset":472,"count":0}],"isBlockCoverage":true},{"functionName":"testComparing","ranges":[{"startOffset":743,"endOffset":3764,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1297,"endOffset":1366,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1378,"endOffset":1447,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1459,"endOffset":1524,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1536,"endOffset":1625,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1637,"endOffset":1729,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1741,"endOffset":1833,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1845,"endOffset":1977,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1989,"endOffset":2135,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2147,"endOffset":2226,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2290,"endOffset":2374,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2386,"endOffset":2469,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2541,"endOffset":2614,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2626,"endOffset":2721,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2733,"endOffset":2825,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2837,"endOffset":2936,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2974,"endOffset":3145,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3157,"endOffset":3328,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3340,"endOffset":3494,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3532,"endOffset":3642,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3654,"endOffset":3761,"count":1}],"isBlockCoverage":true},{"functionName":"testFailing","ranges":[{"startOffset":3793,"endOffset":4159,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3817,"endOffset":3864,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3892,"endOffset":3948,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3960,"endOffset":3993,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3980,"endOffset":3988,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4016,"endOffset":4073,"count":1},{"startOffset":4069,"endOffset":4072,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4053,"endOffset":4068,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4101,"endOffset":4153,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4129,"endOffset":4152,"count":1}],"isBlockCoverage":true},{"functionName":"testSkipping","ranges":[{"startOffset":4189,"endOffset":4297,"count":1}],"isBlockCoverage":true},{"functionName":"testAsync","ranges":[{"startOffset":4324,"endOffset":4564,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4373,"endOffset":4413,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4394,"endOffset":4412,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4456,"endOffset":4477,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4505,"endOffset":4561,"count":1}],"isBlockCoverage":true},{"functionName":"testRepeatRepetition","ranges":[{"startOffset":4602,"endOffset":4753,"count":27034},{"startOffset":4674,"endOffset":4695,"count":2703400}],"isBlockCoverage":true}]},{"scriptId":"115","url":"file:///home/dmonad/ylabs/lib0/prng.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7180,"count":1}],"isBlockCoverage":true},{"functionName":"runGenTest","ranges":[{"startOffset":538,"endOffset":5871,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":594,"endOffset":877,"count":3},{"startOffset":660,"endOffset":787,"count":15000},{"startOffset":713,"endOffset":763,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":926,"endOffset":1348,"count":3},{"startOffset":1027,"endOffset":1127,"count":15000},{"startOffset":1067,"endOffset":1091,"count":7542},{"startOffset":1091,"endOffset":1121,"count":7458}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1398,"endOffset":1771,"count":3},{"startOffset":1473,"endOffset":1520,"count":15000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1826,"endOffset":2550,"count":3},{"startOffset":1938,"endOffset":2135,"count":15000},{"startOffset":2030,"endOffset":2064,"count":27},{"startOffset":2094,"endOffset":2129,"count":25}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2615,"endOffset":2967,"count":3},{"startOffset":2702,"endOffset":2814,"count":15000},{"startOffset":2778,"endOffset":2808,"count":27}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3027,"endOffset":3759,"count":3},{"startOffset":3139,"endOffset":3355,"count":15000},{"startOffset":3250,"endOffset":3284,"count":23},{"startOffset":3314,"endOffset":3349,"count":25}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3820,"endOffset":4471,"count":3},{"startOffset":3936,"endOffset":4158,"count":15000},{"startOffset":4026,"endOffset":4060,"count":20},{"startOffset":4117,"endOffset":4152,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4526,"endOffset":4878,"count":3},{"startOffset":4613,"endOffset":4725,"count":15000},{"startOffset":4689,"endOffset":4719,"count":35}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4923,"endOffset":5307,"count":3},{"startOffset":5010,"endOffset":5123,"count":15000},{"startOffset":5087,"endOffset":5117,"count":20}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5361,"endOffset":5868,"count":3},{"startOffset":5565,"endOffset":5600,"count":288},{"startOffset":5643,"endOffset":5711,"count":15000}],"isBlockCoverage":true},{"functionName":"testGeneratorXoroshiro128plus","ranges":[{"startOffset":5952,"endOffset":6003,"count":1}],"isBlockCoverage":true},{"functionName":"testGeneratorXorshift32","ranges":[{"startOffset":6078,"endOffset":6151,"count":1}],"isBlockCoverage":true},{"functionName":"testGeneratorMt19937","ranges":[{"startOffset":6223,"endOffset":6293,"count":1}],"isBlockCoverage":true},{"functionName":"printDistribution","ranges":[{"startOffset":6402,"endOffset":6813,"count":0}],"isBlockCoverage":false},{"functionName":"testNumberDistributions","ranges":[{"startOffset":6909,"endOffset":7179,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6968,"endOffset":7026,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":7052,"endOffset":7104,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":7127,"endOffset":7176,"count":0}],"isBlockCoverage":false}]},{"scriptId":"116","url":"file:///home/dmonad/ylabs/lib0/logging.node.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3901,"count":1},{"startOffset":1849,"endOffset":1873,"count":0}],"isBlockCoverage":true},{"functionName":"computeNodeLoggingArgs","ranges":[{"startOffset":774,"endOffset":1757,"count":0}],"isBlockCoverage":false},{"functionName":"print","ranges":[{"startOffset":2024,"endOffset":2083,"count":548}],"isBlockCoverage":true},{"functionName":"warn","ranges":[{"startOffset":2187,"endOffset":2247,"count":0}],"isBlockCoverage":false},{"functionName":"printError","ranges":[{"startOffset":2348,"endOffset":2381,"count":0}],"isBlockCoverage":false},{"functionName":"printImg","ranges":[{"startOffset":2553,"endOffset":2675,"count":1}],"isBlockCoverage":true},{"functionName":"printImgBase64","ranges":[{"startOffset":2811,"endOffset":2884,"count":1}],"isBlockCoverage":true},{"functionName":"group","ranges":[{"startOffset":2990,"endOffset":3051,"count":45}],"isBlockCoverage":true},{"functionName":"groupCollapsed","ranges":[{"startOffset":3166,"endOffset":3236,"count":137}],"isBlockCoverage":true},{"functionName":"groupEnd","ranges":[{"startOffset":3285,"endOffset":3315,"count":182}],"isBlockCoverage":true},{"functionName":"printDom","ranges":[{"startOffset":3412,"endOffset":3431,"count":0}],"isBlockCoverage":false},{"functionName":"printCanvas","ranges":[{"startOffset":3554,"endOffset":3612,"count":0}],"isBlockCoverage":false},{"functionName":"createVConsole","ranges":[{"startOffset":3698,"endOffset":3710,"count":0}],"isBlockCoverage":false},{"functionName":"createModuleLogger","ranges":[{"startOffset":3840,"endOffset":3900,"count":1}],"isBlockCoverage":true}]},{"scriptId":"117","url":"file:///home/dmonad/ylabs/lib0/statistics.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":653,"count":1}],"isBlockCoverage":true},{"functionName":"testMedian","ranges":[{"startOffset":175,"endOffset":652,"count":1}],"isBlockCoverage":true}]},{"scriptId":"118","url":"file:///home/dmonad/ylabs/lib0/indexeddb.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3320,"count":1}],"isBlockCoverage":true},{"functionName":"initTestDB","ranges":[{"startOffset":193,"endOffset":256,"count":0}],"isBlockCoverage":false},{"functionName":"createTransaction","ranges":[{"startOffset":370,"endOffset":413,"count":0}],"isBlockCoverage":false},{"functionName":"getStore","ranges":[{"startOffset":518,"endOffset":546,"count":0}],"isBlockCoverage":false},{"functionName":"testRetrieveElements","ranges":[{"startOffset":605,"endOffset":2915,"count":1},{"startOffset":719,"endOffset":2914,"count":0}],"isBlockCoverage":true},{"functionName":"iterateTests","ranges":[{"startOffset":1558,"endOffset":2085,"count":0}],"isBlockCoverage":false},{"functionName":"testBlocked","ranges":[{"startOffset":2965,"endOffset":3319,"count":1},{"startOffset":3069,"endOffset":3318,"count":0}],"isBlockCoverage":true}]},{"scriptId":"119","url":"file:///home/dmonad/ylabs/lib0/binary.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":614,"count":1}],"isBlockCoverage":true},{"functionName":"testBitx","ranges":[{"startOffset":131,"endOffset":274,"count":1},{"startOffset":171,"endOffset":272,"count":32}],"isBlockCoverage":true},{"functionName":"testBitsx","ranges":[{"startOffset":335,"endOffset":613,"count":1},{"startOffset":405,"endOffset":570,"count":31}],"isBlockCoverage":true}]},{"scriptId":"120","url":"file:///home/dmonad/ylabs/lib0/random.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2783,"count":1}],"isBlockCoverage":true},{"functionName":"testRandom","ranges":[{"startOffset":243,"endOffset":310,"count":1}],"isBlockCoverage":true},{"functionName":"testUint32","ranges":[{"startOffset":372,"endOffset":1317,"count":1},{"startOffset":551,"endOffset":811,"count":10000},{"startOffset":718,"endOffset":748,"count":9},{"startOffset":776,"endOffset":807,"count":10},{"startOffset":811,"endOffset":1316,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":669,"endOffset":683,"count":310026}],"isBlockCoverage":true},{"functionName":"testUint53","ranges":[{"startOffset":1379,"endOffset":2135,"count":1},{"startOffset":1561,"endOffset":1821,"count":10000},{"startOffset":1728,"endOffset":1758,"count":7},{"startOffset":1786,"endOffset":1817,"count":16},{"startOffset":1821,"endOffset":2134,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1679,"endOffset":1693,"count":520228}],"isBlockCoverage":true},{"functionName":"testUuidv4","ranges":[{"startOffset":2197,"endOffset":2257,"count":1}],"isBlockCoverage":true},{"functionName":"testUuidv4Overlaps","ranges":[{"startOffset":2327,"endOffset":2782,"count":1},{"startOffset":2392,"endOffset":2401,"count":0},{"startOffset":2475,"endOffset":2742,"count":10000},{"startOffset":2535,"endOffset":2578,"count":0},{"startOffset":2660,"endOffset":2738,"count":20}],"isBlockCoverage":true}]},{"scriptId":"121","url":"file:///home/dmonad/ylabs/lib0/promise.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2324,"count":1}],"isBlockCoverage":true},{"functionName":"measureP","ranges":[{"startOffset":243,"endOffset":511,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":313,"endOffset":508,"count":3}],"isBlockCoverage":true},{"functionName":"failsP","ranges":[{"startOffset":600,"endOffset":708,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":620,"endOffset":707,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":648,"endOffset":697,"count":0}],"isBlockCoverage":false},{"functionName":"testRepeatPromise","ranges":[{"startOffset":778,"endOffset":1517,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":824,"endOffset":832,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1110,"endOffset":1118,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1148,"endOffset":1156,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1303,"endOffset":1314,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1401,"endOffset":1445,"count":10}],"isBlockCoverage":true},{"functionName":"testispromise","ranges":[{"startOffset":1583,"endOffset":2017,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1633,"endOffset":1641,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1689,"endOffset":1697,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1779,"endOffset":1787,"count":1}],"isBlockCoverage":true},{"functionName":"then","ranges":[{"startOffset":1875,"endOffset":1883,"count":0}],"isBlockCoverage":false},{"functionName":"catch","ranges":[{"startOffset":1892,"endOffset":1900,"count":0}],"isBlockCoverage":false},{"functionName":"finally","ranges":[{"startOffset":1911,"endOffset":1919,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1934,"endOffset":2014,"count":1}],"isBlockCoverage":true},{"functionName":"then","ranges":[{"startOffset":1981,"endOffset":1989,"count":0}],"isBlockCoverage":false},{"functionName":"catch","ranges":[{"startOffset":1998,"endOffset":2006,"count":0}],"isBlockCoverage":false},{"functionName":"testTypings","ranges":[{"startOffset":2081,"endOffset":2323,"count":1}],"isBlockCoverage":true}]},{"scriptId":"122","url":"file:///home/dmonad/ylabs/lib0/queue.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":913,"count":1}],"isBlockCoverage":true},{"functionName":"testEnqueueDequeue","ranges":[{"startOffset":140,"endOffset":912,"count":1},{"startOffset":351,"endOffset":434,"count":30},{"startOffset":465,"endOffset":548,"count":30},{"startOffset":646,"endOffset":729,"count":30},{"startOffset":760,"endOffset":843,"count":30}],"isBlockCoverage":true}]},{"scriptId":"123","url":"file:///home/dmonad/ylabs/lib0/eventloop.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1819,"count":1}],"isBlockCoverage":true},{"functionName":"testEventloopOrder","ranges":[{"startOffset":188,"endOffset":553,"count":1},{"startOffset":244,"endOffset":552,"count":10}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":285,"endOffset":329,"count":10}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":355,"endOffset":393,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":466,"endOffset":503,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":527,"endOffset":545,"count":1}],"isBlockCoverage":true},{"functionName":"testTimeout","ranges":[{"startOffset":617,"endOffset":840,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":689,"endOffset":715,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":760,"endOffset":811,"count":1}],"isBlockCoverage":true},{"functionName":"testInterval","ranges":[{"startOffset":905,"endOffset":1166,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":978,"endOffset":1004,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1062,"endOffset":1081,"count":101}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1108,"endOffset":1119,"count":1}],"isBlockCoverage":true},{"functionName":"testAnimationFrame","ranges":[{"startOffset":1237,"endOffset":1364,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1295,"endOffset":1313,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1340,"endOffset":1347,"count":1}],"isBlockCoverage":true},{"functionName":"testIdleCallback","ranges":[{"startOffset":1433,"endOffset":1526,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1471,"endOffset":1523,"count":1}],"isBlockCoverage":true},{"functionName":"testDebouncer","ranges":[{"startOffset":1592,"endOffset":1818,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1683,"endOffset":1706,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1719,"endOffset":1742,"count":1}],"isBlockCoverage":true}]},{"scriptId":"124","url":"file:///home/dmonad/ylabs/lib0/map.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1337,"count":1}],"isBlockCoverage":true},{"functionName":"testMap","ranges":[{"startOffset":159,"endOffset":853,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":288,"endOffset":319,"count":2}],"isBlockCoverage":true},{"functionName":"createT","ranges":[{"startOffset":389,"endOffset":411,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":603,"endOffset":631,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":656,"endOffset":684,"count":2},{"startOffset":674,"endOffset":684,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":710,"endOffset":721,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":747,"endOffset":775,"count":2},{"startOffset":765,"endOffset":775,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":800,"endOffset":849,"count":3},{"startOffset":815,"endOffset":825,"count":2},{"startOffset":826,"endOffset":849,"count":1}],"isBlockCoverage":true},{"functionName":"testTypeDefinitions","ranges":[{"startOffset":925,"endOffset":1336,"count":1}],"isBlockCoverage":true},{"functionName":"A","ranges":[{"startOffset":1046,"endOffset":1085,"count":1}],"isBlockCoverage":true},{"functionName":"B","ranges":[{"startOffset":1116,"endOffset":1169,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1303,"endOffset":1316,"count":1}],"isBlockCoverage":true}]},{"scriptId":"125","url":"file:///home/dmonad/ylabs/lib0/time.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1292,"count":1}],"isBlockCoverage":true},{"functionName":"testTime","ranges":[{"startOffset":161,"endOffset":311,"count":1}],"isBlockCoverage":true},{"functionName":"testHumanDuration","ranges":[{"startOffset":380,"endOffset":1291,"count":1}],"isBlockCoverage":true}]},{"scriptId":"126","url":"file:///home/dmonad/ylabs/lib0/pair.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":636,"count":1}],"isBlockCoverage":true},{"functionName":"testPair","ranges":[{"startOffset":161,"endOffset":635,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":355,"endOffset":423,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":521,"endOffset":533,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":592,"endOffset":614,"count":3}],"isBlockCoverage":true}]},{"scriptId":"127","url":"file:///home/dmonad/ylabs/lib0/object.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1730,"count":1}],"isBlockCoverage":true},{"functionName":"testObject","ranges":[{"startOffset":168,"endOffset":1729,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":890,"endOffset":926,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":976,"endOffset":1012,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1082,"endOffset":1112,"count":2},{"startOffset":1100,"endOffset":1112,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1155,"endOffset":1173,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1215,"endOffset":1225,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1268,"endOffset":1285,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1387,"endOffset":1417,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1513,"endOffset":1525,"count":2}],"isBlockCoverage":true}]},{"scriptId":"128","url":"file:///home/dmonad/ylabs/lib0/observable.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1230,"count":1}],"isBlockCoverage":true},{"functionName":"testTypedObservable","ranges":[{"startOffset":152,"endOffset":1229,"count":1}],"isBlockCoverage":true},{"functionName":"listener","ranges":[{"startOffset":422,"endOffset":521,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":560,"endOffset":604,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":944,"endOffset":1002,"count":1}],"isBlockCoverage":true}]},{"scriptId":"129","url":"file:///home/dmonad/ylabs/lib0/math.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1043,"count":1}],"isBlockCoverage":true},{"functionName":"testMath","ranges":[{"startOffset":163,"endOffset":1042,"count":1}],"isBlockCoverage":true}]},{"scriptId":"130","url":"file:///home/dmonad/ylabs/lib0/number.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1973,"count":1}],"isBlockCoverage":true},{"functionName":"testNumber","ranges":[{"startOffset":206,"endOffset":663,"count":1}],"isBlockCoverage":true},{"functionName":"testShiftVsDivision","ranges":[{"startOffset":809,"endOffset":1972,"count":1},{"startOffset":912,"endOffset":951,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":983,"endOffset":1211,"count":1},{"startOffset":1036,"endOffset":1207,"count":10000},{"startOffset":1083,"endOffset":1201,"count":49385}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1239,"endOffset":1363,"count":1},{"startOffset":1306,"endOffset":1340,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1394,"endOffset":1493,"count":1},{"startOffset":1447,"endOffset":1489,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1666,"endOffset":1787,"count":1},{"startOffset":1721,"endOffset":1781,"count":10000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1817,"endOffset":1926,"count":1},{"startOffset":1872,"endOffset":1920,"count":10000}],"isBlockCoverage":true}]},{"scriptId":"131","url":"file:///home/dmonad/ylabs/lib0/buffer.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1418,"count":1}],"isBlockCoverage":true},{"functionName":"testEncodingHelper","ranges":[{"startOffset":264,"endOffset":741,"count":15628},{"startOffset":668,"endOffset":710,"count":366119}],"isBlockCoverage":true},{"functionName":"testRepeatBase64urlEncoding","ranges":[{"startOffset":820,"endOffset":910,"count":5978}],"isBlockCoverage":true},{"functionName":"testRepeatBase64Encoding","ranges":[{"startOffset":986,"endOffset":1056,"count":4476}],"isBlockCoverage":true},{"functionName":"testRepeatHexEncoding","ranges":[{"startOffset":1129,"endOffset":1205,"count":5174}],"isBlockCoverage":true},{"functionName":"testAnyEncoding","ranges":[{"startOffset":1273,"endOffset":1417,"count":1}],"isBlockCoverage":true}]},{"scriptId":"132","url":"file:///home/dmonad/ylabs/lib0/set.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":380,"count":1}],"isBlockCoverage":true},{"functionName":"testFirst","ranges":[{"startOffset":127,"endOffset":379,"count":1}],"isBlockCoverage":true}]},{"scriptId":"133","url":"file:///home/dmonad/ylabs/lib0/sort.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4899,"count":1}],"isBlockCoverage":true},{"functionName":"runSortTest","ranges":[{"startOffset":276,"endOffset":947,"count":36},{"startOffset":525,"endOffset":725,"count":31}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":446,"endOffset":483,"count":36}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":562,"endOffset":627,"count":31}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":755,"endOffset":808,"count":36}],"isBlockCoverage":true},{"functionName":"createSortTest","ranges":[{"startOffset":1185,"endOffset":2222,"count":4},{"startOffset":2025,"endOffset":2220,"count":0}],"isBlockCoverage":true},{"functionName":"testSortUint8","ranges":[{"startOffset":2287,"endOffset":2707,"count":1}],"isBlockCoverage":true},{"functionName":"getVal","ranges":[{"startOffset":2393,"endOffset":2399,"count":446720}],"isBlockCoverage":true},{"functionName":"compare","ranges":[{"startOffset":2498,"endOffset":2513,"count":7575354}],"isBlockCoverage":true},{"functionName":"createArray","ranges":[{"startOffset":2602,"endOffset":2654,"count":9}],"isBlockCoverage":true},{"functionName":"testSortUint32","ranges":[{"startOffset":2773,"endOffset":3190,"count":1}],"isBlockCoverage":true},{"functionName":"getVal","ranges":[{"startOffset":2879,"endOffset":2885,"count":223360}],"isBlockCoverage":true},{"functionName":"compare","ranges":[{"startOffset":2984,"endOffset":2999,"count":29460979}],"isBlockCoverage":true},{"functionName":"createArray","ranges":[{"startOffset":3088,"endOffset":3137,"count":9}],"isBlockCoverage":true},{"functionName":"testSortUint16","ranges":[{"startOffset":3256,"endOffset":3673,"count":1}],"isBlockCoverage":true},{"functionName":"getVal","ranges":[{"startOffset":3362,"endOffset":3368,"count":223360}],"isBlockCoverage":true},{"functionName":"compare","ranges":[{"startOffset":3467,"endOffset":3482,"count":29803208}],"isBlockCoverage":true},{"functionName":"createArray","ranges":[{"startOffset":3571,"endOffset":3620,"count":9}],"isBlockCoverage":true},{"functionName":"testSortObjectUint32","ranges":[{"startOffset":3745,"endOffset":4220,"count":1}],"isBlockCoverage":true},{"functionName":"getVal","ranges":[{"startOffset":3837,"endOffset":3853,"count":223360}],"isBlockCoverage":true},{"functionName":"compare","ranges":[{"startOffset":3968,"endOffset":3995,"count":29560618}],"isBlockCoverage":true},{"functionName":"createArray","ranges":[{"startOffset":4092,"endOffset":4167,"count":9}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4146,"endOffset":4166,"count":111680}],"isBlockCoverage":true},{"functionName":"testListVsArrayPerformance","ranges":[{"startOffset":4298,"endOffset":4898,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4460,"endOffset":4616,"count":1},{"startOffset":4577,"endOffset":4612,"count":100000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4651,"endOffset":4895,"count":1},{"startOffset":4798,"endOffset":4891,"count":99999}],"isBlockCoverage":true}]},{"scriptId":"134","url":"file:///home/dmonad/ylabs/lib0/url.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":954,"count":1}],"isBlockCoverage":true},{"functionName":"paramTest","ranges":[{"startOffset":131,"endOffset":261,"count":3}],"isBlockCoverage":true},{"functionName":"testUrlParamQuery","ranges":[{"startOffset":330,"endOffset":953,"count":1}],"isBlockCoverage":true}]},{"scriptId":"135","url":"file:///home/dmonad/ylabs/lib0/metric.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1627,"count":1}],"isBlockCoverage":true},{"functionName":"testMetricPrefix","ranges":[{"startOffset":139,"endOffset":1626,"count":1}],"isBlockCoverage":true}]},{"scriptId":"136","url":"file:///home/dmonad/ylabs/lib0/function.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3493,"count":1}],"isBlockCoverage":true},{"functionName":"testBasics","ranges":[{"startOffset":131,"endOffset":963,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":166,"endOffset":179,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":348,"endOffset":960,"count":4},{"startOffset":381,"endOffset":476,"count":1},{"startOffset":502,"endOffset":593,"count":1},{"startOffset":619,"endOffset":710,"count":1},{"startOffset":738,"endOffset":829,"count":1},{"startOffset":865,"endOffset":956,"count":1}],"isBlockCoverage":true},{"functionName":"testCallAll","ranges":[{"startOffset":1027,"endOffset":1346,"count":1},{"startOffset":1300,"endOffset":1345,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1108,"endOffset":1139,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1147,"endOffset":1180,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1201,"endOffset":1232,"count":1}],"isBlockCoverage":true},{"functionName":"testDeepEquality","ranges":[{"startOffset":1415,"endOffset":3492,"count":1}],"isBlockCoverage":true}]},{"scriptId":"137","url":"file:///home/dmonad/ylabs/lib0/storage.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":351,"count":1}],"isBlockCoverage":true},{"functionName":"testStorageModule","ranges":[{"startOffset":142,"endOffset":350,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":252,"endOffset":288,"count":0}],"isBlockCoverage":false}]},{"scriptId":"138","url":"file:///home/dmonad/ylabs/lib0/list.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1995,"count":1}],"isBlockCoverage":true},{"functionName":"QueueItem","ranges":[{"startOffset":146,"endOffset":194,"count":64}],"isBlockCoverage":true},{"functionName":"testEnqueueDequeue","ranges":[{"startOffset":267,"endOffset":1054,"count":1},{"startOffset":459,"endOffset":533,"count":30},{"startOffset":564,"endOffset":674,"count":30},{"startOffset":771,"endOffset":845,"count":30},{"startOffset":876,"endOffset":986,"count":30}],"isBlockCoverage":true},{"functionName":"testSelectivePop","ranges":[{"startOffset":1123,"endOffset":1994,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1448,"endOffset":1456,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1502,"endOffset":1510,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1564,"endOffset":1575,"count":3}],"isBlockCoverage":true}]},{"scriptId":"139","url":"file:///home/dmonad/ylabs/lib0/cache.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2780,"count":1}],"isBlockCoverage":true},{"functionName":"testCache","ranges":[{"startOffset":170,"endOffset":2779,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":419,"endOffset":449,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":492,"endOffset":522,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1807,"endOffset":1833,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2367,"endOffset":2398,"count":1}],"isBlockCoverage":true}]},{"scriptId":"140","url":"file:///home/dmonad/ylabs/lib0/symbol.test.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":315,"count":1}],"isBlockCoverage":true},{"functionName":"testBasicSymbolFeatures","ranges":[{"startOffset":147,"endOffset":314,"count":1}],"isBlockCoverage":true}]},{"scriptId":"141","url":"file:///home/dmonad/ylabs/lib0/environment.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3865,"count":1},{"startOffset":530,"endOffset":533,"count":0},{"startOffset":635,"endOffset":669,"count":0},{"startOffset":670,"endOffset":680,"count":0},{"startOffset":760,"endOffset":792,"count":0},{"startOffset":3698,"endOffset":3843,"count":0}],"isBlockCoverage":true},{"functionName":"computeParams","ranges":[{"startOffset":914,"endOffset":2167,"count":6},{"startOffset":950,"endOffset":2149,"count":1},{"startOffset":1107,"endOffset":1505,"count":5},{"startOffset":1168,"endOffset":1304,"count":2},{"startOffset":1208,"endOffset":1263,"count":0},{"startOffset":1304,"endOffset":1497,"count":3},{"startOffset":1350,"endOffset":1440,"count":1},{"startOffset":1440,"endOffset":1487,"count":2},{"startOffset":1694,"endOffset":2145,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1861,"endOffset":2097,"count":0}],"isBlockCoverage":false},{"functionName":"hasParam","ranges":[{"startOffset":2288,"endOffset":2323,"count":5}],"isBlockCoverage":true},{"functionName":"getParam","ranges":[{"startOffset":2454,"endOffset":2517,"count":1},{"startOffset":2504,"endOffset":2517,"count":0}],"isBlockCoverage":true},{"functionName":"getVariable","ranges":[{"startOffset":2626,"endOffset":2798,"count":2},{"startOffset":2736,"endOffset":2798,"count":0}],"isBlockCoverage":true},{"functionName":"getConf","ranges":[{"startOffset":2903,"endOffset":2968,"count":0}],"isBlockCoverage":false},{"functionName":"ensureConf","ranges":[{"startOffset":3071,"endOffset":3225,"count":0}],"isBlockCoverage":false},{"functionName":"hasConf","ranges":[{"startOffset":3326,"endOffset":3389,"count":2},{"startOffset":3360,"endOffset":3389,"count":1}],"isBlockCoverage":true}]},{"scriptId":"142","url":"file:///home/dmonad/ylabs/lib0/diff.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4774,"count":1}],"isBlockCoverage":true},{"functionName":"simpleDiffString","ranges":[{"startOffset":1221,"endOffset":2026,"count":11469},{"startOffset":1386,"endOffset":1404,"count":11364},{"startOffset":1405,"endOffset":1427,"count":10816},{"startOffset":1429,"endOffset":1445,"count":463},{"startOffset":1560,"endOffset":1599,"count":446},{"startOffset":1601,"endOffset":1607,"count":3},{"startOffset":1641,"endOffset":1667,"count":11296},{"startOffset":1668,"endOffset":1722,"count":10731},{"startOffset":1724,"endOffset":1741,"count":415},{"startOffset":1856,"endOffset":1902,"count":402},{"startOffset":1904,"endOffset":1911,"count":1}],"isBlockCoverage":true},{"functionName":"simpleDiffArray","ranges":[{"startOffset":2688,"endOffset":3199,"count":16},{"startOffset":2879,"endOffset":2897,"count":21},{"startOffset":2898,"endOffset":2926,"count":21},{"startOffset":2928,"endOffset":2944,"count":8},{"startOffset":2978,"endOffset":3004,"count":18},{"startOffset":3005,"endOffset":3065,"count":17},{"startOffset":3067,"endOffset":3084,"count":6}],"isBlockCoverage":true},{"functionName":"simpleDiffStringWithCursor","ranges":[{"startOffset":3443,"endOffset":4773,"count":19},{"startOffset":3745,"endOffset":3767,"count":47},{"startOffset":3768,"endOffset":3794,"count":46},{"startOffset":3795,"endOffset":3815,"count":35},{"startOffset":3820,"endOffset":3836,"count":30},{"startOffset":3951,"endOffset":3990,"count":11},{"startOffset":3992,"endOffset":3998,"count":3},{"startOffset":4102,"endOffset":4132,"count":52},{"startOffset":4133,"endOffset":4191,"count":47},{"startOffset":4196,"endOffset":4213,"count":36},{"startOffset":4328,"endOffset":4374,"count":10},{"startOffset":4376,"endOffset":4383,"count":1},{"startOffset":4517,"endOffset":4547,"count":23},{"startOffset":4548,"endOffset":4574,"count":17},{"startOffset":4579,"endOffset":4595,"count":7},{"startOffset":4611,"endOffset":4650,"count":10},{"startOffset":4652,"endOffset":4658,"count":2}],"isBlockCoverage":true}]},{"scriptId":"143","url":"file:///home/dmonad/ylabs/lib0/object.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2031,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":154,"endOffset":179,"count":1}],"isBlockCoverage":true},{"functionName":"forEach","ranges":[{"startOffset":433,"endOffset":500,"count":721},{"startOffset":472,"endOffset":498,"count":888},{"startOffset":498,"endOffset":499,"count":718}],"isBlockCoverage":true},{"functionName":"map","ranges":[{"startOffset":677,"endOffset":796,"count":40},{"startOffset":737,"endOffset":777,"count":178}],"isBlockCoverage":true},{"functionName":"length","ranges":[{"startOffset":883,"endOffset":906,"count":1506}],"isBlockCoverage":true},{"functionName":"some","ranges":[{"startOffset":1035,"endOffset":1148,"count":4},{"startOffset":1074,"endOffset":1131,"count":7},{"startOffset":1102,"endOffset":1127,"count":2},{"startOffset":1131,"endOffset":1147,"count":2}],"isBlockCoverage":true},{"functionName":"isEmpty","ranges":[{"startOffset":1214,"endOffset":1315,"count":2},{"startOffset":1277,"endOffset":1314,"count":1}],"isBlockCoverage":true},{"functionName":"every","ranges":[{"startOffset":1445,"endOffset":1559,"count":21},{"startOffset":1484,"endOffset":1543,"count":23},{"startOffset":1513,"endOffset":1539,"count":5},{"startOffset":1543,"endOffset":1558,"count":16}],"isBlockCoverage":true},{"functionName":"hasProperty","ranges":[{"startOffset":1714,"endOffset":1774,"count":900}],"isBlockCoverage":true},{"functionName":"equalFlat","ranges":[{"startOffset":1896,"endOffset":2030,"count":20},{"startOffset":1942,"endOffset":2029,"count":19}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1954,"endOffset":2028,"count":18},{"startOffset":1987,"endOffset":2009,"count":3},{"startOffset":2011,"endOffset":2028,"count":16}],"isBlockCoverage":true}]},{"scriptId":"144","url":"file:///home/dmonad/ylabs/lib0/string.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3832,"count":1},{"startOffset":1486,"endOffset":1492,"count":0},{"startOffset":1757,"endOffset":1778,"count":0},{"startOffset":2460,"endOffset":2466,"count":0},{"startOffset":2629,"endOffset":3049,"count":0},{"startOffset":3363,"endOffset":3384,"count":0}],"isBlockCoverage":true},{"functionName":"toLowerCase","ranges":[{"startOffset":433,"endOffset":453,"count":312}],"isBlockCoverage":true},{"functionName":"trimLeft","ranges":[{"startOffset":559,"endOffset":592,"count":141}],"isBlockCoverage":true},{"functionName":"fromCamelCase","ranges":[{"startOffset":740,"endOffset":843,"count":141}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":797,"endOffset":841,"count":312}],"isBlockCoverage":true},{"functionName":"utf8ByteLength","ranges":[{"startOffset":956,"endOffset":1003,"count":53734}],"isBlockCoverage":true},{"functionName":"_encodeUtf8Polyfill","ranges":[{"startOffset":1095,"endOffset":1349,"count":4},{"startOffset":1263,"endOffset":1334,"count":1501971}],"isBlockCoverage":true},{"functionName":"_encodeUtf8Native","ranges":[{"startOffset":1583,"endOffset":1617,"count":1065}],"isBlockCoverage":true},{"functionName":"_decodeUtf8Polyfill","ranges":[{"startOffset":1870,"endOffset":2373,"count":5},{"startOffset":1980,"endOffset":2320,"count":94},{"startOffset":2023,"endOffset":2037,"count":5},{"startOffset":2038,"endOffset":2045,"count":89}],"isBlockCoverage":true},{"functionName":"_decodeUtf8Native","ranges":[{"startOffset":3160,"endOffset":3223,"count":14}],"isBlockCoverage":true},{"functionName":"splice","ranges":[{"startOffset":3606,"endOffset":3699,"count":11476}],"isBlockCoverage":true},{"functionName":"repeat","ranges":[{"startOffset":3778,"endOffset":3831,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3809,"endOffset":3821,"count":4}],"isBlockCoverage":true}]},{"scriptId":"145","url":"file:///home/dmonad/ylabs/lib0/math.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1249,"count":1}],"isBlockCoverage":true},{"functionName":"add","ranges":[{"startOffset":450,"endOffset":465,"count":2819658}],"isBlockCoverage":true},{"functionName":"min","ranges":[{"startOffset":600,"endOffset":623,"count":750189},{"startOffset":616,"endOffset":619,"count":1038},{"startOffset":620,"endOffset":623,"count":749151}],"isBlockCoverage":true},{"functionName":"max","ranges":[{"startOffset":757,"endOffset":780,"count":31079473},{"startOffset":773,"endOffset":776,"count":10384632},{"startOffset":777,"endOffset":780,"count":20694841}],"isBlockCoverage":true},{"functionName":"exp10","ranges":[{"startOffset":1005,"endOffset":1029,"count":424}],"isBlockCoverage":true},{"functionName":"isNegativeZero","ranges":[{"startOffset":1216,"endOffset":1248,"count":78611},{"startOffset":1229,"endOffset":1236,"count":78176},{"startOffset":1237,"endOffset":1248,"count":435}],"isBlockCoverage":true}]},{"scriptId":"146","url":"file:///home/dmonad/ylabs/lib0/random.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":923,"count":1}],"isBlockCoverage":true},{"functionName":"uint32","ranges":[{"startOffset":354,"endOffset":398,"count":418003}],"isBlockCoverage":true},{"functionName":"uint53","ranges":[{"startOffset":422,"endOffset":554,"count":10000}],"isBlockCoverage":true},{"functionName":"oneOf","ranges":[{"startOffset":640,"endOffset":683,"count":1}],"isBlockCoverage":true},{"functionName":"uuidv4","ranges":[{"startOffset":808,"endOffset":922,"count":10001}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":872,"endOffset":920,"count":310031}],"isBlockCoverage":true}]},{"scriptId":"147","url":"file:///home/dmonad/ylabs/lib0/prng.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6079,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":1105,"endOffset":1134,"count":87971}],"isBlockCoverage":true},{"functionName":"bool","ranges":[{"startOffset":1288,"endOffset":1314,"count":25004}],"isBlockCoverage":true},{"functionName":"int53","ranges":[{"startOffset":1663,"endOffset":1728,"count":57222}],"isBlockCoverage":true},{"functionName":"uint53","ranges":[{"startOffset":2078,"endOffset":2127,"count":25377}],"isBlockCoverage":true},{"functionName":"int32","ranges":[{"startOffset":2476,"endOffset":2541,"count":11137510}],"isBlockCoverage":true},{"functionName":"uint32","ranges":[{"startOffset":2891,"endOffset":2936,"count":81810}],"isBlockCoverage":true},{"functionName":"int31","ranges":[{"startOffset":3430,"endOffset":3469,"count":2387720}],"isBlockCoverage":true},{"functionName":"real53","ranges":[{"startOffset":3665,"endOffset":3682,"count":17435}],"isBlockCoverage":true},{"functionName":"char","ranges":[{"startOffset":4086,"endOffset":4126,"count":15010}],"isBlockCoverage":true},{"functionName":"letter","ranges":[{"startOffset":4221,"endOffset":4261,"count":281016}],"isBlockCoverage":true},{"functionName":"word","ranges":[{"startOffset":4468,"endOffset":4635,"count":22927},{"startOffset":4592,"endOffset":4620,"count":281016}],"isBlockCoverage":true},{"functionName":"utf16Rune","ranges":[{"startOffset":4791,"endOffset":4874,"count":2021001}],"isBlockCoverage":true},{"functionName":"utf16String","ranges":[{"startOffset":4965,"endOffset":5118,"count":11795},{"startOffset":5072,"endOffset":5103,"count":2021001}],"isBlockCoverage":true},{"functionName":"oneOf","ranges":[{"startOffset":5375,"endOffset":5429,"count":35971}],"isBlockCoverage":true},{"functionName":"uint8Array","ranges":[{"startOffset":5533,"endOffset":5699,"count":42836},{"startOffset":5638,"endOffset":5684,"count":8621499}],"isBlockCoverage":true},{"functionName":"uint16Array","ranges":[{"startOffset":5827,"endOffset":5889,"count":9}],"isBlockCoverage":true},{"functionName":"uint32Array","ranges":[{"startOffset":5995,"endOffset":6057,"count":18}],"isBlockCoverage":true}]},{"scriptId":"148","url":"file:///home/dmonad/ylabs/lib0/statistics.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":540,"count":1}],"isBlockCoverage":true},{"functionName":"median","ranges":[{"startOffset":246,"endOffset":413,"count":23},{"startOffset":270,"endOffset":275,"count":1},{"startOffset":276,"endOffset":413,"count":22},{"startOffset":300,"endOffset":327,"count":10},{"startOffset":328,"endOffset":412,"count":12}],"isBlockCoverage":true},{"functionName":"average","ranges":[{"startOffset":496,"endOffset":539,"count":17}],"isBlockCoverage":true}]},{"scriptId":"149","url":"file:///home/dmonad/ylabs/lib0/array.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3722,"count":1}],"isBlockCoverage":true},{"functionName":"last","ranges":[{"startOffset":254,"endOffset":280,"count":18}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":349,"endOffset":383,"count":1}],"isBlockCoverage":true},{"functionName":"copy","ranges":[{"startOffset":473,"endOffset":513,"count":1}],"isBlockCoverage":true},{"functionName":"appendTo","ranges":[{"startOffset":652,"endOffset":737,"count":2},{"startOffset":708,"endOffset":735,"count":4}],"isBlockCoverage":true},{"functionName":"every","ranges":[{"startOffset":1178,"endOffset":1307,"count":3},{"startOffset":1231,"endOffset":1291,"count":8},{"startOffset":1261,"endOffset":1287,"count":1},{"startOffset":1291,"endOffset":1306,"count":2}],"isBlockCoverage":true},{"functionName":"some","ranges":[{"startOffset":1546,"endOffset":1674,"count":2},{"startOffset":1599,"endOffset":1657,"count":5},{"startOffset":1628,"endOffset":1653,"count":1},{"startOffset":1657,"endOffset":1673,"count":1}],"isBlockCoverage":true},{"functionName":"equalFlat","ranges":[{"startOffset":1811,"endOffset":1890,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1855,"endOffset":1889,"count":2}],"isBlockCoverage":true},{"functionName":"flatten","ranges":[{"startOffset":2001,"endOffset":2081,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2051,"endOffset":2080,"count":2}],"isBlockCoverage":true},{"functionName":"unfold","ranges":[{"startOffset":2216,"endOffset":2342,"count":8},{"startOffset":2293,"endOffset":2325,"count":20105}],"isBlockCoverage":true},{"functionName":"fold","ranges":[{"startOffset":2510,"endOffset":2557,"count":2298031}],"isBlockCoverage":true},{"functionName":"unique","ranges":[{"startOffset":2689,"endOffset":2715,"count":2}],"isBlockCoverage":true},{"functionName":"uniqueBy","ranges":[{"startOffset":2863,"endOffset":3202,"count":2},{"startOffset":3124,"endOffset":3180,"count":1}],"isBlockCoverage":true},{"functionName":"map","ranges":[{"startOffset":3476,"endOffset":3721,"count":5191},{"startOffset":3602,"endOffset":3685,"count":120924}],"isBlockCoverage":true}]},{"scriptId":"150","url":"file:///home/dmonad/ylabs/lib0/json.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":296,"count":1}],"isBlockCoverage":true}]},{"scriptId":"151","url":"file:///home/dmonad/ylabs/lib0/time.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1229,"count":1}],"isBlockCoverage":true},{"functionName":"getDate","ranges":[{"startOffset":214,"endOffset":230,"count":1}],"isBlockCoverage":true},{"functionName":"humanizeDuration","ranges":[{"startOffset":570,"endOffset":1228,"count":411},{"startOffset":594,"endOffset":690,"count":399},{"startOffset":690,"endOffset":880,"count":12},{"startOffset":880,"endOffset":993,"count":4},{"startOffset":918,"endOffset":933,"count":2},{"startOffset":935,"endOffset":983,"count":3},{"startOffset":957,"endOffset":968,"count":2},{"startOffset":969,"endOffset":976,"count":1},{"startOffset":984,"endOffset":988,"count":1},{"startOffset":993,"endOffset":1011,"count":8},{"startOffset":1011,"endOffset":1158,"count":6},{"startOffset":1077,"endOffset":1092,"count":4},{"startOffset":1094,"endOffset":1148,"count":4},{"startOffset":1130,"endOffset":1139,"count":0},{"startOffset":1149,"endOffset":1153,"count":2},{"startOffset":1158,"endOffset":1199,"count":2},{"startOffset":1199,"endOffset":1220,"count":1},{"startOffset":1221,"endOffset":1225,"count":1}],"isBlockCoverage":true}]},{"scriptId":"152","url":"file:///home/dmonad/ylabs/lib0/promise.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2481,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":334,"endOffset":381,"count":20}],"isBlockCoverage":true},{"functionName":"createEmpty","ranges":[{"startOffset":511,"endOffset":530,"count":3}],"isBlockCoverage":true},{"functionName":"reject","ranges":[{"startOffset":878,"endOffset":910,"count":5}],"isBlockCoverage":true},{"functionName":"resolve","ranges":[{"startOffset":1010,"endOffset":1037,"count":5}],"isBlockCoverage":true},{"functionName":"resolveWith","ranges":[{"startOffset":1131,"endOffset":1158,"count":3}],"isBlockCoverage":true},{"functionName":"until","ranges":[{"startOffset":1405,"endOffset":1932,"count":5}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1457,"endOffset":1931,"count":5}],"isBlockCoverage":true},{"functionName":"untilInterval","ranges":[{"startOffset":1576,"endOffset":1857,"count":15},{"startOffset":1601,"endOffset":1660,"count":4},{"startOffset":1660,"endOffset":1853,"count":11},{"startOffset":1682,"endOffset":1853,"count":2},{"startOffset":1763,"endOffset":1847,"count":1}],"isBlockCoverage":true},{"functionName":"wait","ranges":[{"startOffset":2021,"endOffset":2089,"count":9}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2039,"endOffset":2088,"count":9}],"isBlockCoverage":true},{"functionName":"isPromise","ranges":[{"startOffset":2414,"endOffset":2480,"count":115111},{"startOffset":2440,"endOffset":2480,"count":115080},{"startOffset":2446,"endOffset":2455,"count":2},{"startOffset":2456,"endOffset":2466,"count":2},{"startOffset":2467,"endOffset":2479,"count":2}],"isBlockCoverage":true}]},{"scriptId":"153","url":"file:///home/dmonad/ylabs/lib0/performance.node.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":614,"count":1},{"startOffset":267,"endOffset":293,"count":0},{"startOffset":429,"endOffset":447,"count":0},{"startOffset":587,"endOffset":613,"count":0}],"isBlockCoverage":true}]},{"scriptId":"154","url":"node:perf_hooks","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1065,"count":1}],"isBlockCoverage":false}]},{"scriptId":"155","url":"node:internal/perf/performance_entry","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3272,"count":1}],"isBlockCoverage":false},{"functionName":"isPerformanceEntry","ranges":[{"startOffset":675,"endOffset":748,"count":411}],"isBlockCoverage":true},{"functionName":"PerformanceEntry","ranges":[{"startOffset":777,"endOffset":1132,"count":411},{"startOffset":962,"endOffset":1012,"count":0}],"isBlockCoverage":true},{"functionName":"get name","ranges":[{"startOffset":1136,"endOffset":1236,"count":0}],"isBlockCoverage":false},{"functionName":"get entryType","ranges":[{"startOffset":1240,"endOffset":1355,"count":411}],"isBlockCoverage":true},{"functionName":"get startTime","ranges":[{"startOffset":1359,"endOffset":1474,"count":0}],"isBlockCoverage":false},{"functionName":"get duration","ranges":[{"startOffset":1478,"endOffset":1590,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1594,"endOffset":1838,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":1842,"endOffset":2064,"count":0}],"isBlockCoverage":false},{"functionName":"createPerformanceEntry","ranges":[{"startOffset":2286,"endOffset":2422,"count":0}],"isBlockCoverage":false},{"functionName":"get detail","ranges":[{"startOffset":2539,"endOffset":2649,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":2653,"endOffset":2904,"count":0}],"isBlockCoverage":false},{"functionName":"createPerformanceNodeEntry","ranges":[{"startOffset":2908,"endOffset":3112,"count":0}],"isBlockCoverage":false}]},{"scriptId":"156","url":"node:internal/perf/resource_timing","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7433,"count":1}],"isBlockCoverage":false},{"functionName":"PerformanceResourceTiming","ranges":[{"startOffset":831,"endOffset":1045,"count":0}],"isBlockCoverage":false},{"functionName":"get name","ranges":[{"startOffset":1049,"endOffset":1174,"count":0}],"isBlockCoverage":false},{"functionName":"get startTime","ranges":[{"startOffset":1178,"endOffset":1314,"count":0}],"isBlockCoverage":false},{"functionName":"get duration","ranges":[{"startOffset":1318,"endOffset":1481,"count":0}],"isBlockCoverage":false},{"functionName":"get initiatorType","ranges":[{"startOffset":1485,"endOffset":1621,"count":0}],"isBlockCoverage":false},{"functionName":"get workerStart","ranges":[{"startOffset":1625,"endOffset":1781,"count":0}],"isBlockCoverage":false},{"functionName":"get redirectStart","ranges":[{"startOffset":1785,"endOffset":1933,"count":0}],"isBlockCoverage":false},{"functionName":"get redirectEnd","ranges":[{"startOffset":1937,"endOffset":2081,"count":0}],"isBlockCoverage":false},{"functionName":"get fetchStart","ranges":[{"startOffset":2085,"endOffset":2234,"count":0}],"isBlockCoverage":false},{"functionName":"get domainLookupStart","ranges":[{"startOffset":2238,"endOffset":2421,"count":0}],"isBlockCoverage":false},{"functionName":"get domainLookupEnd","ranges":[{"startOffset":2425,"endOffset":2604,"count":0}],"isBlockCoverage":false},{"functionName":"get connectStart","ranges":[{"startOffset":2608,"endOffset":2784,"count":0}],"isBlockCoverage":false},{"functionName":"get connectEnd","ranges":[{"startOffset":2788,"endOffset":2960,"count":0}],"isBlockCoverage":false},{"functionName":"get secureConnectionStart","ranges":[{"startOffset":2964,"endOffset":3162,"count":0}],"isBlockCoverage":false},{"functionName":"get nextHopProtocol","ranges":[{"startOffset":3166,"endOffset":3355,"count":0}],"isBlockCoverage":false},{"functionName":"get requestStart","ranges":[{"startOffset":3359,"endOffset":3517,"count":0}],"isBlockCoverage":false},{"functionName":"get responseStart","ranges":[{"startOffset":3521,"endOffset":3681,"count":0}],"isBlockCoverage":false},{"functionName":"get responseEnd","ranges":[{"startOffset":3685,"endOffset":3821,"count":0}],"isBlockCoverage":false},{"functionName":"get encodedBodySize","ranges":[{"startOffset":3825,"endOffset":3973,"count":0}],"isBlockCoverage":false},{"functionName":"get decodedBodySize","ranges":[{"startOffset":3977,"endOffset":4125,"count":0}],"isBlockCoverage":false},{"functionName":"get transferSize","ranges":[{"startOffset":4129,"endOffset":4383,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":4387,"endOffset":5328,"count":0}],"isBlockCoverage":false},{"functionName":"createPerformanceResourceTiming","ranges":[{"startOffset":6196,"endOffset":6793,"count":0}],"isBlockCoverage":false},{"functionName":"markResourceTiming","ranges":[{"startOffset":6862,"endOffset":7358,"count":0}],"isBlockCoverage":false}]},{"scriptId":"157","url":"node:internal/perf/observe","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":16722,"count":1}],"isBlockCoverage":false},{"functionName":"queuePending","ranges":[{"startOffset":2600,"endOffset":2861,"count":0}],"isBlockCoverage":false},{"functionName":"getObserverType","ranges":[{"startOffset":2863,"endOffset":3203,"count":0}],"isBlockCoverage":false},{"functionName":"maybeDecrementObserverCounts","ranges":[{"startOffset":3205,"endOffset":3626,"count":0}],"isBlockCoverage":false},{"functionName":"maybeIncrementObserverCount","ranges":[{"startOffset":3628,"endOffset":3970,"count":0}],"isBlockCoverage":false},{"functionName":"performanceObserverSorter","ranges":[{"startOffset":4047,"endOffset":4114,"count":0}],"isBlockCoverage":false},{"functionName":"PerformanceObserverEntryList","ranges":[{"startOffset":4156,"endOffset":4384,"count":0}],"isBlockCoverage":false},{"functionName":"getEntries","ranges":[{"startOffset":4388,"endOffset":4527,"count":0}],"isBlockCoverage":false},{"functionName":"getEntriesByType","ranges":[{"startOffset":4531,"endOffset":4835,"count":0}],"isBlockCoverage":false},{"functionName":"getEntriesByName","ranges":[{"startOffset":4839,"endOffset":5332,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":5336,"endOffset":5584,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":5936,"endOffset":9533,"count":0}],"isBlockCoverage":false},{"functionName":"enqueue","ranges":[{"startOffset":10015,"endOffset":10217,"count":411},{"startOffset":10079,"endOffset":10146,"count":0},{"startOffset":10180,"endOffset":10215,"count":0}],"isBlockCoverage":true},{"functionName":"bufferUserTiming","ranges":[{"startOffset":10278,"endOffset":11304,"count":411},{"startOffset":10392,"endOffset":10427,"count":274},{"startOffset":10427,"endOffset":10523,"count":137},{"startOffset":10500,"endOffset":10523,"count":0},{"startOffset":10640,"endOffset":10680,"count":0},{"startOffset":10682,"endOffset":11302,"count":0}],"isBlockCoverage":true},{"functionName":"bufferResourceTiming","ranges":[{"startOffset":11592,"endOffset":12856,"count":0}],"isBlockCoverage":false},{"functionName":"setResourceTimingBufferSize","ranges":[{"startOffset":12944,"endOffset":13216,"count":0}],"isBlockCoverage":false},{"functionName":"setDispatchBufferFull","ranges":[{"startOffset":13218,"endOffset":13283,"count":1}],"isBlockCoverage":true},{"functionName":"clearEntriesFromBuffer","ranges":[{"startOffset":13285,"endOffset":13885,"count":0}],"isBlockCoverage":false},{"functionName":"filterBufferMapByNameAndType","ranges":[{"startOffset":13887,"endOffset":14729,"count":0}],"isBlockCoverage":false},{"functionName":"observerCallback","ranges":[{"startOffset":14731,"endOffset":15847,"count":0}],"isBlockCoverage":false},{"functionName":"hasObserver","ranges":[{"startOffset":15884,"endOffset":16003,"count":0}],"isBlockCoverage":false},{"functionName":"startPerf","ranges":[{"startOffset":16006,"endOffset":16116,"count":0}],"isBlockCoverage":false},{"functionName":"stopPerf","ranges":[{"startOffset":16118,"endOffset":16433,"count":0}],"isBlockCoverage":false}]},{"scriptId":"158","url":"node:internal/perf/usertiming","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6259,"count":1}],"isBlockCoverage":false},{"functionName":"getMark","ranges":[{"startOffset":1134,"endOffset":1586,"count":274},{"startOffset":1185,"endOffset":1192,"count":0},{"startOffset":1225,"endOffset":1322,"count":0},{"startOffset":1393,"endOffset":1417,"count":0},{"startOffset":1482,"endOffset":1571,"count":0}],"isBlockCoverage":true},{"functionName":"PerformanceMark","ranges":[{"startOffset":1639,"endOffset":2370,"count":274},{"startOffset":1712,"endOffset":1761,"count":0},{"startOffset":1838,"endOffset":1884,"count":0},{"startOffset":2084,"endOffset":2139,"count":0},{"startOffset":2241,"endOffset":2272,"count":0}],"isBlockCoverage":true},{"functionName":"get detail","ranges":[{"startOffset":2374,"endOffset":2479,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":2483,"endOffset":2666,"count":0}],"isBlockCoverage":false},{"functionName":"PerformanceMeasure","ranges":[{"startOffset":2917,"endOffset":3214,"count":137},{"startOffset":3102,"endOffset":3152,"count":0}],"isBlockCoverage":true},{"functionName":"get detail","ranges":[{"startOffset":3218,"endOffset":3326,"count":0}],"isBlockCoverage":false},{"functionName":"createPerformanceMeasure","ranges":[{"startOffset":3528,"endOffset":3733,"count":137}],"isBlockCoverage":true},{"functionName":"mark","ranges":[{"startOffset":3735,"endOffset":3876,"count":274}],"isBlockCoverage":true},{"functionName":"calculateStartDuration","ranges":[{"startOffset":3878,"endOffset":5461,"count":137},{"startOffset":4092,"endOffset":4214,"count":0},{"startOffset":4235,"endOffset":4793,"count":0},{"startOffset":4857,"endOffset":5083,"count":0},{"startOffset":5183,"endOffset":5402,"count":0}],"isBlockCoverage":true},{"functionName":"measure","ranges":[{"startOffset":5463,"endOffset":5898,"count":137},{"startOffset":5721,"endOffset":5746,"count":0}],"isBlockCoverage":true},{"functionName":"clearMarkTimings","ranges":[{"startOffset":5900,"endOffset":6155,"count":0}],"isBlockCoverage":false}]},{"scriptId":"159","url":"node:internal/perf/nodetiming","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3516,"count":1}],"isBlockCoverage":false},{"functionName":"PerformanceNodeTiming","ranges":[{"startOffset":729,"endOffset":2742,"count":1}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":1394,"endOffset":1490,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":1606,"endOffset":1700,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":1820,"endOffset":1917,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":2035,"endOffset":2131,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":2248,"endOffset":2343,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":2469,"endOffset":2586,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2746,"endOffset":2987,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":2991,"endOffset":3377,"count":0}],"isBlockCoverage":false}]},{"scriptId":"160","url":"node:internal/perf/performance","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6365,"count":1}],"isBlockCoverage":false},{"functionName":"Performance","ranges":[{"startOffset":1338,"endOffset":1398,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1402,"endOffset":1697,"count":0}],"isBlockCoverage":false},{"functionName":"clearMarks","ranges":[{"startOffset":1701,"endOffset":1932,"count":0}],"isBlockCoverage":false},{"functionName":"clearMeasures","ranges":[{"startOffset":1936,"endOffset":2145,"count":0}],"isBlockCoverage":false},{"functionName":"clearResourceTimings","ranges":[{"startOffset":2149,"endOffset":2366,"count":0}],"isBlockCoverage":false},{"functionName":"getEntries","ranges":[{"startOffset":2370,"endOffset":2498,"count":0}],"isBlockCoverage":false},{"functionName":"getEntriesByName","ranges":[{"startOffset":2502,"endOffset":2759,"count":0}],"isBlockCoverage":false},{"functionName":"getEntriesByType","ranges":[{"startOffset":2763,"endOffset":3020,"count":0}],"isBlockCoverage":false},{"functionName":"mark","ranges":[{"startOffset":3024,"endOffset":3245,"count":274},{"startOffset":3160,"endOffset":3209,"count":0}],"isBlockCoverage":true},{"functionName":"measure","ranges":[{"startOffset":3249,"endOffset":3534,"count":137},{"startOffset":3423,"endOffset":3472,"count":0}],"isBlockCoverage":true},{"functionName":"now","ranges":[{"startOffset":3538,"endOffset":3634,"count":115626}],"isBlockCoverage":true},{"functionName":"setResourceTimingBufferSize","ranges":[{"startOffset":3638,"endOffset":3954,"count":0}],"isBlockCoverage":false},{"functionName":"get timeOrigin","ranges":[{"startOffset":3958,"endOffset":4084,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":4088,"endOffset":4316,"count":0}],"isBlockCoverage":false},{"functionName":"createPerformance","ranges":[{"startOffset":5917,"endOffset":6086,"count":1}],"isBlockCoverage":true},{"functionName":"Performance","ranges":[{"startOffset":5974,"endOffset":6065,"count":1}],"isBlockCoverage":true},{"functionName":"dispatchBufferFull","ranges":[{"startOffset":6130,"endOffset":6268,"count":0}],"isBlockCoverage":false}]},{"scriptId":"161","url":"node:internal/perf/event_loop_utilization","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1527,"count":1}],"isBlockCoverage":false},{"functionName":"eventLoopUtilization","ranges":[{"startOffset":153,"endOffset":446,"count":0}],"isBlockCoverage":false},{"functionName":"internalEventLoopUtilization","ranges":[{"startOffset":448,"endOffset":1447,"count":0}],"isBlockCoverage":false}]},{"scriptId":"162","url":"node:internal/perf/timerify","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2280,"count":1}],"isBlockCoverage":false},{"functionName":"processComplete","ranges":[{"startOffset":610,"endOffset":985,"count":0}],"isBlockCoverage":false},{"functionName":"timerify","ranges":[{"startOffset":987,"endOffset":2251,"count":0}],"isBlockCoverage":false}]},{"scriptId":"163","url":"node:internal/histogram","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8057,"count":1}],"isBlockCoverage":false},{"functionName":"isHistogram","ranges":[{"startOffset":894,"endOffset":968,"count":0}],"isBlockCoverage":false},{"functionName":"Histogram","ranges":[{"startOffset":990,"endOffset":1050,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1054,"endOffset":1466,"count":0}],"isBlockCoverage":false},{"functionName":"get count","ranges":[{"startOffset":1517,"endOffset":1644,"count":0}],"isBlockCoverage":false},{"functionName":"get countBigInt","ranges":[{"startOffset":1695,"endOffset":1834,"count":0}],"isBlockCoverage":false},{"functionName":"get min","ranges":[{"startOffset":1885,"endOffset":2008,"count":0}],"isBlockCoverage":false},{"functionName":"get minBigInt","ranges":[{"startOffset":2059,"endOffset":2194,"count":0}],"isBlockCoverage":false},{"functionName":"get max","ranges":[{"startOffset":2245,"endOffset":2368,"count":0}],"isBlockCoverage":false},{"functionName":"get maxBigInt","ranges":[{"startOffset":2419,"endOffset":2554,"count":0}],"isBlockCoverage":false},{"functionName":"get mean","ranges":[{"startOffset":2605,"endOffset":2730,"count":0}],"isBlockCoverage":false},{"functionName":"get exceeds","ranges":[{"startOffset":2781,"endOffset":2912,"count":0}],"isBlockCoverage":false},{"functionName":"get exceedsBigInt","ranges":[{"startOffset":2963,"endOffset":3106,"count":0}],"isBlockCoverage":false},{"functionName":"get stddev","ranges":[{"startOffset":3157,"endOffset":3286,"count":0}],"isBlockCoverage":false},{"functionName":"percentile","ranges":[{"startOffset":3357,"endOffset":3706,"count":0}],"isBlockCoverage":false},{"functionName":"percentileBigInt","ranges":[{"startOffset":3777,"endOffset":4138,"count":0}],"isBlockCoverage":false},{"functionName":"get percentiles","ranges":[{"startOffset":4201,"endOffset":4390,"count":0}],"isBlockCoverage":false},{"functionName":"get percentilesBigInt","ranges":[{"startOffset":4453,"endOffset":4654,"count":0}],"isBlockCoverage":false},{"functionName":"reset","ranges":[{"startOffset":4691,"endOffset":4807,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":4811,"endOffset":4968,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":4972,"endOffset":5032,"count":0}],"isBlockCoverage":false},{"functionName":"toJSON","ranges":[{"startOffset":5036,"endOffset":5293,"count":0}],"isBlockCoverage":false},{"functionName":"RecordableHistogram","ranges":[{"startOffset":5345,"endOffset":5405,"count":0}],"isBlockCoverage":false},{"functionName":"record","ranges":[{"startOffset":5474,"endOffset":5748,"count":0}],"isBlockCoverage":false},{"functionName":"recordDelta","ranges":[{"startOffset":5785,"endOffset":5936,"count":0}],"isBlockCoverage":false},{"functionName":"add","ranges":[{"startOffset":5992,"endOffset":6265,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":6269,"endOffset":6436,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":6440,"endOffset":6500,"count":0}],"isBlockCoverage":false},{"functionName":"internalHistogram","ranges":[{"startOffset":6504,"endOffset":6691,"count":0}],"isBlockCoverage":false},{"functionName":"internalHistogram.","ranges":[{"startOffset":6736,"endOffset":6744,"count":0}],"isBlockCoverage":false},{"functionName":"internalRecordableHistogram","ranges":[{"startOffset":6747,"endOffset":6986,"count":0}],"isBlockCoverage":false},{"functionName":"internalRecordableHistogram.","ranges":[{"startOffset":7041,"endOffset":7049,"count":0}],"isBlockCoverage":false},{"functionName":"createHistogram","ranges":[{"startOffset":7193,"endOffset":7880,"count":0}],"isBlockCoverage":false}]},{"scriptId":"164","url":"node:internal/perf/event_loop_delay","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1724,"count":1}],"isBlockCoverage":false},{"functionName":"ELDHistogram","ranges":[{"startOffset":625,"endOffset":686,"count":0}],"isBlockCoverage":false},{"functionName":"enable","ranges":[{"startOffset":726,"endOffset":937,"count":0}],"isBlockCoverage":false},{"functionName":"disable","ranges":[{"startOffset":977,"endOffset":1190,"count":0}],"isBlockCoverage":false},{"functionName":"monitorEventLoopDelay","ranges":[{"startOffset":1283,"endOffset":1682,"count":0}],"isBlockCoverage":false}]},{"scriptId":"165","url":"file:///home/dmonad/ylabs/lib0/broadcastchannel.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3042,"count":1},{"startOffset":1710,"endOffset":1732,"count":0}],"isBlockCoverage":true},{"functionName":"LocalStoragePolyfill","ranges":[{"startOffset":999,"endOffset":1348,"count":0}],"isBlockCoverage":false},{"functionName":"postMessage","ranges":[{"startOffset":1394,"endOffset":1521,"count":0}],"isBlockCoverage":false},{"functionName":"close","ranges":[{"startOffset":1525,"endOffset":1577,"count":0}],"isBlockCoverage":false},{"functionName":"getChannel","ranges":[{"startOffset":1825,"endOffset":2129,"count":6}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1870,"endOffset":2128,"count":2}],"isBlockCoverage":true},{"functionName":"bc.onmessage","ranges":[{"startOffset":2033,"endOffset":2090,"count":0}],"isBlockCoverage":false},{"functionName":"subscribe","ranges":[{"startOffset":2282,"endOffset":2340,"count":1}],"isBlockCoverage":true},{"functionName":"unsubscribe","ranges":[{"startOffset":2499,"endOffset":2720,"count":1}],"isBlockCoverage":true},{"functionName":"publish","ranges":[{"startOffset":2910,"endOffset":3041,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3014,"endOffset":3038,"count":2}],"isBlockCoverage":true}]},{"scriptId":"166","url":"file:///home/dmonad/ylabs/lib0/hash/rabin-gf2-polynomial.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8884,"count":1}],"isBlockCoverage":true},{"functionName":"_degreeToMinByteLength","ranges":[{"startOffset":622,"endOffset":658,"count":33392}],"isBlockCoverage":true},{"functionName":"GF2Polynomial","ranges":[{"startOffset":928,"endOffset":1022,"count":6429052}],"isBlockCoverage":true},{"functionName":"createFromBytes","ranges":[{"startOffset":1123,"endOffset":1427,"count":226890},{"startOffset":1234,"endOffset":1414,"count":542849},{"startOffset":1300,"endOffset":1410,"count":4342792},{"startOffset":1342,"endOffset":1385,"count":2079056}],"isBlockCoverage":true},{"functionName":"toUint8Array","ranges":[{"startOffset":1560,"endOffset":1869,"count":3014}],"isBlockCoverage":true},{"functionName":"setBit","ranges":[{"startOffset":1736,"endOffset":1826,"count":74957}],"isBlockCoverage":true},{"functionName":"createFromUint","ranges":[{"startOffset":2021,"endOffset":2164,"count":4},{"startOffset":2093,"endOffset":2132,"count":16}],"isBlockCoverage":true},{"functionName":"createRandom","ranges":[{"startOffset":2284,"endOffset":2762,"count":30378}],"isBlockCoverage":true},{"functionName":"getHighestDegree","ranges":[{"startOffset":2850,"endOffset":2901,"count":2298024}],"isBlockCoverage":true},{"functionName":"addInto","ranges":[{"startOffset":3118,"endOffset":3285,"count":4472374}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3153,"endOffset":3282,"count":75106147},{"startOffset":3197,"endOffset":3236,"count":38915532},{"startOffset":3236,"endOffset":3278,"count":36190615}],"isBlockCoverage":true},{"functionName":"orInto","ranges":[{"startOffset":3501,"endOffset":3581,"count":195000}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3536,"endOffset":3578,"count":779520}],"isBlockCoverage":true},{"functionName":"add","ranges":[{"startOffset":3793,"endOffset":4085,"count":70092}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3865,"endOffset":3954,"count":70092},{"startOffset":3910,"endOffset":3950,"count":59184}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3977,"endOffset":4066,"count":406340},{"startOffset":4022,"endOffset":4062,"count":395432}],"isBlockCoverage":true},{"functionName":"clone","ranges":[{"startOffset":4269,"endOffset":4380,"count":1117248}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4335,"endOffset":4361,"count":13495833}],"isBlockCoverage":true},{"functionName":"addDegreeInto","ranges":[{"startOffset":4598,"endOffset":4717,"count":28048959},{"startOffset":4644,"endOffset":4678,"count":13002690},{"startOffset":4678,"endOffset":4715,"count":15046269}],"isBlockCoverage":true},{"functionName":"multiply","ranges":[{"startOffset":4867,"endOffset":5064,"count":345948}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4939,"endOffset":5045,"count":1707323}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4975,"endOffset":5040,"count":28048959}],"isBlockCoverage":true},{"functionName":"shiftLeft","ranges":[{"startOffset":5210,"endOffset":5382,"count":4667374}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":5283,"endOffset":5363,"count":79720846}],"isBlockCoverage":true},{"functionName":"mod","ranges":[{"startOffset":5522,"endOffset":5830,"count":1117248},{"startOffset":5688,"endOffset":5812,"count":8139451},{"startOffset":5731,"endOffset":5808,"count":4472374}],"isBlockCoverage":true},{"functionName":"modPow","ranges":[{"startOffset":6025,"endOffset":6244,"count":70092},{"startOffset":6074,"endOffset":6242,"count":346043},{"startOffset":6099,"endOffset":6149,"count":69996},{"startOffset":6180,"endOffset":6207,"count":70092},{"startOffset":6207,"endOffset":6242,"count":275951}],"isBlockCoverage":true},{"functionName":"gcd","ranges":[{"startOffset":6396,"endOffset":6518,"count":70092},{"startOffset":6440,"endOffset":6504,"count":504708}],"isBlockCoverage":true},{"functionName":"equals","ranges":[{"startOffset":6636,"endOffset":6798,"count":70093},{"startOffset":6693,"endOffset":6705,"count":21750},{"startOffset":6705,"endOffset":6736,"count":48343},{"startOffset":6736,"endOffset":6782,"count":48354},{"startOffset":6766,"endOffset":6778,"count":7618},{"startOffset":6782,"endOffset":6797,"count":40725}],"isBlockCoverage":true},{"functionName":"reduceExponent","ranges":[{"startOffset":7159,"endOffset":7317,"count":70092}],"isBlockCoverage":true},{"functionName":"isIrreducibleBenOr","ranges":[{"startOffset":7673,"endOffset":7888,"count":30383},{"startOffset":7756,"endOffset":7872,"count":70092},{"startOffset":7842,"endOffset":7868,"count":29368},{"startOffset":7872,"endOffset":7887,"count":1015}],"isBlockCoverage":true},{"functionName":"createIrreducible","ranges":[{"startOffset":7957,"endOffset":8066,"count":10},{"startOffset":7984,"endOffset":8064,"count":252},{"startOffset":8052,"endOffset":8060,"count":10}],"isBlockCoverage":true},{"functionName":"fingerprint","ranges":[{"startOffset":8228,"endOffset":8331,"count":1500}],"isBlockCoverage":true},{"functionName":"RabinPolynomialEncoder","ranges":[{"startOffset":8442,"endOffset":8521,"count":1500}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":8560,"endOffset":8758,"count":195000}],"isBlockCoverage":true},{"functionName":"getFingerprint","ranges":[{"startOffset":8762,"endOffset":8881,"count":1500}],"isBlockCoverage":true}]},{"scriptId":"167","url":"file:///home/dmonad/ylabs/lib0/hash/rabin-uncached.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1772,"count":1}],"isBlockCoverage":true},{"functionName":"RabinUncachedEncoder","ranges":[{"startOffset":395,"endOffset":646,"count":1500}],"isBlockCoverage":true},{"functionName":"add","ranges":[{"startOffset":815,"endOffset":1070,"count":742584},{"startOffset":971,"endOffset":1066,"count":5166169}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":1112,"endOffset":1560,"count":195000},{"startOffset":1334,"endOffset":1452,"count":1560000},{"startOffset":1386,"endOffset":1446,"count":742584}],"isBlockCoverage":true},{"functionName":"getFingerprint","ranges":[{"startOffset":1564,"endOffset":1769,"count":1500},{"startOffset":1681,"endOffset":1747,"count":9300}],"isBlockCoverage":true}]},{"scriptId":"168","url":"file:///home/dmonad/ylabs/lib0/hash/rabin.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3053,"count":1}],"isBlockCoverage":true},{"functionName":"ensureCache","ranges":[{"startOffset":872,"endOffset":1779,"count":3105}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":946,"endOffset":1778,"count":6},{"startOffset":1198,"endOffset":1761,"count":42},{"startOffset":1327,"endOffset":1757,"count":1524},{"startOffset":1516,"endOffset":1655,"count":9652}],"isBlockCoverage":true},{"functionName":"RabinEncoder","ranges":[{"startOffset":1869,"endOffset":2152,"count":3105}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":2194,"endOffset":2560,"count":392535},{"startOffset":2431,"endOffset":2516,"count":2813070}],"isBlockCoverage":true},{"functionName":"getFingerprint","ranges":[{"startOffset":2564,"endOffset":2769,"count":3100},{"startOffset":2681,"endOffset":2747,"count":18700}],"isBlockCoverage":true},{"functionName":"fingerprint","ranges":[{"startOffset":2871,"endOffset":3052,"count":1600},{"startOffset":2984,"endOffset":3016,"count":197535}],"isBlockCoverage":true}]},{"scriptId":"169","url":"file:///home/dmonad/ylabs/lib0/buffer.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4120,"count":1},{"startOffset":1918,"endOffset":1935,"count":0},{"startOffset":2013,"endOffset":2032,"count":0}],"isBlockCoverage":true},{"functionName":"createUint8ArrayFromLen","ranges":[{"startOffset":389,"endOffset":415,"count":61483}],"isBlockCoverage":true},{"functionName":"createUint8ArrayViewFromArrayBuffer","ranges":[{"startOffset":620,"endOffset":694,"count":10463}],"isBlockCoverage":true},{"functionName":"createUint8ArrayFromArrayBuffer","ranges":[{"startOffset":839,"endOffset":871,"count":1}],"isBlockCoverage":true},{"functionName":"toBase64Browser","ranges":[{"startOffset":976,"endOffset":1147,"count":0}],"isBlockCoverage":false},{"functionName":"toBase64Node","ranges":[{"startOffset":1248,"endOffset":1337,"count":15265}],"isBlockCoverage":true},{"functionName":"fromBase64Browser","ranges":[{"startOffset":1440,"endOffset":1646,"count":0}],"isBlockCoverage":false},{"functionName":"fromBase64Node","ranges":[{"startOffset":1721,"endOffset":1857,"count":10463}],"isBlockCoverage":true},{"functionName":"toBase64UrlEncoded","ranges":[{"startOffset":2206,"endOffset":2288,"count":5984}],"isBlockCoverage":true},{"functionName":"fromBase64UrlEncoded","ranges":[{"startOffset":2360,"endOffset":2430,"count":5987}],"isBlockCoverage":true},{"functionName":"toHexString","ranges":[{"startOffset":2581,"endOffset":2649,"count":5191}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2603,"endOffset":2639,"count":120924}],"isBlockCoverage":true},{"functionName":"fromHexString","ranges":[{"startOffset":2782,"endOffset":3012,"count":5175},{"startOffset":2903,"endOffset":2997,"count":120380}],"isBlockCoverage":true},{"functionName":"copyUint8Array","ranges":[{"startOffset":3177,"endOffset":3299,"count":15628}],"isBlockCoverage":true},{"functionName":"encodeAny","ranges":[{"startOffset":3505,"endOffset":3575,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3531,"endOffset":3574,"count":1}],"isBlockCoverage":true},{"functionName":"decodeAny","ranges":[{"startOffset":3689,"endOffset":3741,"count":1}],"isBlockCoverage":true},{"functionName":"shiftNBitsLeft","ranges":[{"startOffset":3933,"endOffset":4119,"count":742626},{"startOffset":3961,"endOffset":3970,"count":92537},{"startOffset":3970,"endOffset":4049,"count":650089},{"startOffset":4049,"endOffset":4105,"count":3873180},{"startOffset":4105,"endOffset":4118,"count":650089}],"isBlockCoverage":true}]},{"scriptId":"170","url":"file:///home/dmonad/ylabs/lib0/map.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2211,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":196,"endOffset":211,"count":10}],"isBlockCoverage":true},{"functionName":"copy","ranges":[{"startOffset":365,"endOffset":444,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":405,"endOffset":430,"count":3}],"isBlockCoverage":true},{"functionName":"setIfUndefined","ranges":[{"startOffset":927,"endOffset":1056,"count":3218},{"startOffset":1002,"endOffset":1041,"count":99}],"isBlockCoverage":true},{"functionName":"map","ranges":[{"startOffset":1334,"endOffset":1443,"count":2},{"startOffset":1395,"endOffset":1428,"count":89}],"isBlockCoverage":true},{"functionName":"any","ranges":[{"startOffset":1741,"endOffset":1856,"count":3},{"startOffset":1785,"endOffset":1839,"count":6},{"startOffset":1810,"endOffset":1835,"count":2},{"startOffset":1839,"endOffset":1855,"count":1}],"isBlockCoverage":true},{"functionName":"all","ranges":[{"startOffset":2094,"endOffset":2210,"count":2},{"startOffset":2138,"endOffset":2194,"count":5},{"startOffset":2164,"endOffset":2190,"count":1},{"startOffset":2194,"endOffset":2209,"count":1}],"isBlockCoverage":true}]},{"scriptId":"171","url":"file:///home/dmonad/ylabs/lib0/hash/sha256.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":5242,"count":1}],"isBlockCoverage":true},{"functionName":"rotr","ranges":[{"startOffset":349,"endOffset":398,"count":34082496}],"isBlockCoverage":true},{"functionName":"sum0to256","ranges":[{"startOffset":491,"endOffset":534,"count":3786944}],"isBlockCoverage":true},{"functionName":"sum1to256","ranges":[{"startOffset":627,"endOffset":670,"count":3786944}],"isBlockCoverage":true},{"functionName":"sigma0to256","ranges":[{"startOffset":765,"endOffset":804,"count":2840208}],"isBlockCoverage":true},{"functionName":"sigma1to256","ranges":[{"startOffset":899,"endOffset":940,"count":2840208}],"isBlockCoverage":true},{"functionName":"Hasher","ranges":[{"startOffset":2470,"endOffset":2746,"count":20013}],"isBlockCoverage":true},{"functionName":"_updateHash","ranges":[{"startOffset":2750,"endOffset":3501,"count":59171},{"startOffset":2845,"endOffset":2935,"count":2840208},{"startOffset":3116,"endOffset":3385,"count":3786944}],"isBlockCoverage":true},{"functionName":"digest","ranges":[{"startOffset":3547,"endOffset":5146,"count":20013},{"startOffset":3612,"endOffset":4143,"count":39158},{"startOffset":3687,"endOffset":3709,"count":626527},{"startOffset":3716,"endOffset":3809,"count":626525},{"startOffset":3834,"endOffset":4112,"count":2},{"startOffset":3967,"endOffset":4047,"count":3},{"startOffset":4320,"endOffset":4438,"count":160052},{"startOffset":4353,"endOffset":4371,"count":620202},{"startOffset":4379,"endOffset":4432,"count":600195},{"startOffset":4511,"endOffset":4597,"count":20011},{"startOffset":4544,"endOffset":4547,"count":4},{"startOffset":4548,"endOffset":4551,"count":20007},{"startOffset":5021,"endOffset":5128,"count":160104},{"startOffset":5060,"endOffset":5122,"count":640416}],"isBlockCoverage":true},{"functionName":"digest","ranges":[{"startOffset":5208,"endOffset":5241,"count":20013}],"isBlockCoverage":true}]},{"scriptId":"172","url":"file:///home/dmonad/ylabs/lib0/function.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3704,"count":1}],"isBlockCoverage":true},{"functionName":"callAll","ranges":[{"startOffset":334,"endOffset":506,"count":2},{"startOffset":396,"endOffset":424,"count":4},{"startOffset":462,"endOffset":500,"count":1}],"isBlockCoverage":true},{"functionName":"nop","ranges":[{"startOffset":527,"endOffset":535,"count":5}],"isBlockCoverage":true},{"functionName":"apply","ranges":[{"startOffset":623,"endOffset":631,"count":1}],"isBlockCoverage":true},{"functionName":"id","ranges":[{"startOffset":708,"endOffset":714,"count":3}],"isBlockCoverage":true},{"functionName":"equalityStrict","ranges":[{"startOffset":825,"endOffset":842,"count":36}],"isBlockCoverage":true},{"functionName":"equalityFlat","ranges":[{"startOffset":979,"endOffset":1187,"count":4},{"startOffset":1059,"endOffset":1186,"count":2},{"startOffset":1081,"endOffset":1131,"count":1},{"startOffset":1133,"endOffset":1185,"count":1}],"isBlockCoverage":true},{"functionName":"equalityDeep","ranges":[{"startOffset":1305,"endOffset":2819,"count":50},{"startOffset":1347,"endOffset":1384,"count":2},{"startOffset":1384,"endOffset":1424,"count":48},{"startOffset":1424,"endOffset":1446,"count":2},{"startOffset":1446,"endOffset":1462,"count":46},{"startOffset":1462,"endOffset":1483,"count":9},{"startOffset":1483,"endOffset":1515,"count":37},{"startOffset":1515,"endOffset":1588,"count":4},{"startOffset":1640,"endOffset":1861,"count":8},{"startOffset":1700,"endOffset":1772,"count":4},{"startOffset":1801,"endOffset":1835,"count":2},{"startOffset":1843,"endOffset":1861,"count":2},{"startOffset":1866,"endOffset":2056,"count":6},{"startOffset":1907,"endOffset":1937,"count":2},{"startOffset":1937,"endOffset":2038,"count":4},{"startOffset":1996,"endOffset":2030,"count":2},{"startOffset":2038,"endOffset":2056,"count":2},{"startOffset":2061,"endOffset":2295,"count":3},{"startOffset":2102,"endOffset":2132,"count":1},{"startOffset":2132,"endOffset":2277,"count":2},{"startOffset":2193,"endOffset":2233,"count":1},{"startOffset":2235,"endOffset":2269,"count":1},{"startOffset":2277,"endOffset":2295,"count":1},{"startOffset":2300,"endOffset":2550,"count":11},{"startOffset":2362,"endOffset":2392,"count":2},{"startOffset":2392,"endOffset":2420,"count":9},{"startOffset":2496,"endOffset":2530,"count":1},{"startOffset":2538,"endOffset":2550,"count":8},{"startOffset":2555,"endOffset":2767,"count":7},{"startOffset":2600,"endOffset":2630,"count":2},{"startOffset":2630,"endOffset":2672,"count":5},{"startOffset":2672,"endOffset":2755,"count":4},{"startOffset":2713,"endOffset":2747,"count":1},{"startOffset":2755,"endOffset":2767,"count":4},{"startOffset":2772,"endOffset":2799,"count":2},{"startOffset":2803,"endOffset":2818,"count":17}],"isBlockCoverage":true},{"functionName":"isOneOf","ranges":[{"startOffset":2958,"endOffset":3001,"count":3}],"isBlockCoverage":true},{"functionName":"isString","ranges":[{"startOffset":3137,"endOffset":3173,"count":4}],"isBlockCoverage":true},{"functionName":"isNumber","ranges":[{"startOffset":3250,"endOffset":3292,"count":4}],"isBlockCoverage":true},{"functionName":"is","ranges":[{"startOffset":3449,"endOffset":3483,"count":4}],"isBlockCoverage":true},{"functionName":"isTemplate","ranges":[{"startOffset":3593,"endOffset":3703,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3674,"endOffset":3703,"count":4}],"isBlockCoverage":true}]},{"scriptId":"173","url":"file:///home/dmonad/ylabs/lib0/webcrypto.node.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":195,"count":1}],"isBlockCoverage":true}]},{"scriptId":"174","url":"node:crypto","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8825,"count":1}],"isBlockCoverage":false},{"functionName":"lazyWebCrypto","ranges":[{"startOffset":3084,"endOffset":3186,"count":4}],"isBlockCoverage":true},{"functionName":"lazyOwnsProcessState","ranges":[{"startOffset":3210,"endOffset":3340,"count":0}],"isBlockCoverage":false},{"functionName":"createHash","ranges":[{"startOffset":3482,"endOffset":3564,"count":20000}],"isBlockCoverage":true},{"functionName":"createCipher","ranges":[{"startOffset":3566,"endOffset":3666,"count":0}],"isBlockCoverage":false},{"functionName":"createCipheriv","ranges":[{"startOffset":3668,"endOffset":3770,"count":0}],"isBlockCoverage":false},{"functionName":"createDecipher","ranges":[{"startOffset":3772,"endOffset":3876,"count":0}],"isBlockCoverage":false},{"functionName":"createDecipheriv","ranges":[{"startOffset":3878,"endOffset":3984,"count":0}],"isBlockCoverage":false},{"functionName":"createDiffieHellman","ranges":[{"startOffset":3986,"endOffset":4142,"count":0}],"isBlockCoverage":false},{"functionName":"createDiffieHellmanGroup","ranges":[{"startOffset":4144,"endOffset":4226,"count":0}],"isBlockCoverage":false},{"functionName":"createECDH","ranges":[{"startOffset":4228,"endOffset":4284,"count":0}],"isBlockCoverage":false},{"functionName":"createHmac","ranges":[{"startOffset":4286,"endOffset":4368,"count":0}],"isBlockCoverage":false},{"functionName":"createSign","ranges":[{"startOffset":4370,"endOffset":4452,"count":0}],"isBlockCoverage":false},{"functionName":"createVerify","ranges":[{"startOffset":4454,"endOffset":4540,"count":0}],"isBlockCoverage":false},{"functionName":"getFips","ranges":[{"startOffset":5583,"endOffset":5668,"count":0}],"isBlockCoverage":false},{"functionName":"setFips","ranges":[{"startOffset":5670,"endOffset":5954,"count":0}],"isBlockCoverage":false},{"functionName":"getRandomValues","ranges":[{"startOffset":5956,"endOffset":6047,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":6125,"endOffset":6379,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":6383,"endOffset":6572,"count":0}],"isBlockCoverage":false},{"functionName":"getRandomBytesAlias","ranges":[{"startOffset":6621,"endOffset":7454,"count":3}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":6719,"endOffset":7209,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":7215,"endOffset":7446,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":8198,"endOffset":8238,"count":2}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":8350,"endOffset":8397,"count":2}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":8523,"endOffset":8544,"count":2}],"isBlockCoverage":true}]},{"scriptId":"175","url":"node:internal/crypto/random","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":16246,"count":1}],"isBlockCoverage":false},{"functionName":"assertOffset","ranges":[{"startOffset":1260,"endOffset":1626,"count":459384},{"startOffset":1495,"endOffset":1577,"count":0}],"isBlockCoverage":true},{"functionName":"assertSize","ranges":[{"startOffset":1628,"endOffset":2089,"count":0}],"isBlockCoverage":false},{"functionName":"randomBytes","ranges":[{"startOffset":2091,"endOffset":2634,"count":0}],"isBlockCoverage":false},{"functionName":"randomFillSync","ranges":[{"startOffset":2636,"endOffset":3304,"count":459384},{"startOffset":2742,"endOffset":2850,"count":0},{"startOffset":2896,"endOffset":2900,"count":0},{"startOffset":3033,"endOffset":3110,"count":0},{"startOffset":3134,"endOffset":3145,"count":0},{"startOffset":3277,"endOffset":3287,"count":0}],"isBlockCoverage":true},{"functionName":"randomFill","ranges":[{"startOffset":3306,"endOffset":4352,"count":0}],"isBlockCoverage":false},{"functionName":"randomInt","ranges":[{"startOffset":4902,"endOffset":7142,"count":0}],"isBlockCoverage":false},{"functionName":"asyncRefillRandomIntCache","ranges":[{"startOffset":7144,"endOffset":8020,"count":0}],"isBlockCoverage":false},{"functionName":"onJobDone","ranges":[{"startOffset":8023,"endOffset":8185,"count":0}],"isBlockCoverage":false},{"functionName":"getRandomValues","ranges":[{"startOffset":8417,"endOffset":9033,"count":459384},{"startOffset":8537,"endOffset":8844,"count":0},{"startOffset":8876,"endOffset":8989,"count":0}],"isBlockCoverage":true},{"functionName":"getHexBytes","ranges":[{"startOffset":9398,"endOffset":9697,"count":0}],"isBlockCoverage":false},{"functionName":"serializeUUID","ranges":[{"startOffset":9699,"endOffset":10425,"count":0}],"isBlockCoverage":false},{"functionName":"getBufferedUUID","ranges":[{"startOffset":10427,"endOffset":10730,"count":0}],"isBlockCoverage":false},{"functionName":"getUnbufferedUUID","ranges":[{"startOffset":10732,"endOffset":10970,"count":0}],"isBlockCoverage":false},{"functionName":"randomUUID","ranges":[{"startOffset":10972,"endOffset":11292,"count":0}],"isBlockCoverage":false},{"functionName":"createRandomPrimeJob","ranges":[{"startOffset":11294,"endOffset":12527,"count":0}],"isBlockCoverage":false},{"functionName":"generatePrime","ranges":[{"startOffset":12529,"endOffset":12985,"count":0}],"isBlockCoverage":false},{"functionName":"generatePrimeSync","ranges":[{"startOffset":12987,"endOffset":13245,"count":0}],"isBlockCoverage":false},{"functionName":"numberToHexCharCode","ranges":[{"startOffset":13519,"endOffset":13563,"count":0}],"isBlockCoverage":false},{"functionName":"arrayBufferToUnsignedBigInt","ranges":[{"startOffset":13638,"endOffset":14065,"count":0}],"isBlockCoverage":false},{"functionName":"unsignedBigIntToBuffer","ranges":[{"startOffset":14067,"endOffset":14364,"count":0}],"isBlockCoverage":false},{"functionName":"checkPrime","ranges":[{"startOffset":14366,"endOffset":15259,"count":0}],"isBlockCoverage":false},{"functionName":"checkPrimeSync","ranges":[{"startOffset":15261,"endOffset":16059,"count":0}],"isBlockCoverage":false}]},{"scriptId":"176","url":"node:internal/crypto/pbkdf2","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3018,"count":1}],"isBlockCoverage":false},{"functionName":"pbkdf2","ranges":[{"startOffset":472,"endOffset":1136,"count":8},{"startOffset":580,"endOffset":632,"count":0}],"isBlockCoverage":true},{"functionName":"job.ondone","ranges":[{"startOffset":917,"endOffset":1119,"count":8},{"startOffset":969,"endOffset":1018,"count":0}],"isBlockCoverage":true},{"functionName":"pbkdf2Sync","ranges":[{"startOffset":1138,"endOffset":1543,"count":0}],"isBlockCoverage":false},{"functionName":"check","ranges":[{"startOffset":1545,"endOffset":2016,"count":8}],"isBlockCoverage":true},{"functionName":"pbkdf2DeriveBits","ranges":[{"startOffset":2059,"endOffset":2950,"count":8},{"startOffset":2197,"endOffset":2280,"count":0},{"startOffset":2351,"endOffset":2417,"count":0},{"startOffset":2445,"endOffset":2511,"count":0},{"startOffset":2530,"endOffset":2628,"count":0},{"startOffset":2768,"endOffset":2923,"count":0}],"isBlockCoverage":true}]},{"scriptId":"177","url":"node:internal/crypto/util","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":14973,"count":1}],"isBlockCoverage":false},{"functionName":"toBuf","ranges":[{"startOffset":1730,"endOffset":1909,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1943,"endOffset":1986,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2020,"endOffset":2062,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2096,"endOffset":2138,"count":0}],"isBlockCoverage":false},{"functionName":"setEngine","ranges":[{"startOffset":2142,"endOffset":2549,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2596,"endOffset":3060,"count":33},{"startOffset":2662,"endOffset":2676,"count":8},{"startOffset":2676,"endOffset":2711,"count":25},{"startOffset":2711,"endOffset":2814,"count":0},{"startOffset":2814,"endOffset":2849,"count":25},{"startOffset":2849,"endOffset":3041,"count":0},{"startOffset":3041,"endOffset":3059,"count":25}],"isBlockCoverage":true},{"functionName":"validateMaxBufferLength","ranges":[{"startOffset":6504,"endOffset":6717,"count":44026},{"startOffset":6593,"endOffset":6715,"count":0}],"isBlockCoverage":true},{"functionName":"normalizeAlgorithm","ranges":[{"startOffset":6943,"endOffset":9378,"count":82156},{"startOffset":7029,"endOffset":7080,"count":40044},{"startOffset":7080,"endOffset":7464,"count":42112},{"startOffset":7464,"endOffset":7729,"count":169018},{"startOffset":7533,"endOffset":7556,"count":0},{"startOffset":7650,"endOffset":7725,"count":42112},{"startOffset":7729,"endOffset":7767,"count":42112},{"startOffset":7767,"endOffset":7842,"count":0},{"startOffset":7842,"endOffset":7945,"count":42112},{"startOffset":7945,"endOffset":7970,"count":40061},{"startOffset":7970,"endOffset":8283,"count":2051},{"startOffset":8283,"endOffset":8301,"count":2043},{"startOffset":8302,"endOffset":8306,"count":8},{"startOffset":8352,"endOffset":9345,"count":4046},{"startOffset":8446,"endOffset":8455,"count":0},{"startOffset":8585,"endOffset":8596,"count":4023},{"startOffset":8598,"endOffset":9010,"count":2014},{"startOffset":8795,"endOffset":8805,"count":0},{"startOffset":8870,"endOffset":8873,"count":0},{"startOffset":8938,"endOffset":8983,"count":0},{"startOffset":9010,"endOffset":9341,"count":2032},{"startOffset":9059,"endOffset":9142,"count":23},{"startOffset":9142,"endOffset":9341,"count":2009},{"startOffset":9187,"endOffset":9341,"count":0},{"startOffset":9345,"endOffset":9377,"count":2051}],"isBlockCoverage":true},{"functionName":"getDataViewOrTypedArrayBuffer","ranges":[{"startOffset":9380,"endOffset":9519,"count":46070},{"startOffset":9447,"endOffset":9482,"count":0}],"isBlockCoverage":true},{"functionName":"getDataViewOrTypedArrayByteOffset","ranges":[{"startOffset":9521,"endOffset":9672,"count":2014},{"startOffset":9592,"endOffset":9631,"count":0}],"isBlockCoverage":true},{"functionName":"getDataViewOrTypedArrayByteLength","ranges":[{"startOffset":9674,"endOffset":9825,"count":2014},{"startOffset":9745,"endOffset":9784,"count":0}],"isBlockCoverage":true},{"functionName":"hasAnyNotIn","ranges":[{"startOffset":9827,"endOffset":9966,"count":45},{"startOffset":9890,"endOffset":9948,"count":63},{"startOffset":9936,"endOffset":9948,"count":0}],"isBlockCoverage":true},{"functionName":"validateBitLength","ranges":[{"startOffset":9968,"endOffset":10310,"count":0}],"isBlockCoverage":false},{"functionName":"validateByteLength","ranges":[{"startOffset":10312,"endOffset":10508,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10553,"endOffset":10822,"count":0}],"isBlockCoverage":false},{"functionName":"onDone","ranges":[{"startOffset":10826,"endOffset":11058,"count":42029},{"startOffset":10885,"endOffset":11037,"count":1},{"startOffset":11037,"endOffset":11057,"count":42028}],"isBlockCoverage":true},{"functionName":"jobPromise","ranges":[{"startOffset":11060,"endOffset":11330,"count":42029}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":11111,"endOffset":11326,"count":42029},{"startOffset":11267,"endOffset":11322,"count":0}],"isBlockCoverage":true},{"functionName":"bigIntArrayToUnsignedInt","ranges":[{"startOffset":11866,"endOffset":12146,"count":4},{"startOffset":11969,"endOffset":12126,"count":12},{"startOffset":12040,"endOffset":12051,"count":0},{"startOffset":12059,"endOffset":12066,"count":0}],"isBlockCoverage":true},{"functionName":"bigIntArrayToUnsignedBigInt","ranges":[{"startOffset":12148,"endOffset":12384,"count":0}],"isBlockCoverage":false},{"functionName":"getStringOption","ranges":[{"startOffset":12386,"endOffset":12551,"count":0}],"isBlockCoverage":false},{"functionName":"getUsagesUnion","ranges":[{"startOffset":12553,"endOffset":12765,"count":16},{"startOffset":12663,"endOffset":12746,"count":24},{"startOffset":12704,"endOffset":12742,"count":16}],"isBlockCoverage":true},{"functionName":"getBlockSize","ranges":[{"startOffset":12767,"endOffset":12948,"count":0}],"isBlockCoverage":false},{"functionName":"validateKeyOps","ranges":[{"startOffset":13087,"endOffset":14053,"count":11},{"startOffset":13160,"endOffset":13167,"count":0},{"startOffset":13271,"endOffset":13811,"count":12},{"startOffset":13401,"endOffset":13410,"count":0},{"startOffset":13494,"endOffset":13557,"count":0},{"startOffset":13879,"endOffset":14047,"count":12},{"startOffset":13929,"endOffset":14041,"count":0}],"isBlockCoverage":true},{"functionName":"secureHeapUsed","ranges":[{"startOffset":14055,"endOffset":14438,"count":0}],"isBlockCoverage":false}]},{"scriptId":"178","url":"node:internal/crypto/hashnames","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2520,"count":1}],"isBlockCoverage":false},{"functionName":"normalizeHashName","ranges":[{"startOffset":1890,"endOffset":2133,"count":40039},{"startOffset":1989,"endOffset":2001,"count":0},{"startOffset":2123,"endOffset":2130,"count":0}],"isBlockCoverage":true}]},{"scriptId":"179","url":"node:internal/crypto/scrypt","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3331,"count":1}],"isBlockCoverage":false},{"functionName":"scrypt","ranges":[{"startOffset":626,"endOffset":1292,"count":0}],"isBlockCoverage":false},{"functionName":"scryptSync","ranges":[{"startOffset":1294,"endOffset":1700,"count":0}],"isBlockCoverage":false},{"functionName":"check","ranges":[{"startOffset":1702,"endOffset":3283,"count":0}],"isBlockCoverage":false}]},{"scriptId":"180","url":"node:internal/crypto/hkdf","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3308,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":816,"endOffset":1274,"count":0}],"isBlockCoverage":false},{"functionName":"prepareKey","ranges":[{"startOffset":1278,"endOffset":1706,"count":0}],"isBlockCoverage":false},{"functionName":"hkdf","ranges":[{"startOffset":1708,"endOffset":2174,"count":0}],"isBlockCoverage":false},{"functionName":"hkdfSync","ranges":[{"startOffset":2176,"endOffset":2514,"count":0}],"isBlockCoverage":false},{"functionName":"hkdfDeriveBits","ranges":[{"startOffset":2553,"endOffset":3246,"count":0}],"isBlockCoverage":false}]},{"scriptId":"181","url":"node:internal/crypto/keys","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":21401,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2331,"endOffset":6452,"count":1}],"isBlockCoverage":true},{"functionName":"KeyObject","ranges":[{"startOffset":2441,"endOffset":2983,"count":45},{"startOffset":2497,"endOffset":2517,"count":27},{"startOffset":2518,"endOffset":2539,"count":13},{"startOffset":2549,"endOffset":2595,"count":0},{"startOffset":2682,"endOffset":2741,"count":0}],"isBlockCoverage":true},{"functionName":"get type","ranges":[{"startOffset":2989,"endOffset":3036,"count":51}],"isBlockCoverage":true},{"functionName":"from","ranges":[{"startOffset":3049,"endOffset":3190,"count":0}],"isBlockCoverage":false},{"functionName":"equals","ranges":[{"startOffset":3196,"endOffset":3480,"count":0}],"isBlockCoverage":false},{"functionName":"SecretKeyObject","ranges":[{"startOffset":3698,"endOffset":3756,"count":18}],"isBlockCoverage":true},{"functionName":"get symmetricKeySize","ranges":[{"startOffset":3762,"endOffset":3842,"count":0}],"isBlockCoverage":false},{"functionName":"export","ranges":[{"startOffset":3848,"endOffset":4196,"count":10},{"startOffset":3899,"endOffset":4153,"count":0}],"isBlockCoverage":true},{"functionName":"normalizeKeyDetails","ranges":[{"startOffset":4329,"endOffset":4598,"count":0}],"isBlockCoverage":false},{"functionName":"AsymmetricKeyObject","ranges":[{"startOffset":4707,"endOffset":4767,"count":27}],"isBlockCoverage":true},{"functionName":"get asymmetricKeyType","ranges":[{"startOffset":4773,"endOffset":4925,"count":11}],"isBlockCoverage":true},{"functionName":"get asymmetricKeyDetails","ranges":[{"startOffset":4931,"endOffset":5308,"count":0}],"isBlockCoverage":false},{"functionName":"PublicKeyObject","ranges":[{"startOffset":5372,"endOffset":5430,"count":14}],"isBlockCoverage":true},{"functionName":"export","ranges":[{"startOffset":5436,"endOffset":5727,"count":0}],"isBlockCoverage":false},{"functionName":"PrivateKeyObject","ranges":[{"startOffset":5792,"endOffset":5851,"count":13}],"isBlockCoverage":true},{"functionName":"export","ranges":[{"startOffset":5857,"endOffset":6371,"count":0}],"isBlockCoverage":false},{"functionName":"parseKeyFormat","ranges":[{"startOffset":6456,"endOffset":6841,"count":0}],"isBlockCoverage":false},{"functionName":"parseKeyType","ranges":[{"startOffset":6843,"endOffset":7695,"count":0}],"isBlockCoverage":false},{"functionName":"option","ranges":[{"startOffset":7697,"endOffset":7818,"count":0}],"isBlockCoverage":false},{"functionName":"parseKeyFormatAndType","ranges":[{"startOffset":7820,"endOffset":8520,"count":0}],"isBlockCoverage":false},{"functionName":"isStringOrBuffer","ranges":[{"startOffset":8522,"endOffset":8659,"count":0}],"isBlockCoverage":false},{"functionName":"parseKeyEncoding","ranges":[{"startOffset":8661,"endOffset":10019,"count":0}],"isBlockCoverage":false},{"functionName":"parsePublicKeyEncoding","ranges":[{"startOffset":10218,"endOffset":10354,"count":0}],"isBlockCoverage":false},{"functionName":"parsePrivateKeyEncoding","ranges":[{"startOffset":10554,"endOffset":10670,"count":0}],"isBlockCoverage":false},{"functionName":"getKeyObjectHandle","ranges":[{"startOffset":10672,"endOffset":11250,"count":0}],"isBlockCoverage":false},{"functionName":"getKeyTypes","ranges":[{"startOffset":11252,"endOffset":11757,"count":0}],"isBlockCoverage":false},{"functionName":"getKeyObjectHandleFromJwk","ranges":[{"startOffset":11759,"endOffset":14308,"count":0}],"isBlockCoverage":false},{"functionName":"prepareAsymmetricKey","ranges":[{"startOffset":14310,"endOffset":15853,"count":0}],"isBlockCoverage":false},{"functionName":"preparePrivateKey","ranges":[{"startOffset":15855,"endOffset":15943,"count":0}],"isBlockCoverage":false},{"functionName":"preparePublicOrPrivateKey","ranges":[{"startOffset":15945,"endOffset":16040,"count":0}],"isBlockCoverage":false},{"functionName":"prepareSecretKey","ranges":[{"startOffset":16042,"endOffset":16740,"count":17},{"startOffset":16124,"endOffset":16478,"count":0},{"startOffset":16542,"endOffset":16573,"count":8},{"startOffset":16575,"endOffset":16685,"count":0}],"isBlockCoverage":true},{"functionName":"createSecretKey","ranges":[{"startOffset":16742,"endOffset":16946,"count":17}],"isBlockCoverage":true},{"functionName":"createPublicKey","ranges":[{"startOffset":16948,"endOffset":17285,"count":0}],"isBlockCoverage":false},{"functionName":"createPrivateKey","ranges":[{"startOffset":17287,"endOffset":17628,"count":0}],"isBlockCoverage":false},{"functionName":"isKeyObject","ranges":[{"startOffset":17630,"endOffset":17712,"count":0}],"isBlockCoverage":false},{"functionName":"CryptoKey","ranges":[{"startOffset":18135,"endOffset":18195,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":18199,"endOffset":18548,"count":0}],"isBlockCoverage":false},{"functionName":"get type","ranges":[{"startOffset":18552,"endOffset":18687,"count":51},{"startOffset":18609,"endOffset":18649,"count":0}],"isBlockCoverage":true},{"functionName":"get extractable","ranges":[{"startOffset":18691,"endOffset":18830,"count":34},{"startOffset":18755,"endOffset":18795,"count":0}],"isBlockCoverage":true},{"functionName":"get algorithm","ranges":[{"startOffset":18834,"endOffset":18969,"count":4065},{"startOffset":18896,"endOffset":18936,"count":0}],"isBlockCoverage":true},{"functionName":"get usages","ranges":[{"startOffset":18973,"endOffset":19116,"count":2085},{"startOffset":19032,"endOffset":19072,"count":0}],"isBlockCoverage":true},{"functionName":"InternalCryptoKey","ranges":[{"startOffset":19694,"endOffset":20173,"count":45}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":20177,"endOffset":20529,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":20533,"endOffset":20737,"count":0}],"isBlockCoverage":false},{"functionName":"isCryptoKey","ranges":[{"startOffset":20866,"endOffset":20950,"count":0}],"isBlockCoverage":false}]},{"scriptId":"182","url":"node:internal/crypto/keygen","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":10712,"count":1}],"isBlockCoverage":false},{"functionName":"isJwk","ranges":[{"startOffset":1183,"endOffset":1253,"count":16}],"isBlockCoverage":true},{"functionName":"wrapKey","ranges":[{"startOffset":1255,"endOffset":1409,"count":16},{"startOffset":1372,"endOffset":1383,"count":0}],"isBlockCoverage":true},{"functionName":"generateKeyPair","ranges":[{"startOffset":1411,"endOffset":2047,"count":8},{"startOffset":1500,"endOffset":1554,"count":0}],"isBlockCoverage":true},{"functionName":"job.ondone","ranges":[{"startOffset":1671,"endOffset":2030,"count":8},{"startOffset":1707,"endOffset":1758,"count":0}],"isBlockCoverage":true},{"functionName":"generateKeyPairSync","ranges":[{"startOffset":2193,"endOffset":2310,"count":0}],"isBlockCoverage":false},{"functionName":"handleError","ranges":[{"startOffset":2312,"endOffset":2690,"count":0}],"isBlockCoverage":false},{"functionName":"parseKeyEncoding","ranges":[{"startOffset":2692,"endOffset":3942,"count":8},{"startOffset":2928,"endOffset":3286,"count":0},{"startOffset":3426,"endOffset":3825,"count":0}],"isBlockCoverage":true},{"functionName":"createJob","ranges":[{"startOffset":3944,"endOffset":9232,"count":8},{"startOffset":4187,"endOffset":4198,"count":4},{"startOffset":4203,"endOffset":6292,"count":4},{"startOffset":4445,"endOffset":4488,"count":0},{"startOffset":4802,"endOffset":6204,"count":0},{"startOffset":6232,"endOffset":6243,"count":0},{"startOffset":6297,"endOffset":6765,"count":0},{"startOffset":6770,"endOffset":7379,"count":4},{"startOffset":6994,"endOffset":7022,"count":0},{"startOffset":7071,"endOffset":7259,"count":0},{"startOffset":7384,"endOffset":7399,"count":0},{"startOffset":7404,"endOffset":7417,"count":0},{"startOffset":7422,"endOffset":7436,"count":0},{"startOffset":7441,"endOffset":7851,"count":0},{"startOffset":7856,"endOffset":9110,"count":0},{"startOffset":9115,"endOffset":9123,"count":0},{"startOffset":9149,"endOffset":9231,"count":0}],"isBlockCoverage":true},{"functionName":"generateKeyJob","ranges":[{"startOffset":9263,"endOffset":9800,"count":0}],"isBlockCoverage":false},{"functionName":"handleGenerateKeyError","ranges":[{"startOffset":9802,"endOffset":10004,"count":0}],"isBlockCoverage":false},{"functionName":"generateKey","ranges":[{"startOffset":10006,"endOffset":10476,"count":0}],"isBlockCoverage":false},{"functionName":"generateKeySync","ranges":[{"startOffset":10478,"endOffset":10612,"count":0}],"isBlockCoverage":false}]},{"scriptId":"183","url":"node:internal/crypto/diffiehellman","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":9910,"count":1}],"isBlockCoverage":false},{"functionName":"DiffieHellman","ranges":[{"startOffset":1232,"endOffset":3036,"count":0}],"isBlockCoverage":false},{"functionName":"DiffieHellmanGroup","ranges":[{"startOffset":3039,"endOffset":3365,"count":0}],"isBlockCoverage":false},{"functionName":"dhGenerateKeys","ranges":[{"startOffset":3476,"endOffset":3591,"count":0}],"isBlockCoverage":false},{"functionName":"dhComputeSecret","ranges":[{"startOffset":3705,"endOffset":3963,"count":0}],"isBlockCoverage":false},{"functionName":"dhGetPrime","ranges":[{"startOffset":4062,"endOffset":4171,"count":0}],"isBlockCoverage":false},{"functionName":"dhGetGenerator","ranges":[{"startOffset":4282,"endOffset":4407,"count":0}],"isBlockCoverage":false},{"functionName":"dhGetPublicKey","ranges":[{"startOffset":4518,"endOffset":4631,"count":0}],"isBlockCoverage":false},{"functionName":"dhGetPrivateKey","ranges":[{"startOffset":4745,"endOffset":4860,"count":0}],"isBlockCoverage":false},{"functionName":"setPublicKey","ranges":[{"startOffset":4902,"endOffset":5044,"count":0}],"isBlockCoverage":false},{"functionName":"setPrivateKey","ranges":[{"startOffset":5088,"endOffset":5232,"count":0}],"isBlockCoverage":false},{"functionName":"ECDH","ranges":[{"startOffset":5236,"endOffset":5390,"count":0}],"isBlockCoverage":false},{"functionName":"generateKeys","ranges":[{"startOffset":5701,"endOffset":5823,"count":0}],"isBlockCoverage":false},{"functionName":"getPublicKey","ranges":[{"startOffset":5856,"endOffset":6007,"count":0}],"isBlockCoverage":false},{"functionName":"convertKey","ranges":[{"startOffset":6028,"endOffset":6294,"count":0}],"isBlockCoverage":false},{"functionName":"encode","ranges":[{"startOffset":6297,"endOffset":6432,"count":0}],"isBlockCoverage":false},{"functionName":"getFormat","ranges":[{"startOffset":6434,"endOffset":6757,"count":0}],"isBlockCoverage":false},{"functionName":"diffieHellman","ranges":[{"startOffset":6831,"endOffset":7899,"count":0}],"isBlockCoverage":false},{"functionName":"ecdhDeriveBits","ranges":[{"startOffset":8018,"endOffset":9804,"count":0}],"isBlockCoverage":false}]},{"scriptId":"184","url":"node:internal/crypto/cipher","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":10199,"count":1}],"isBlockCoverage":false},{"functionName":"rsaFunctionFor","ranges":[{"startOffset":1233,"endOffset":1981,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1301,"endOffset":1978,"count":0}],"isBlockCoverage":false},{"functionName":"getDecoder","ranges":[{"startOffset":2482,"endOffset":2848,"count":0}],"isBlockCoverage":false},{"functionName":"getUIntOption","ranges":[{"startOffset":2850,"endOffset":3084,"count":0}],"isBlockCoverage":false},{"functionName":"createCipherBase","ranges":[{"startOffset":3086,"endOffset":3505,"count":0}],"isBlockCoverage":false},{"functionName":"createCipher","ranges":[{"startOffset":3507,"endOffset":3742,"count":0}],"isBlockCoverage":false},{"functionName":"createCipherWithIV","ranges":[{"startOffset":3744,"endOffset":4083,"count":0}],"isBlockCoverage":false},{"functionName":"Cipher","ranges":[{"startOffset":4326,"endOffset":4527,"count":0}],"isBlockCoverage":false},{"functionName":"_transform","ranges":[{"startOffset":4670,"endOffset":4786,"count":0}],"isBlockCoverage":false},{"functionName":"_flush","ranges":[{"startOffset":4815,"endOffset":4953,"count":0}],"isBlockCoverage":false},{"functionName":"update","ranges":[{"startOffset":4982,"endOffset":5498,"count":0}],"isBlockCoverage":false},{"functionName":"final","ranges":[{"startOffset":5527,"endOffset":5771,"count":0}],"isBlockCoverage":false},{"functionName":"setAutoPadding","ranges":[{"startOffset":5809,"endOffset":5956,"count":0}],"isBlockCoverage":false},{"functionName":"getAuthTag","ranges":[{"startOffset":5989,"endOffset":6149,"count":0}],"isBlockCoverage":false},{"functionName":"setAuthTag","ranges":[{"startOffset":6153,"endOffset":6365,"count":0}],"isBlockCoverage":false},{"functionName":"setAAD","ranges":[{"startOffset":6393,"endOffset":6735,"count":0}],"isBlockCoverage":false},{"functionName":"Cipheriv","ranges":[{"startOffset":6983,"endOffset":7193,"count":0}],"isBlockCoverage":false},{"functionName":"addCipherPrototypeFunctions","ranges":[{"startOffset":7195,"endOffset":7786,"count":3},{"startOffset":7591,"endOffset":7664,"count":1},{"startOffset":7664,"endOffset":7726,"count":2}],"isBlockCoverage":true},{"functionName":"Decipher","ranges":[{"startOffset":8187,"endOffset":8395,"count":0}],"isBlockCoverage":false},{"functionName":"Decipheriv","ranges":[{"startOffset":8800,"endOffset":9017,"count":0}],"isBlockCoverage":false},{"functionName":"getCipherInfo","ranges":[{"startOffset":9179,"endOffset":10040,"count":0}],"isBlockCoverage":false}]},{"scriptId":"185","url":"node:internal/streams/lazy_transform","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1535,"count":1}],"isBlockCoverage":false},{"functionName":"LazyTransform","ranges":[{"startOffset":401,"endOffset":463,"count":20000}],"isBlockCoverage":true},{"functionName":"makeGetter","ranges":[{"startOffset":595,"endOffset":918,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":632,"endOffset":915,"count":0}],"isBlockCoverage":false},{"functionName":"makeSetter","ranges":[{"startOffset":920,"endOffset":1139,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":957,"endOffset":1136,"count":0}],"isBlockCoverage":false}]},{"scriptId":"186","url":"node:stream","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4792,"count":1}],"isBlockCoverage":false},{"functionName":"fn","ranges":[{"startOffset":2402,"endOffset":2562,"count":0}],"isBlockCoverage":false},{"functionName":"fn","ranges":[{"startOffset":2987,"endOffset":3125,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4113,"endOffset":4145,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4243,"endOffset":4284,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4377,"endOffset":4418,"count":0}],"isBlockCoverage":false},{"functionName":"_uint8ArrayToBuffer","ranges":[{"startOffset":4583,"endOffset":4790,"count":0}],"isBlockCoverage":false}]},{"scriptId":"187","url":"node:internal/streams/operators","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":10772,"count":1}],"isBlockCoverage":false},{"functionName":"compose","ranges":[{"startOffset":1019,"endOffset":1599,"count":0}],"isBlockCoverage":false},{"functionName":"map","ranges":[{"startOffset":1601,"endOffset":4704,"count":0}],"isBlockCoverage":false},{"functionName":"asIndexedPairs","ranges":[{"startOffset":4706,"endOffset":5179,"count":0}],"isBlockCoverage":false},{"functionName":"some","ranges":[{"startOffset":5181,"endOffset":5329,"count":0}],"isBlockCoverage":false},{"functionName":"every","ranges":[{"startOffset":5331,"endOffset":5659,"count":0}],"isBlockCoverage":false},{"functionName":"find","ranges":[{"startOffset":5661,"endOffset":5803,"count":0}],"isBlockCoverage":false},{"functionName":"forEach","ranges":[{"startOffset":5805,"endOffset":6175,"count":0}],"isBlockCoverage":false},{"functionName":"filter","ranges":[{"startOffset":6177,"endOffset":6504,"count":0}],"isBlockCoverage":false},{"functionName":"ReduceAwareErrMissingArgs","ranges":[{"startOffset":6720,"endOffset":6834,"count":0}],"isBlockCoverage":false},{"functionName":"reduce","ranges":[{"startOffset":6838,"endOffset":8280,"count":0}],"isBlockCoverage":false},{"functionName":"toArray","ranges":[{"startOffset":8282,"endOffset":8711,"count":0}],"isBlockCoverage":false},{"functionName":"flatMap","ranges":[{"startOffset":8713,"endOffset":8907,"count":0}],"isBlockCoverage":false},{"functionName":"toIntegerOrInfinity","ranges":[{"startOffset":8909,"endOffset":9231,"count":0}],"isBlockCoverage":false},{"functionName":"drop","ranges":[{"startOffset":9233,"endOffset":9781,"count":0}],"isBlockCoverage":false},{"functionName":"take","ranges":[{"startOffset":9783,"endOffset":10453,"count":0}],"isBlockCoverage":false}]},{"scriptId":"188","url":"node:internal/abort_controller","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":12472,"count":1}],"isBlockCoverage":false},{"functionName":"lazyMessageChannel","ranges":[{"startOffset":1635,"endOffset":1768,"count":0}],"isBlockCoverage":false},{"functionName":"lazyMakeTransferable","ranges":[{"startOffset":1770,"endOffset":1928,"count":0}],"isBlockCoverage":false},{"functionName":"customInspect","ranges":[{"startOffset":2398,"endOffset":2657,"count":0}],"isBlockCoverage":false},{"functionName":"validateThisAbortSignal","ranges":[{"startOffset":2659,"endOffset":2784,"count":0}],"isBlockCoverage":false},{"functionName":"setWeakAbortSignalTimeout","ranges":[{"startOffset":3366,"endOffset":3766,"count":0}],"isBlockCoverage":false},{"functionName":"AbortSignal","ranges":[{"startOffset":3810,"endOffset":3870,"count":0}],"isBlockCoverage":false},{"functionName":"get aborted","ranges":[{"startOffset":3907,"endOffset":3990,"count":0}],"isBlockCoverage":false},{"functionName":"get reason","ranges":[{"startOffset":4023,"endOffset":4102,"count":0}],"isBlockCoverage":false},{"functionName":"throwIfAborted","ranges":[{"startOffset":4106,"endOffset":4222,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":4226,"endOffset":4355,"count":0}],"isBlockCoverage":false},{"functionName":"abort","ranges":[{"startOffset":4433,"endOffset":4577,"count":0}],"isBlockCoverage":false},{"functionName":"timeout","ranges":[{"startOffset":4655,"endOffset":4917,"count":0}],"isBlockCoverage":false},{"functionName":"any","ranges":[{"startOffset":5004,"endOffset":6339,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":6343,"endOffset":7111,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":7115,"endOffset":7469,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":7473,"endOffset":8080,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":8084,"endOffset":8336,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":8340,"endOffset":8788,"count":0}],"isBlockCoverage":false},{"functionName":"ClonedAbortSignal","ranges":[{"startOffset":8792,"endOffset":8876,"count":0}],"isBlockCoverage":false},{"functionName":"ClonedAbortSignal.","ranges":[{"startOffset":8921,"endOffset":8929,"count":0}],"isBlockCoverage":false},{"functionName":"createAbortSignal","ranges":[{"startOffset":9407,"endOffset":9820,"count":0}],"isBlockCoverage":false},{"functionName":"abortSignal","ranges":[{"startOffset":9822,"endOffset":10184,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10186,"endOffset":10842,"count":0}],"isBlockCoverage":false},{"functionName":"transferableAbortSignal","ranges":[{"startOffset":10990,"endOffset":11182,"count":0}],"isBlockCoverage":false},{"functionName":"transferableAbortController","ranges":[{"startOffset":11254,"endOffset":11343,"count":0}],"isBlockCoverage":false},{"functionName":"aborted","ranges":[{"startOffset":11437,"endOffset":12023,"count":0}],"isBlockCoverage":false}]},{"scriptId":"189","url":"node:internal/streams/end-of-stream","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8360,"count":1}],"isBlockCoverage":false},{"functionName":"isRequest","ranges":[{"startOffset":891,"endOffset":986,"count":0}],"isBlockCoverage":false},{"functionName":"nop","ranges":[{"startOffset":1000,"endOffset":1008,"count":0}],"isBlockCoverage":false},{"functionName":"eos","ranges":[{"startOffset":1011,"endOffset":6953,"count":0}],"isBlockCoverage":false},{"functionName":"eosWeb","ranges":[{"startOffset":6955,"endOffset":7840,"count":0}],"isBlockCoverage":false},{"functionName":"finished","ranges":[{"startOffset":7842,"endOffset":8300,"count":0}],"isBlockCoverage":false}]},{"scriptId":"190","url":"node:internal/streams/compose","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":5451,"count":1}],"isBlockCoverage":false},{"functionName":"compose","ranges":[{"startOffset":543,"endOffset":5449,"count":0}],"isBlockCoverage":false}]},{"scriptId":"191","url":"node:internal/streams/pipeline","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":12326,"count":1}],"isBlockCoverage":false},{"functionName":"destroyer","ranges":[{"startOffset":1058,"endOffset":1487,"count":0}],"isBlockCoverage":false},{"functionName":"popCallback","ranges":[{"startOffset":1489,"endOffset":1817,"count":0}],"isBlockCoverage":false},{"functionName":"makeAsyncIterable","ranges":[{"startOffset":1819,"endOffset":2105,"count":0}],"isBlockCoverage":false},{"functionName":"fromReadable","ranges":[{"startOffset":2107,"endOffset":2281,"count":0}],"isBlockCoverage":false},{"functionName":"pumpToNode","ranges":[{"startOffset":2283,"endOffset":3327,"count":0}],"isBlockCoverage":false},{"functionName":"pumpToWeb","ranges":[{"startOffset":3329,"endOffset":3927,"count":0}],"isBlockCoverage":false},{"functionName":"pipeline","ranges":[{"startOffset":3929,"endOffset":4022,"count":0}],"isBlockCoverage":false},{"functionName":"pipelineImpl","ranges":[{"startOffset":4024,"endOffset":10476,"count":0}],"isBlockCoverage":false},{"functionName":"pipe","ranges":[{"startOffset":10478,"endOffset":12279,"count":0}],"isBlockCoverage":false}]},{"scriptId":"192","url":"node:internal/streams/destroy","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7437,"count":1}],"isBlockCoverage":false},{"functionName":"checkError","ranges":[{"startOffset":487,"endOffset":798,"count":0}],"isBlockCoverage":false},{"functionName":"destroy","ranges":[{"startOffset":908,"endOffset":1785,"count":0}],"isBlockCoverage":false},{"functionName":"_destroy","ranges":[{"startOffset":1787,"endOffset":2411,"count":0}],"isBlockCoverage":false},{"functionName":"emitErrorCloseNT","ranges":[{"startOffset":2413,"endOffset":2500,"count":0}],"isBlockCoverage":false},{"functionName":"emitCloseNT","ranges":[{"startOffset":2502,"endOffset":2822,"count":0}],"isBlockCoverage":false},{"functionName":"emitErrorNT","ranges":[{"startOffset":2824,"endOffset":3171,"count":0}],"isBlockCoverage":false},{"functionName":"undestroy","ranges":[{"startOffset":3173,"endOffset":3863,"count":2}],"isBlockCoverage":true},{"functionName":"errorOrDestroy","ranges":[{"startOffset":3865,"endOffset":5004,"count":0}],"isBlockCoverage":false},{"functionName":"construct","ranges":[{"startOffset":5006,"endOffset":5422,"count":0}],"isBlockCoverage":false},{"functionName":"constructNT","ranges":[{"startOffset":5424,"endOffset":6181,"count":0}],"isBlockCoverage":false},{"functionName":"emitConstructNT","ranges":[{"startOffset":6183,"endOffset":6246,"count":0}],"isBlockCoverage":false},{"functionName":"isRequest","ranges":[{"startOffset":6248,"endOffset":6344,"count":0}],"isBlockCoverage":false},{"functionName":"emitCloseLegacy","ranges":[{"startOffset":6346,"endOffset":6406,"count":0}],"isBlockCoverage":false},{"functionName":"emitErrorCloseLegacy","ranges":[{"startOffset":6408,"endOffset":6528,"count":0}],"isBlockCoverage":false},{"functionName":"destroyer","ranges":[{"startOffset":6563,"endOffset":7345,"count":0}],"isBlockCoverage":false}]},{"scriptId":"193","url":"node:internal/streams/duplex","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6489,"count":1}],"isBlockCoverage":false},{"functionName":"Duplex","ranges":[{"startOffset":2251,"endOffset":4214,"count":2},{"startOffset":2315,"endOffset":2342,"count":0},{"startOffset":3203,"endOffset":3378,"count":0},{"startOffset":3430,"endOffset":3456,"count":0},{"startOffset":3509,"endOffset":3537,"count":0},{"startOffset":3591,"endOffset":3621,"count":0},{"startOffset":3676,"endOffset":3708,"count":0},{"startOffset":3761,"endOffset":3789,"count":0},{"startOffset":3846,"endOffset":3882,"count":0},{"startOffset":3914,"endOffset":3951,"count":0},{"startOffset":3955,"endOffset":3997,"count":0},{"startOffset":4061,"endOffset":4212,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4095,"endOffset":4206,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":5362,"endOffset":5574,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":5580,"endOffset":5841,"count":0}],"isBlockCoverage":false},{"functionName":"lazyWebStreams","ranges":[{"startOffset":5915,"endOffset":6079,"count":0}],"isBlockCoverage":false},{"functionName":"Duplex.fromWeb","ranges":[{"startOffset":6098,"endOffset":6216,"count":0}],"isBlockCoverage":false},{"functionName":"Duplex.toWeb","ranges":[{"startOffset":6234,"endOffset":6323,"count":0}],"isBlockCoverage":false},{"functionName":"Duplex.from","ranges":[{"startOffset":6356,"endOffset":6487,"count":0}],"isBlockCoverage":false}]},{"scriptId":"194","url":"node:internal/streams/legacy","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2934,"count":1}],"isBlockCoverage":false},{"functionName":"Stream","ranges":[{"startOffset":112,"endOffset":160,"count":2}],"isBlockCoverage":true},{"functionName":"Stream.pipe","ranges":[{"startOffset":274,"endOffset":2076,"count":0}],"isBlockCoverage":false},{"functionName":"prependListener","ranges":[{"startOffset":2079,"endOffset":2886,"count":0}],"isBlockCoverage":false}]},{"scriptId":"195","url":"node:internal/streams/readable","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":51291,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1842,"endOffset":1867,"count":0}],"isBlockCoverage":false},{"functionName":"nop","ranges":[{"startOffset":2829,"endOffset":2837,"count":0}],"isBlockCoverage":false},{"functionName":"makeBitMapDescriptor","ranges":[{"startOffset":3733,"endOffset":3955,"count":19}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":3808,"endOffset":3852,"count":2}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":3858,"endOffset":3947,"count":20},{"startOffset":3888,"endOffset":3941,"count":10}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":6129,"endOffset":6217,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":6223,"endOffset":6389,"count":2},{"startOffset":6253,"endOffset":6333,"count":0}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":6466,"endOffset":6566,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":6572,"endOffset":6802,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":6871,"endOffset":6959,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":6965,"endOffset":7131,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":7201,"endOffset":7291,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":7297,"endOffset":7466,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":7535,"endOffset":7638,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":7644,"endOffset":7911,"count":0}],"isBlockCoverage":false},{"functionName":"ReadableState","ranges":[{"startOffset":7924,"endOffset":9919,"count":2},{"startOffset":8323,"endOffset":8351,"count":0},{"startOffset":8414,"endOffset":8442,"count":0},{"startOffset":8690,"endOffset":8726,"count":0},{"startOffset":9068,"endOffset":9098,"count":0},{"startOffset":9377,"endOffset":9406,"count":0},{"startOffset":9407,"endOffset":9437,"count":0},{"startOffset":9486,"endOffset":9645,"count":0},{"startOffset":9818,"endOffset":9917,"count":0}],"isBlockCoverage":true},{"functionName":"onConstructed","ranges":[{"startOffset":9963,"endOffset":10080,"count":0}],"isBlockCoverage":false},{"functionName":"Readable","ranges":[{"startOffset":10083,"endOffset":11117,"count":0}],"isBlockCoverage":true},{"functionName":"Readable._destroy","ranges":[{"startOffset":11254,"endOffset":11286,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.","ranges":[{"startOffset":11337,"endOffset":11375,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.","ranges":[{"startOffset":11419,"endOffset":11675,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.push","ranges":[{"startOffset":11904,"endOffset":12173,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.unshift","ranges":[{"startOffset":12269,"endOffset":12536,"count":0}],"isBlockCoverage":false},{"functionName":"readableAddChunkUnshiftByteMode","ranges":[{"startOffset":12540,"endOffset":13589,"count":0}],"isBlockCoverage":false},{"functionName":"readableAddChunkUnshiftObjectMode","ranges":[{"startOffset":13591,"endOffset":13831,"count":0}],"isBlockCoverage":false},{"functionName":"readableAddChunkUnshiftValue","ranges":[{"startOffset":13833,"endOffset":14166,"count":0}],"isBlockCoverage":false},{"functionName":"readableAddChunkPushByteMode","ranges":[{"startOffset":14168,"endOffset":15543,"count":0}],"isBlockCoverage":false},{"functionName":"readableAddChunkPushObjectMode","ranges":[{"startOffset":15545,"endOffset":16142,"count":0}],"isBlockCoverage":false},{"functionName":"canPushMore","ranges":[{"startOffset":16144,"endOffset":16474,"count":0}],"isBlockCoverage":false},{"functionName":"addChunk","ranges":[{"startOffset":16476,"endOffset":17420,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.isPaused","ranges":[{"startOffset":17452,"endOffset":17607,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.setEncoding","ranges":[{"startOffset":17671,"endOffset":18241,"count":0}],"isBlockCoverage":false},{"functionName":"computeNewHighWaterMark","ranges":[{"startOffset":18302,"endOffset":18653,"count":0}],"isBlockCoverage":false},{"functionName":"howMuchToRead","ranges":[{"startOffset":18766,"endOffset":19247,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.read","ranges":[{"startOffset":19344,"endOffset":24019,"count":0}],"isBlockCoverage":false},{"functionName":"onEofChunk","ranges":[{"startOffset":24022,"endOffset":24984,"count":0}],"isBlockCoverage":false},{"functionName":"emitReadable","ranges":[{"startOffset":25185,"endOffset":25516,"count":0}],"isBlockCoverage":false},{"functionName":"emitReadable_","ranges":[{"startOffset":25518,"endOffset":26190,"count":0}],"isBlockCoverage":false},{"functionName":"maybeReadMore","ranges":[{"startOffset":26540,"endOffset":26747,"count":0}],"isBlockCoverage":false},{"functionName":"maybeReadMore_","ranges":[{"startOffset":26749,"endOffset":28578,"count":0}],"isBlockCoverage":false},{"functionName":"Readable._read","ranges":[{"startOffset":28849,"endOffset":28915,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.pipe","ranges":[{"startOffset":28944,"endOffset":33454,"count":0}],"isBlockCoverage":false},{"functionName":"pipeOnDrain","ranges":[{"startOffset":33457,"endOffset":34134,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.unpipe","ranges":[{"startOffset":34165,"endOffset":34866,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.on","ranges":[{"startOffset":34992,"endOffset":36001,"count":560},{"startOffset":35124,"endOffset":35553,"count":0},{"startOffset":35582,"endOffset":35984,"count":0}],"isBlockCoverage":true},{"functionName":"Readable.removeListener","ranges":[{"startOffset":36096,"endOffset":36803,"count":558},{"startOffset":36296,"endOffset":36682,"count":0},{"startOffset":36706,"endOffset":36741,"count":0},{"startOffset":36743,"endOffset":36786,"count":0}],"isBlockCoverage":true},{"functionName":"Readable.removeAllListeners","ranges":[{"startOffset":36906,"endOffset":37500,"count":0}],"isBlockCoverage":false},{"functionName":"updateReadableListening","ranges":[{"startOffset":37503,"endOffset":38205,"count":0}],"isBlockCoverage":false},{"functionName":"nReadingNextTick","ranges":[{"startOffset":38207,"endOffset":38295,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.resume","ranges":[{"startOffset":38449,"endOffset":38954,"count":0}],"isBlockCoverage":false},{"functionName":"resume","ranges":[{"startOffset":38957,"endOffset":39130,"count":0}],"isBlockCoverage":false},{"functionName":"resume_","ranges":[{"startOffset":39132,"endOffset":39446,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.pause","ranges":[{"startOffset":39475,"endOffset":39787,"count":0}],"isBlockCoverage":false},{"functionName":"flow","ranges":[{"startOffset":39790,"endOffset":39941,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.wrap","ranges":[{"startOffset":40125,"endOffset":41146,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.","ranges":[{"startOffset":41191,"endOffset":41243,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.iterator","ranges":[{"startOffset":41276,"endOffset":41419,"count":0}],"isBlockCoverage":false},{"functionName":"streamToAsyncIterator","ranges":[{"startOffset":41422,"endOffset":41671,"count":0}],"isBlockCoverage":false},{"functionName":"createAsyncIterator","ranges":[{"startOffset":41673,"endOffset":42749,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":42968,"endOffset":43357,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":43363,"endOffset":43493,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":43575,"endOffset":43639,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":43721,"endOffset":43929,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":44017,"endOffset":44083,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":44164,"endOffset":44246,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":44328,"endOffset":44388,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":44399,"endOffset":44508,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":44584,"endOffset":44638,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":44718,"endOffset":44806,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":44884,"endOffset":44969,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":45038,"endOffset":45122,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":45167,"endOffset":45251,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":45322,"endOffset":45409,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":45415,"endOffset":45704,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":45779,"endOffset":45867,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":46008,"endOffset":46053,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":46133,"endOffset":46191,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":46197,"endOffset":46358,"count":0}],"isBlockCoverage":false},{"functionName":"fromList","ranges":[{"startOffset":46664,"endOffset":49116,"count":0}],"isBlockCoverage":false},{"functionName":"endReadable","ranges":[{"startOffset":49118,"endOffset":49344,"count":0}],"isBlockCoverage":false},{"functionName":"endReadableNT","ranges":[{"startOffset":49346,"endOffset":50239,"count":0}],"isBlockCoverage":false},{"functionName":"endWritableNT","ranges":[{"startOffset":50241,"endOffset":50401,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.from","ranges":[{"startOffset":50419,"endOffset":50488,"count":0}],"isBlockCoverage":false},{"functionName":"lazyWebStreams","ranges":[{"startOffset":50553,"endOffset":50717,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.fromWeb","ranges":[{"startOffset":50738,"endOffset":50872,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.toWeb","ranges":[{"startOffset":50892,"endOffset":51026,"count":0}],"isBlockCoverage":false},{"functionName":"Readable.wrap","ranges":[{"startOffset":51045,"endOffset":51289,"count":0}],"isBlockCoverage":false}]},{"scriptId":"196","url":"node:internal/streams/add-abort-signal","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1704,"count":1}],"isBlockCoverage":false},{"functionName":"validateAbortSignal","ranges":[{"startOffset":557,"endOffset":716,"count":0}],"isBlockCoverage":false},{"functionName":"addAbortSignal","ranges":[{"startOffset":751,"endOffset":1062,"count":0}],"isBlockCoverage":false},{"functionName":"module.exports.addAbortSignalNoValidate","ranges":[{"startOffset":1107,"endOffset":1702,"count":0}],"isBlockCoverage":false}]},{"scriptId":"197","url":"node:internal/streams/state","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1332,"count":1}],"isBlockCoverage":false},{"functionName":"highWaterMarkFrom","ranges":[{"startOffset":287,"endOffset":454,"count":4},{"startOffset":385,"endOffset":408,"count":0},{"startOffset":445,"endOffset":451,"count":0}],"isBlockCoverage":true},{"functionName":"getDefaultHighWaterMark","ranges":[{"startOffset":456,"endOffset":586,"count":4},{"startOffset":523,"endOffset":555,"count":0}],"isBlockCoverage":true},{"functionName":"setDefaultHighWaterMark","ranges":[{"startOffset":588,"endOffset":799,"count":0}],"isBlockCoverage":false},{"functionName":"getHighWaterMark","ranges":[{"startOffset":801,"endOffset":1234,"count":4},{"startOffset":948,"endOffset":1160,"count":0}],"isBlockCoverage":true}]},{"scriptId":"198","url":"node:internal/streams/from","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4341,"count":1}],"isBlockCoverage":false},{"functionName":"from","ranges":[{"startOffset":241,"endOffset":4316,"count":0}],"isBlockCoverage":false}]},{"scriptId":"199","url":"node:internal/streams/writable","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":33049,"count":1}],"isBlockCoverage":false},{"functionName":"nop","ranges":[{"startOffset":2611,"endOffset":2628,"count":0}],"isBlockCoverage":false},{"functionName":"makeBitMapDescriptor","ranges":[{"startOffset":3684,"endOffset":3906,"count":20}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":3759,"endOffset":3803,"count":2}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":3809,"endOffset":3898,"count":20},{"startOffset":3839,"endOffset":3859,"count":2},{"startOffset":3859,"endOffset":3892,"count":18}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":6870,"endOffset":6948,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":6954,"endOffset":7120,"count":2},{"startOffset":6984,"endOffset":7064,"count":0}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":7190,"endOffset":7290,"count":6},{"startOffset":7241,"endOffset":7275,"count":0}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":7296,"endOffset":7569,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":7646,"endOffset":7746,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":7752,"endOffset":7982,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":8123,"endOffset":8200,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":8206,"endOffset":8372,"count":558},{"startOffset":8316,"endOffset":8366,"count":0}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":8559,"endOffset":8659,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":8665,"endOffset":8864,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":8934,"endOffset":9012,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":9018,"endOffset":9185,"count":0}],"isBlockCoverage":false},{"functionName":"WritableState","ranges":[{"startOffset":9198,"endOffset":11499,"count":2},{"startOffset":9475,"endOffset":9503,"count":0},{"startOffset":9566,"endOffset":9594,"count":0},{"startOffset":9885,"endOffset":9921,"count":0},{"startOffset":9975,"endOffset":10006,"count":0},{"startOffset":10264,"endOffset":10294,"count":0},{"startOffset":10551,"endOffset":10557,"count":0},{"startOffset":10589,"endOffset":10618,"count":0},{"startOffset":10619,"endOffset":10649,"count":0},{"startOffset":10698,"endOffset":10907,"count":0}],"isBlockCoverage":true},{"functionName":"resetBuffer","ranges":[{"startOffset":11501,"endOffset":11665,"count":2}],"isBlockCoverage":true},{"functionName":"getBuffer","ranges":[{"startOffset":11703,"endOffset":11832,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":11928,"endOffset":12039,"count":0}],"isBlockCoverage":false},{"functionName":"onConstructed","ranges":[{"startOffset":12088,"endOffset":12274,"count":0}],"isBlockCoverage":false},{"functionName":"Writable","ranges":[{"startOffset":12277,"endOffset":13383,"count":0}],"isBlockCoverage":false},{"functionName":"value","ranges":[{"startOffset":13465,"endOffset":13669,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.pipe","ranges":[{"startOffset":13770,"endOffset":13838,"count":0}],"isBlockCoverage":false},{"functionName":"_write","ranges":[{"startOffset":13841,"endOffset":15222,"count":558},{"startOffset":13974,"endOffset":13993,"count":0},{"startOffset":14017,"endOffset":14062,"count":0},{"startOffset":14201,"endOffset":14224,"count":0},{"startOffset":14231,"endOffset":14351,"count":0},{"startOffset":14440,"endOffset":14524,"count":0},{"startOffset":14530,"endOffset":14833,"count":0},{"startOffset":14889,"endOffset":14938,"count":0},{"startOffset":14984,"endOffset":15034,"count":0},{"startOffset":15047,"endOffset":15138,"count":0}],"isBlockCoverage":true},{"functionName":"Writable.write","ranges":[{"startOffset":15251,"endOffset":15442,"count":558}],"isBlockCoverage":true},{"functionName":"Writable.cork","ranges":[{"startOffset":15471,"endOffset":15569,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.uncork","ranges":[{"startOffset":15600,"endOffset":15838,"count":0}],"isBlockCoverage":false},{"functionName":"setDefaultEncoding","ranges":[{"startOffset":15881,"endOffset":16206,"count":0}],"isBlockCoverage":false},{"functionName":"writeOrBuffer","ranges":[{"startOffset":16396,"endOffset":17578,"count":558},{"startOffset":16513,"endOffset":16516,"count":0},{"startOffset":16647,"endOffset":17054,"count":0},{"startOffset":17358,"endOffset":17396,"count":0}],"isBlockCoverage":true},{"functionName":"doWrite","ranges":[{"startOffset":17580,"endOffset":18017,"count":0}],"isBlockCoverage":false},{"functionName":"onwriteError","ranges":[{"startOffset":18019,"endOffset":18404,"count":0}],"isBlockCoverage":false},{"functionName":"onwrite","ranges":[{"startOffset":18406,"endOffset":20999,"count":558},{"startOffset":18523,"endOffset":18597,"count":0},{"startOffset":18714,"endOffset":18719,"count":0},{"startOffset":18849,"endOffset":19463,"count":0},{"startOffset":19514,"endOffset":19555,"count":0},{"startOffset":19632,"endOffset":19653,"count":0},{"startOffset":20017,"endOffset":20368,"count":0},{"startOffset":20422,"endOffset":20483,"count":525},{"startOffset":20485,"endOffset":20543,"count":525},{"startOffset":20543,"endOffset":20934,"count":33},{"startOffset":20791,"endOffset":20934,"count":0},{"startOffset":20940,"endOffset":20993,"count":0}],"isBlockCoverage":true},{"functionName":"afterWriteTick","ranges":[{"startOffset":21001,"endOffset":21188,"count":32}],"isBlockCoverage":true},{"functionName":"afterWrite","ranges":[{"startOffset":21190,"endOffset":21698,"count":32},{"startOffset":21368,"endOffset":21389,"count":0},{"startOffset":21408,"endOffset":21473,"count":0},{"startOffset":21497,"endOffset":21539,"count":554},{"startOffset":21583,"endOffset":21612,"count":0},{"startOffset":21653,"endOffset":21696,"count":0}],"isBlockCoverage":true},{"functionName":"errorBuffer","ranges":[{"startOffset":21770,"endOffset":22321,"count":0}],"isBlockCoverage":false},{"functionName":"clearBuffer","ranges":[{"startOffset":22387,"endOffset":24019,"count":0}],"isBlockCoverage":false},{"functionName":"Writable._write","ranges":[{"startOffset":24049,"endOffset":24218,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.end","ranges":[{"startOffset":24282,"endOffset":25922,"count":0}],"isBlockCoverage":false},{"functionName":"needFinish","ranges":[{"startOffset":25925,"endOffset":26354,"count":0}],"isBlockCoverage":false},{"functionName":"onFinish","ranges":[{"startOffset":26356,"endOffset":26984,"count":0}],"isBlockCoverage":false},{"functionName":"prefinish","ranges":[{"startOffset":26986,"endOffset":27510,"count":0}],"isBlockCoverage":false},{"functionName":"finishMaybe","ranges":[{"startOffset":27512,"endOffset":28011,"count":0}],"isBlockCoverage":false},{"functionName":"finish","ranges":[{"startOffset":28013,"endOffset":28656,"count":0}],"isBlockCoverage":false},{"functionName":"callFinishedCallbacks","ranges":[{"startOffset":28658,"endOffset":28976,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":29060,"endOffset":29163,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":29211,"endOffset":29317,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":29323,"endOffset":29573,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":29620,"endOffset":30026,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":30032,"endOffset":30166,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":30221,"endOffset":30339,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":30396,"endOffset":30516,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":30569,"endOffset":30664,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":30716,"endOffset":30832,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":30888,"endOffset":31041,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":31101,"endOffset":31198,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":31251,"endOffset":31344,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":31397,"endOffset":31487,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":31556,"endOffset":31653,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":31712,"endOffset":31969,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.destroy","ranges":[{"startOffset":32047,"endOffset":32327,"count":0}],"isBlockCoverage":false},{"functionName":"Writable._destroy","ranges":[{"startOffset":32415,"endOffset":32447,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.","ranges":[{"startOffset":32498,"endOffset":32536,"count":0}],"isBlockCoverage":false},{"functionName":"lazyWebStreams","ranges":[{"startOffset":32601,"endOffset":32765,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.fromWeb","ranges":[{"startOffset":32786,"endOffset":32920,"count":0}],"isBlockCoverage":false},{"functionName":"Writable.toWeb","ranges":[{"startOffset":32940,"endOffset":33047,"count":0}],"isBlockCoverage":false}]},{"scriptId":"200","url":"node:stream/promises","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":917,"count":1}],"isBlockCoverage":false},{"functionName":"pipeline","ranges":[{"startOffset":318,"endOffset":869,"count":0}],"isBlockCoverage":false}]},{"scriptId":"201","url":"node:internal/streams/transform","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7121,"count":1}],"isBlockCoverage":false},{"functionName":"Transform","ranges":[{"startOffset":3920,"endOffset":5500,"count":0}],"isBlockCoverage":true},{"functionName":"final","ranges":[{"startOffset":5502,"endOffset":5946,"count":0}],"isBlockCoverage":false},{"functionName":"prefinish","ranges":[{"startOffset":5948,"endOffset":6029,"count":0}],"isBlockCoverage":false},{"functionName":"Transform._transform","ranges":[{"startOffset":6101,"endOffset":6196,"count":0}],"isBlockCoverage":false},{"functionName":"Transform._write","ranges":[{"startOffset":6228,"endOffset":6963,"count":0}],"isBlockCoverage":false},{"functionName":"Transform._read","ranges":[{"startOffset":6994,"endOffset":7119,"count":0}],"isBlockCoverage":false}]},{"scriptId":"202","url":"node:internal/streams/passthrough","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1762,"count":1}],"isBlockCoverage":false},{"functionName":"PassThrough","ranges":[{"startOffset":1529,"endOffset":1671,"count":0}],"isBlockCoverage":false},{"functionName":"PassThrough._transform","ranges":[{"startOffset":1708,"endOffset":1760,"count":0}],"isBlockCoverage":false}]},{"scriptId":"203","url":"node:internal/crypto/sig","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6942,"count":1}],"isBlockCoverage":false},{"functionName":"Sign","ranges":[{"startOffset":870,"endOffset":1129,"count":0}],"isBlockCoverage":false},{"functionName":"_write","ranges":[{"startOffset":1252,"endOffset":1344,"count":0}],"isBlockCoverage":false},{"functionName":"update","ranges":[{"startOffset":1371,"endOffset":1684,"count":0}],"isBlockCoverage":false},{"functionName":"getPadding","ranges":[{"startOffset":1687,"endOffset":1762,"count":0}],"isBlockCoverage":false},{"functionName":"getSaltLength","ranges":[{"startOffset":1764,"endOffset":1845,"count":0}],"isBlockCoverage":false},{"functionName":"getDSASignatureEncoding","ranges":[{"startOffset":1847,"endOffset":2199,"count":0}],"isBlockCoverage":false},{"functionName":"getIntOption","ranges":[{"startOffset":2201,"endOffset":2446,"count":0}],"isBlockCoverage":false},{"functionName":"sign","ranges":[{"startOffset":2470,"endOffset":3086,"count":0}],"isBlockCoverage":false},{"functionName":"signOneShot","ranges":[{"startOffset":3089,"endOffset":4307,"count":0}],"isBlockCoverage":false},{"functionName":"Verify","ranges":[{"startOffset":4309,"endOffset":4576,"count":0}],"isBlockCoverage":false},{"functionName":"verify","ranges":[{"startOffset":4804,"endOffset":5387,"count":0}],"isBlockCoverage":false},{"functionName":"verifyOneShot","ranges":[{"startOffset":5390,"endOffset":6868,"count":0}],"isBlockCoverage":false}]},{"scriptId":"204","url":"node:internal/crypto/hash","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":4553,"count":1}],"isBlockCoverage":false},{"functionName":"Hash","ranges":[{"startOffset":954,"endOffset":1474,"count":20000},{"startOffset":1025,"endOffset":1061,"count":0},{"startOffset":1188,"endOffset":1207,"count":0},{"startOffset":1208,"endOffset":1234,"count":0},{"startOffset":1280,"endOffset":1327,"count":0}],"isBlockCoverage":true},{"functionName":"copy","ranges":[{"startOffset":1605,"endOffset":1773,"count":0}],"isBlockCoverage":false},{"functionName":"_transform","ranges":[{"startOffset":1804,"endOffset":1909,"count":0}],"isBlockCoverage":false},{"functionName":"_flush","ranges":[{"startOffset":1936,"endOffset":2016,"count":0}],"isBlockCoverage":false},{"functionName":"update","ranges":[{"startOffset":2043,"endOffset":2507,"count":20000},{"startOffset":2136,"endOffset":2174,"count":0},{"startOffset":2208,"endOffset":2251,"count":0},{"startOffset":2287,"endOffset":2397,"count":0},{"startOffset":2448,"endOffset":2490,"count":0}],"isBlockCoverage":true},{"functionName":"digest","ranges":[{"startOffset":2535,"endOffset":2856,"count":20000},{"startOffset":2628,"endOffset":2666,"count":0},{"startOffset":2788,"endOffset":2810,"count":0}],"isBlockCoverage":true},{"functionName":"Hmac","ranges":[{"startOffset":2859,"endOffset":3259,"count":0}],"isBlockCoverage":false},{"functionName":"digest","ranges":[{"startOffset":3440,"endOffset":3872,"count":0}],"isBlockCoverage":false},{"functionName":"asyncDigest","ranges":[{"startOffset":4027,"endOffset":4498,"count":40012},{"startOffset":4147,"endOffset":4160,"count":0},{"startOffset":4417,"endOffset":4497,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4311,"endOffset":4411,"count":40012}],"isBlockCoverage":true}]},{"scriptId":"205","url":"node:internal/crypto/x509","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":9909,"count":1}],"isBlockCoverage":false},{"functionName":"isX509Certificate","ranges":[{"startOffset":1155,"endOffset":1238,"count":0}],"isBlockCoverage":false},{"functionName":"getFlags","ranges":[{"startOffset":1240,"endOffset":2485,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2487,"endOffset":2649,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":2651,"endOffset":9663,"count":0}],"isBlockCoverage":false}]},{"scriptId":"206","url":"node:internal/crypto/certificate","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1546,"count":1}],"isBlockCoverage":false},{"functionName":"verifySpkac","ranges":[{"startOffset":385,"endOffset":505,"count":0}],"isBlockCoverage":false},{"functionName":"exportPublicKey","ranges":[{"startOffset":507,"endOffset":635,"count":0}],"isBlockCoverage":false},{"functionName":"exportChallenge","ranges":[{"startOffset":637,"endOffset":765,"count":0}],"isBlockCoverage":false},{"functionName":"Certificate","ranges":[{"startOffset":1122,"endOffset":1216,"count":0}],"isBlockCoverage":false}]},{"scriptId":"207","url":"node:internal/crypto/webcrypto","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":30940,"count":1}],"isBlockCoverage":false},{"functionName":"digest","ranges":[{"startOffset":1190,"endOffset":1799,"count":40012},{"startOffset":1254,"endOffset":1297,"count":0}],"isBlockCoverage":true},{"functionName":"randomUUID","ranges":[{"startOffset":1801,"endOffset":1911,"count":0}],"isBlockCoverage":false},{"functionName":"generateKey","ranges":[{"startOffset":1913,"endOffset":4408,"count":8},{"startOffset":2007,"endOffset":2050,"count":0},{"startOffset":2686,"endOffset":2711,"count":0},{"startOffset":2738,"endOffset":2753,"count":0},{"startOffset":2780,"endOffset":2957,"count":4},{"startOffset":2962,"endOffset":2977,"count":0},{"startOffset":3004,"endOffset":3017,"count":0},{"startOffset":3044,"endOffset":3058,"count":0},{"startOffset":3085,"endOffset":3260,"count":0},{"startOffset":3265,"endOffset":3278,"count":4},{"startOffset":3305,"endOffset":3476,"count":4},{"startOffset":3481,"endOffset":3651,"count":0},{"startOffset":3656,"endOffset":3671,"count":0},{"startOffset":3698,"endOffset":3713,"count":0},{"startOffset":3740,"endOffset":3755,"count":0},{"startOffset":3782,"endOffset":3953,"count":0},{"startOffset":3958,"endOffset":4048,"count":0},{"startOffset":4093,"endOffset":4157,"count":0},{"startOffset":4158,"endOffset":4193,"count":0},{"startOffset":4280,"endOffset":4388,"count":0}],"isBlockCoverage":true},{"functionName":"deriveBits","ranges":[{"startOffset":4410,"endOffset":5970,"count":0}],"isBlockCoverage":false},{"functionName":"getKeyLength","ranges":[{"startOffset":5972,"endOffset":6592,"count":8},{"startOffset":6042,"endOffset":6057,"count":0},{"startOffset":6062,"endOffset":6077,"count":0},{"startOffset":6187,"endOffset":6250,"count":0},{"startOffset":6277,"endOffset":6531,"count":0},{"startOffset":6536,"endOffset":6548,"count":0},{"startOffset":6553,"endOffset":6586,"count":0}],"isBlockCoverage":true},{"functionName":"deriveKey","ranges":[{"startOffset":6594,"endOffset":8774,"count":8},{"startOffset":6720,"endOffset":6763,"count":0},{"startOffset":7700,"endOffset":7809,"count":0},{"startOffset":7863,"endOffset":7934,"count":0},{"startOffset":8063,"endOffset":8077,"count":0},{"startOffset":8104,"endOffset":8116,"count":0},{"startOffset":8143,"endOffset":8281,"count":0},{"startOffset":8286,"endOffset":8415,"count":0},{"startOffset":8560,"endOffset":8650,"count":0}],"isBlockCoverage":true},{"functionName":"exportKeySpki","ranges":[{"startOffset":8776,"endOffset":9754,"count":0}],"isBlockCoverage":false},{"functionName":"exportKeyPkcs8","ranges":[{"startOffset":9756,"endOffset":10743,"count":0}],"isBlockCoverage":false},{"functionName":"exportKeyRaw","ranges":[{"startOffset":10745,"endOffset":11678,"count":4},{"startOffset":10816,"endOffset":10829,"count":2},{"startOffset":10856,"endOffset":11022,"count":2},{"startOffset":11009,"endOffset":11022,"count":0},{"startOffset":11027,"endOffset":11042,"count":0},{"startOffset":11069,"endOffset":11082,"count":0},{"startOffset":11109,"endOffset":11123,"count":0},{"startOffset":11150,"endOffset":11320,"count":0},{"startOffset":11325,"endOffset":11340,"count":0},{"startOffset":11367,"endOffset":11382,"count":0},{"startOffset":11409,"endOffset":11424,"count":2},{"startOffset":11451,"endOffset":11465,"count":2},{"startOffset":11492,"endOffset":11550,"count":2},{"startOffset":11554,"endOffset":11677,"count":0}],"isBlockCoverage":true},{"functionName":"exportKeyJWK","ranges":[{"startOffset":11680,"endOffset":13210,"count":15},{"startOffset":11865,"endOffset":12019,"count":0},{"startOffset":12024,"endOffset":12171,"count":0},{"startOffset":12176,"endOffset":12325,"count":6},{"startOffset":12330,"endOffset":12343,"count":6},{"startOffset":12370,"endOffset":12444,"count":6},{"startOffset":12449,"endOffset":12463,"count":0},{"startOffset":12490,"endOffset":12558,"count":0},{"startOffset":12563,"endOffset":12578,"count":0},{"startOffset":12605,"endOffset":12674,"count":0},{"startOffset":12679,"endOffset":12694,"count":0},{"startOffset":12721,"endOffset":12736,"count":0},{"startOffset":12763,"endOffset":12778,"count":3},{"startOffset":12805,"endOffset":12953,"count":3},{"startOffset":12958,"endOffset":13100,"count":0},{"startOffset":13105,"endOffset":13113,"count":0},{"startOffset":13139,"endOffset":13209,"count":0}],"isBlockCoverage":true},{"functionName":"exportKey","ranges":[{"startOffset":13212,"endOffset":14072,"count":19},{"startOffset":13275,"endOffset":13318,"count":0},{"startOffset":13712,"endOffset":13787,"count":0},{"startOffset":13813,"endOffset":13852,"count":0},{"startOffset":13857,"endOffset":13898,"count":0},{"startOffset":13903,"endOffset":13940,"count":15},{"startOffset":13945,"endOffset":13982,"count":4},{"startOffset":13986,"endOffset":14071,"count":0}],"isBlockCoverage":true},{"functionName":"importGenericSecretKey","ranges":[{"startOffset":14074,"endOffset":15424,"count":8},{"startOffset":14251,"endOffset":14325,"count":0},{"startOffset":14386,"endOffset":14490,"count":0},{"startOffset":14593,"endOffset":14713,"count":0},{"startOffset":15072,"endOffset":15097,"count":0},{"startOffset":15099,"endOffset":15175,"count":0},{"startOffset":15311,"endOffset":15423,"count":0}],"isBlockCoverage":true},{"functionName":"importKey","ranges":[{"startOffset":15426,"endOffset":18168,"count":29},{"startOffset":15539,"endOffset":15582,"count":0},{"startOffset":15889,"endOffset":15903,"count":11},{"startOffset":15904,"endOffset":15920,"count":18},{"startOffset":16451,"endOffset":16476,"count":0},{"startOffset":16503,"endOffset":16518,"count":0},{"startOffset":16545,"endOffset":16701,"count":4},{"startOffset":16706,"endOffset":16719,"count":7},{"startOffset":16746,"endOffset":16896,"count":7},{"startOffset":16901,"endOffset":16916,"count":0},{"startOffset":16943,"endOffset":16956,"count":0},{"startOffset":16983,"endOffset":16997,"count":0},{"startOffset":17024,"endOffset":17178,"count":0},{"startOffset":17183,"endOffset":17336,"count":0},{"startOffset":17341,"endOffset":17356,"count":0},{"startOffset":17383,"endOffset":17398,"count":0},{"startOffset":17425,"endOffset":17440,"count":10},{"startOffset":17467,"endOffset":17621,"count":10},{"startOffset":17626,"endOffset":17638,"count":0},{"startOffset":17665,"endOffset":17830,"count":8},{"startOffset":17835,"endOffset":17925,"count":0},{"startOffset":17963,"endOffset":17991,"count":11},{"startOffset":17993,"endOffset":18022,"count":23},{"startOffset":18024,"endOffset":18148,"count":0}],"isBlockCoverage":true},{"functionName":"wrapKey","ranges":[{"startOffset":18261,"endOffset":19796,"count":0}],"isBlockCoverage":false},{"functionName":"unwrapKey","ranges":[{"startOffset":19891,"endOffset":21854,"count":0}],"isBlockCoverage":false},{"functionName":"signVerify","ranges":[{"startOffset":21856,"endOffset":22959,"count":7},{"startOffset":21964,"endOffset":21991,"count":4},{"startOffset":22142,"endOffset":22248,"count":0},{"startOffset":22282,"endOffset":22297,"count":0},{"startOffset":22324,"endOffset":22450,"count":0},{"startOffset":22575,"endOffset":22590,"count":0},{"startOffset":22617,"endOffset":22756,"count":0},{"startOffset":22761,"endOffset":22875,"count":0},{"startOffset":22879,"endOffset":22958,"count":0}],"isBlockCoverage":true},{"functionName":"sign","ranges":[{"startOffset":22961,"endOffset":23587,"count":3},{"startOffset":23028,"endOffset":23071,"count":0}],"isBlockCoverage":true},{"functionName":"verify","ranges":[{"startOffset":23589,"endOffset":24346,"count":4},{"startOffset":23669,"endOffset":23712,"count":0}],"isBlockCoverage":true},{"functionName":"cipherOrWrap","ranges":[{"startOffset":24348,"endOffset":25759,"count":2009},{"startOffset":24826,"endOffset":24955,"count":1},{"startOffset":24955,"endOffset":25196,"count":2008},{"startOffset":25196,"endOffset":25304,"count":2},{"startOffset":25309,"endOffset":25324,"count":0},{"startOffset":25351,"endOffset":25366,"count":0},{"startOffset":25393,"endOffset":25500,"count":2006},{"startOffset":25505,"endOffset":25675,"count":0},{"startOffset":25679,"endOffset":25758,"count":0}],"isBlockCoverage":true},{"functionName":"encrypt","ranges":[{"startOffset":25761,"endOffset":26487,"count":1005},{"startOffset":25831,"endOffset":25874,"count":0}],"isBlockCoverage":true},{"functionName":"decrypt","ranges":[{"startOffset":26489,"endOffset":27215,"count":1004},{"startOffset":26559,"endOffset":26602,"count":0}],"isBlockCoverage":true},{"functionName":"SubtleCrypto","ranges":[{"startOffset":27371,"endOffset":27431,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":27466,"endOffset":27479,"count":1}],"isBlockCoverage":true},{"functionName":"Crypto","ranges":[{"startOffset":27518,"endOffset":27578,"count":0}],"isBlockCoverage":true},{"functionName":"get subtle","ranges":[{"startOffset":27582,"endOffset":27682,"count":3},{"startOffset":27622,"endOffset":27659,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":27717,"endOffset":27730,"count":1}],"isBlockCoverage":true},{"functionName":"getRandomValues","ranges":[{"startOffset":27746,"endOffset":28079,"count":459384},{"startOffset":27803,"endOffset":27840,"count":0}],"isBlockCoverage":true}]},{"scriptId":"208","url":"file:///home/dmonad/ylabs/lib0/crypto/jwt.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2028,"count":1}],"isBlockCoverage":true},{"functionName":"_stringify","ranges":[{"startOffset":281,"endOffset":355,"count":4}],"isBlockCoverage":true},{"functionName":"_parse","ranges":[{"startOffset":409,"endOffset":491,"count":7}],"isBlockCoverage":true},{"functionName":"encodeJwt","ranges":[{"startOffset":586,"endOffset":1063,"count":2},{"startOffset":781,"endOffset":813,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":992,"endOffset":1057,"count":2}],"isBlockCoverage":true},{"functionName":"verifyJwt","ranges":[{"startOffset":1153,"endOffset":1692,"count":2},{"startOffset":1445,"endOffset":1485,"count":0},{"startOffset":1552,"endOffset":1587,"count":1},{"startOffset":1589,"endOffset":1691,"count":1}],"isBlockCoverage":true},{"functionName":"unsafeDecode","ranges":[{"startOffset":1878,"endOffset":2027,"count":2}],"isBlockCoverage":true}]},{"scriptId":"209","url":"file:///home/dmonad/ylabs/lib0/crypto/rsa-oaep.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1836,"count":1}],"isBlockCoverage":true},{"functionName":"encrypt","ranges":[{"startOffset":478,"endOffset":611,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":584,"endOffset":610,"count":1}],"isBlockCoverage":true},{"functionName":"decrypt","ranges":[{"startOffset":840,"endOffset":975,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":946,"endOffset":974,"count":1}],"isBlockCoverage":true},{"functionName":"generateKeyPair","ranges":[{"startOffset":1148,"endOffset":1404,"count":4}],"isBlockCoverage":true},{"functionName":"importKeyJwk","ranges":[{"startOffset":1558,"endOffset":1835,"count":4},{"startOffset":1629,"endOffset":1701,"count":2},{"startOffset":1681,"endOffset":1697,"count":0}],"isBlockCoverage":true}]},{"scriptId":"210","url":"file:///home/dmonad/ylabs/lib0/crypto/aes-gcm.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3420,"count":1}],"isBlockCoverage":true},{"functionName":"encrypt","ranges":[{"startOffset":495,"endOffset":1064,"count":1003}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":746,"endOffset":1061,"count":1003}],"isBlockCoverage":true},{"functionName":"decrypt","ranges":[{"startOffset":1293,"endOffset":1612,"count":1003}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1581,"endOffset":1609,"count":1002}],"isBlockCoverage":true},{"functionName":"importKeyJwk","ranges":[{"startOffset":1822,"endOffset":2071,"count":1},{"startOffset":1945,"endOffset":1961,"count":0}],"isBlockCoverage":true},{"functionName":"importKeyRaw","ranges":[{"startOffset":2277,"endOffset":2436,"count":1}],"isBlockCoverage":true},{"functionName":"toBinary","ranges":[{"startOffset":2521,"endOffset":2586,"count":16},{"startOffset":2580,"endOffset":2586,"count":0}],"isBlockCoverage":true},{"functionName":"deriveKey","ranges":[{"startOffset":2913,"endOffset":3419,"count":8}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3100,"endOffset":3415,"count":8}],"isBlockCoverage":true}]},{"scriptId":"211","url":"file:///home/dmonad/ylabs/lib0/crypto/ecdsa.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2144,"count":1}],"isBlockCoverage":true},{"functionName":"sign","ranges":[{"startOffset":535,"endOffset":667,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":628,"endOffset":666,"count":3}],"isBlockCoverage":true},{"functionName":"verify","ranges":[{"startOffset":893,"endOffset":1008,"count":4}],"isBlockCoverage":true},{"functionName":"generateKeyPair","ranges":[{"startOffset":1238,"endOffset":1384,"count":4}],"isBlockCoverage":true},{"functionName":"importKeyJwk","ranges":[{"startOffset":1538,"endOffset":1799,"count":6},{"startOffset":1609,"endOffset":1683,"count":4},{"startOffset":1663,"endOffset":1679,"count":0}],"isBlockCoverage":true},{"functionName":"importKeyRaw","ranges":[{"startOffset":1998,"endOffset":2143,"count":1}],"isBlockCoverage":true}]},{"scriptId":"212","url":"file:///home/dmonad/ylabs/lib0/encoding.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":26422,"count":1},{"startOffset":9013,"endOffset":9038,"count":0}],"isBlockCoverage":true},{"functionName":"Encoder","ranges":[{"startOffset":1191,"endOffset":1333,"count":61944}],"isBlockCoverage":true},{"functionName":"createEncoder","ranges":[{"startOffset":1408,"endOffset":1427,"count":61932}],"isBlockCoverage":true},{"functionName":"encode","ranges":[{"startOffset":1496,"endOffset":1584,"count":7148}],"isBlockCoverage":true},{"functionName":"length","ranges":[{"startOffset":1723,"endOffset":1863,"count":115676},{"startOffset":1809,"endOffset":1848,"count":1159}],"isBlockCoverage":true},{"functionName":"hasContent","ranges":[{"startOffset":1999,"endOffset":2053,"count":53755},{"startOffset":2027,"endOffset":2053,"count":1}],"isBlockCoverage":true},{"functionName":"toUint8Array","ranges":[{"startOffset":2212,"endOffset":2524,"count":61940},{"startOffset":2341,"endOffset":2427,"count":1146}],"isBlockCoverage":true},{"functionName":"verifyLen","ranges":[{"startOffset":2750,"endOffset":3016,"count":5554},{"startOffset":2848,"endOffset":3014,"count":5}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":3180,"endOffset":3424,"count":11973866},{"startOffset":3274,"endOffset":3385,"count":152}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":3704,"endOffset":4099,"count":9},{"startOffset":3836,"endOffset":3854,"count":2},{"startOffset":3861,"endOffset":3996,"count":2},{"startOffset":3917,"endOffset":3992,"count":1},{"startOffset":4020,"endOffset":4077,"count":8}],"isBlockCoverage":true},{"functionName":"writeUint16","ranges":[{"startOffset":4735,"endOffset":4838,"count":982}],"isBlockCoverage":true},{"functionName":"setUint16","ranges":[{"startOffset":5107,"endOffset":5225,"count":1}],"isBlockCoverage":true},{"functionName":"writeUint32","ranges":[{"startOffset":5405,"endOffset":5516,"count":1017},{"startOffset":5455,"endOffset":5514,"count":4068}],"isBlockCoverage":true},{"functionName":"writeUint32BigEndian","ranges":[{"startOffset":5759,"endOffset":5870,"count":999},{"startOffset":5810,"endOffset":5868,"count":3996}],"isBlockCoverage":true},{"functionName":"setUint32","ranges":[{"startOffset":6140,"endOffset":6263,"count":1},{"startOffset":6195,"endOffset":6261,"count":4}],"isBlockCoverage":true},{"functionName":"writeVarUint","ranges":[{"startOffset":6478,"endOffset":6673,"count":4794276},{"startOffset":6527,"endOffset":6634,"count":134126}],"isBlockCoverage":true},{"functionName":"writeVarInt","ranges":[{"startOffset":6926,"endOffset":7544,"count":72580},{"startOffset":7010,"endOffset":7030,"count":31657},{"startOffset":7161,"endOffset":7174,"count":59290},{"startOffset":7175,"endOffset":7178,"count":13290},{"startOffset":7194,"endOffset":7207,"count":31657},{"startOffset":7208,"endOffset":7211,"count":40923},{"startOffset":7408,"endOffset":7542,"count":367735},{"startOffset":7449,"endOffset":7462,"count":308445},{"startOffset":7463,"endOffset":7466,"count":59290}],"isBlockCoverage":true},{"functionName":"_writeVarStringNative","ranges":[{"startOffset":7860,"endOffset":8270,"count":2444416},{"startOffset":7913,"endOffset":8201,"count":2443393},{"startOffset":8076,"endOffset":8080,"count":487},{"startOffset":8154,"endOffset":8197,"count":5190198},{"startOffset":8201,"endOffset":8268,"count":1023}],"isBlockCoverage":true},{"functionName":"_writeVarStringPolyfill","ranges":[{"startOffset":8455,"endOffset":8709,"count":300040},{"startOffset":8629,"endOffset":8707,"count":1377820}],"isBlockCoverage":true},{"functionName":"writeTerminatedString","ranges":[{"startOffset":9528,"endOffset":9606,"count":2}],"isBlockCoverage":true},{"functionName":"writeTerminatedUint8Array","ranges":[{"startOffset":10391,"endOffset":10585,"count":4},{"startOffset":10450,"endOffset":10563,"count":35},{"startOffset":10489,"endOffset":10499,"count":28},{"startOffset":10501,"endOffset":10532,"count":9}],"isBlockCoverage":true},{"functionName":"writeBinaryEncoder","ranges":[{"startOffset":11024,"endOffset":11091,"count":1}],"isBlockCoverage":true},{"functionName":"writeUint8Array","ranges":[{"startOffset":11260,"endOffset":11943,"count":7597},{"startOffset":11594,"endOffset":11941,"count":1032}],"isBlockCoverage":true},{"functionName":"writeVarUint8Array","ranges":[{"startOffset":12101,"endOffset":12215,"count":5531}],"isBlockCoverage":true},{"functionName":"writeOnDataView","ranges":[{"startOffset":12744,"endOffset":12897,"count":5553}],"isBlockCoverage":true},{"functionName":"writeFloat32","ranges":[{"startOffset":12986,"endOffset":13057,"count":47}],"isBlockCoverage":true},{"functionName":"writeFloat64","ranges":[{"startOffset":13146,"endOffset":13217,"count":4855}],"isBlockCoverage":true},{"functionName":"writeBigInt64","ranges":[{"startOffset":13307,"endOffset":13400,"count":650}],"isBlockCoverage":true},{"functionName":"writeBigUint64","ranges":[{"startOffset":13491,"endOffset":13585,"count":1}],"isBlockCoverage":true},{"functionName":"isFloat32","ranges":[{"startOffset":13769,"endOffset":13857,"count":4900}],"isBlockCoverage":true},{"functionName":"writeAny","ranges":[{"startOffset":16078,"endOffset":17810,"count":25983},{"startOffset":16128,"endOffset":16242,"count":2660},{"startOffset":16247,"endOffset":16681,"count":4903},{"startOffset":16295,"endOffset":16329,"count":2469},{"startOffset":16331,"endOffset":16432,"count":3},{"startOffset":16432,"endOffset":16669,"count":4900},{"startOffset":16459,"endOffset":16561,"count":46},{"startOffset":16561,"endOffset":16669,"count":4854},{"startOffset":16686,"endOffset":16799,"count":649},{"startOffset":16804,"endOffset":17621,"count":10185},{"startOffset":16844,"endOffset":16907,"count":2598},{"startOffset":16907,"endOffset":17609,"count":7587},{"startOffset":16938,"endOffset":17140,"count":2497},{"startOffset":17084,"endOffset":17132,"count":22394},{"startOffset":17140,"endOffset":17609,"count":5090},{"startOffset":17178,"endOffset":17290,"count":2517},{"startOffset":17290,"endOffset":17609,"count":2573},{"startOffset":17482,"endOffset":17601,"count":2575},{"startOffset":17626,"endOffset":17736,"count":5093},{"startOffset":17712,"endOffset":17717,"count":2539},{"startOffset":17718,"endOffset":17723,"count":2554},{"startOffset":17741,"endOffset":17804,"count":2493}],"isBlockCoverage":true},{"functionName":"RleEncoder","ranges":[{"startOffset":18390,"endOffset":18578,"count":1}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":18612,"endOffset":19005,"count":5050},{"startOffset":18646,"endOffset":18672,"count":4950},{"startOffset":18672,"endOffset":19001,"count":100},{"startOffset":18706,"endOffset":18908,"count":99}],"isBlockCoverage":true},{"functionName":"IntDiffEncoder","ranges":[{"startOffset":19255,"endOffset":19370,"count":3}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":19409,"endOffset":19473,"count":20200}],"isBlockCoverage":true},{"functionName":"RleIntDiffEncoder","ranges":[{"startOffset":19836,"endOffset":19970,"count":2}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":20009,"endOffset":20434,"count":15150},{"startOffset":20042,"endOffset":20059,"count":5068},{"startOffset":20061,"endOffset":20087,"count":5068},{"startOffset":20087,"endOffset":20430,"count":10082},{"startOffset":20121,"endOffset":20323,"count":10080}],"isBlockCoverage":true},{"functionName":"flushUintOptRleEncoder","ranges":[{"startOffset":20515,"endOffset":21032,"count":6032},{"startOffset":20553,"endOffset":21030,"count":6031},{"startOffset":20830,"endOffset":20841,"count":5785},{"startOffset":20842,"endOffset":20854,"count":246},{"startOffset":20883,"endOffset":21026,"count":246}],"isBlockCoverage":true},{"functionName":"UintOptRleEncoder","ranges":[{"startOffset":21462,"endOffset":21587,"count":2}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":21626,"endOffset":21776,"count":6080},{"startOffset":21660,"endOffset":21686,"count":5001},{"startOffset":21686,"endOffset":21772,"count":1079}],"isBlockCoverage":true},{"functionName":"toUint8Array","ranges":[{"startOffset":21910,"endOffset":22002,"count":2}],"isBlockCoverage":true},{"functionName":"IncUintOptRleEncoder","ranges":[{"startOffset":22320,"endOffset":22445,"count":1}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":22484,"endOffset":22647,"count":5050},{"startOffset":22531,"endOffset":22557,"count":100},{"startOffset":22557,"endOffset":22643,"count":4950}],"isBlockCoverage":true},{"functionName":"toUint8Array","ranges":[{"startOffset":22781,"endOffset":22873,"count":1}],"isBlockCoverage":true},{"functionName":"flushIntDiffOptRleEncoder","ranges":[{"startOffset":22960,"endOffset":23676,"count":10170},{"startOffset":22998,"endOffset":23674,"count":10168},{"startOffset":23213,"endOffset":23216,"count":10039},{"startOffset":23217,"endOffset":23220,"count":129},{"startOffset":23527,"endOffset":23670,"count":129}],"isBlockCoverage":true},{"functionName":"IntDiffOptRleEncoder","ranges":[{"startOffset":24583,"endOffset":24726,"count":2}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":24765,"endOffset":24976,"count":15150},{"startOffset":24811,"endOffset":24854,"count":4982},{"startOffset":24854,"endOffset":24972,"count":10168}],"isBlockCoverage":true},{"functionName":"toUint8Array","ranges":[{"startOffset":25110,"endOffset":25205,"count":2}],"isBlockCoverage":true},{"functionName":"StringEncoder","ranges":[{"startOffset":25835,"endOffset":25976,"count":1}],"isBlockCoverage":true},{"functionName":"write","ranges":[{"startOffset":26020,"endOffset":26180,"count":1030},{"startOffset":26086,"endOffset":26140,"count":375}],"isBlockCoverage":true},{"functionName":"toUint8Array","ranges":[{"startOffset":26184,"endOffset":26419,"count":1}],"isBlockCoverage":true}]},{"scriptId":"213","url":"file:///home/dmonad/ylabs/lib0/decoding.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":17649,"count":1},{"startOffset":10767,"endOffset":10791,"count":0}],"isBlockCoverage":true},{"functionName":"Decoder","ranges":[{"startOffset":1440,"endOffset":1665,"count":61916}],"isBlockCoverage":true},{"functionName":"createDecoder","ranges":[{"startOffset":1774,"endOffset":1811,"count":61905}],"isBlockCoverage":true},{"functionName":"hasContent","ranges":[{"startOffset":1909,"endOffset":1954,"count":72188}],"isBlockCoverage":true},{"functionName":"clone","ranges":[{"startOffset":2222,"endOffset":2348,"count":1}],"isBlockCoverage":true},{"functionName":"readUint8Array","ranges":[{"startOffset":2857,"endOffset":3006,"count":2088096}],"isBlockCoverage":true},{"functionName":"readVarUint8Array","ranges":[{"startOffset":3394,"endOffset":3450,"count":2086030}],"isBlockCoverage":true},{"functionName":"readTailAsUint8Array","ranges":[{"startOffset":3611,"endOffset":3679,"count":3}],"isBlockCoverage":true},{"functionName":"skip8","ranges":[{"startOffset":3855,"endOffset":3879,"count":1}],"isBlockCoverage":true},{"functionName":"readUint8","ranges":[{"startOffset":4057,"endOffset":4094,"count":28066}],"isBlockCoverage":true},{"functionName":"readUint16","ranges":[{"startOffset":4252,"endOffset":4385,"count":982}],"isBlockCoverage":true},{"functionName":"readUint32","ranges":[{"startOffset":4543,"endOffset":4770,"count":1017}],"isBlockCoverage":true},{"functionName":"readUint32BigEndian","ranges":[{"startOffset":4990,"endOffset":5217,"count":999}],"isBlockCoverage":true},{"functionName":"peekUint8","ranges":[{"startOffset":5438,"endOffset":5473,"count":1}],"isBlockCoverage":true},{"functionName":"peekUint16","ranges":[{"startOffset":5695,"endOffset":5772,"count":1}],"isBlockCoverage":true},{"functionName":"peekUint32","ranges":[{"startOffset":5994,"endOffset":6163,"count":1}],"isBlockCoverage":true},{"functionName":"readVarUint","ranges":[{"startOffset":6494,"endOffset":7062,"count":4132322},{"startOffset":6597,"endOffset":7026,"count":4268325},{"startOffset":6865,"endOffset":6889,"count":4132321},{"startOffset":6889,"endOffset":6955,"count":136004},{"startOffset":6955,"endOffset":6997,"count":0},{"startOffset":7026,"endOffset":7061,"count":1}],"isBlockCoverage":true},{"functionName":"readVarInt","ranges":[{"startOffset":7505,"endOffset":8167,"count":72581},{"startOffset":7637,"endOffset":7641,"count":31658},{"startOffset":7642,"endOffset":7645,"count":40923},{"startOffset":7677,"endOffset":7734,"count":13290},{"startOffset":7734,"endOffset":7796,"count":59291},{"startOffset":7796,"endOffset":8131,"count":367735},{"startOffset":7963,"endOffset":7994,"count":59290},{"startOffset":7994,"endOffset":8060,"count":308445},{"startOffset":8060,"endOffset":8102,"count":0},{"startOffset":8131,"endOffset":8166,"count":1}],"isBlockCoverage":true},{"functionName":"peekVarUint","ranges":[{"startOffset":8329,"endOffset":8433,"count":9122}],"isBlockCoverage":true},{"functionName":"peekVarInt","ranges":[{"startOffset":8594,"endOffset":8697,"count":7722}],"isBlockCoverage":true},{"functionName":"_readVarStringPolyfill","ranges":[{"startOffset":9277,"endOffset":10256,"count":1000},{"startOffset":9358,"endOffset":9377,"count":0},{"startOffset":9517,"endOffset":9677,"count":0},{"startOffset":9716,"endOffset":10191,"count":4000},{"startOffset":9763,"endOffset":9777,"count":1000},{"startOffset":9778,"endOffset":9785,"count":3000}],"isBlockCoverage":true},{"functionName":"_readVarStringNative","ranges":[{"startOffset":10400,"endOffset":10489,"count":2081522}],"isBlockCoverage":true},{"functionName":"readTerminatedUint8Array","ranges":[{"startOffset":10893,"endOffset":11160,"count":4},{"startOffset":10972,"endOffset":11158,"count":39},{"startOffset":11018,"endOffset":11069,"count":4},{"startOffset":11069,"endOffset":11087,"count":35},{"startOffset":11087,"endOffset":11123,"count":9},{"startOffset":11123,"endOffset":11158,"count":35}],"isBlockCoverage":true},{"functionName":"readTerminatedString","ranges":[{"startOffset":11254,"endOffset":11317,"count":2}],"isBlockCoverage":true},{"functionName":"peekVarString","ranges":[{"startOffset":11483,"endOffset":11589,"count":7147}],"isBlockCoverage":true},{"functionName":"readFromDataView","ranges":[{"startOffset":11704,"endOffset":11847,"count":5553}],"isBlockCoverage":true},{"functionName":"readFloat32","ranges":[{"startOffset":11912,"endOffset":11972,"count":47}],"isBlockCoverage":true},{"functionName":"readFloat64","ranges":[{"startOffset":12037,"endOffset":12097,"count":4855}],"isBlockCoverage":true},{"functionName":"readBigInt64","ranges":[{"startOffset":12163,"endOffset":12245,"count":650}],"isBlockCoverage":true},{"functionName":"readBigUint64","ranges":[{"startOffset":12312,"endOffset":12395,"count":1}],"isBlockCoverage":true},{"functionName":"obj","ranges":[{"startOffset":12476,"endOffset":12496,"count":2493}],"isBlockCoverage":true},{"functionName":"obj","ranges":[{"startOffset":12523,"endOffset":12538,"count":2598}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12703,"endOffset":12719,"count":2554}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12752,"endOffset":12767,"count":2539}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12836,"endOffset":13122,"count":2573},{"startOffset":13021,"endOffset":13103,"count":2575}],"isBlockCoverage":true},{"functionName":"readAnyLookupTable","ranges":[{"startOffset":13126,"endOffset":13312,"count":2497},{"startOffset":13253,"endOffset":13293,"count":22394}],"isBlockCoverage":true},{"functionName":"readAny","ranges":[{"startOffset":13420,"endOffset":13484,"count":25983}],"isBlockCoverage":true},{"functionName":"RleDecoder","ranges":[{"startOffset":13668,"endOffset":13883,"count":1}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":13887,"endOffset":14244,"count":5050},{"startOffset":13923,"endOffset":14186,"count":100},{"startOffset":13986,"endOffset":14107,"count":99},{"startOffset":14107,"endOffset":14180,"count":1}],"isBlockCoverage":true},{"functionName":"IntDiffDecoder","ranges":[{"startOffset":14371,"endOffset":14508,"count":3}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":14546,"endOffset":14608,"count":20200}],"isBlockCoverage":true},{"functionName":"RleIntDiffDecoder","ranges":[{"startOffset":14738,"endOffset":14894,"count":2}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":14932,"endOffset":15294,"count":15150},{"startOffset":14968,"endOffset":15231,"count":10082},{"startOffset":15031,"endOffset":15152,"count":10080},{"startOffset":15152,"endOffset":15225,"count":2}],"isBlockCoverage":true},{"functionName":"UintOptRleDecoder","ranges":[{"startOffset":15397,"endOffset":15521,"count":2}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":15525,"endOffset":15915,"count":6080},{"startOffset":15561,"endOffset":15852,"count":1080},{"startOffset":15769,"endOffset":15846,"count":147}],"isBlockCoverage":true},{"functionName":"IncUintOptRleDecoder","ranges":[{"startOffset":16021,"endOffset":16145,"count":1}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":16149,"endOffset":16541,"count":5050},{"startOffset":16185,"endOffset":16476,"count":4951},{"startOffset":16393,"endOffset":16470,"count":99}],"isBlockCoverage":true},{"functionName":"IntDiffOptRleDecoder","ranges":[{"startOffset":16647,"endOffset":16789,"count":2}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":16827,"endOffset":17200,"count":15150},{"startOffset":16863,"endOffset":17137,"count":10168},{"startOffset":17079,"endOffset":17131,"count":129}],"isBlockCoverage":true},{"functionName":"StringDecoder","ranges":[{"startOffset":17283,"endOffset":17465,"count":1}],"isBlockCoverage":true},{"functionName":"read","ranges":[{"startOffset":17503,"endOffset":17646,"count":1030}],"isBlockCoverage":true}]},{"scriptId":"214","url":"file:///home/dmonad/ylabs/lib0/binary.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2038,"count":1}],"isBlockCoverage":true}]},{"scriptId":"215","url":"file:///home/dmonad/ylabs/lib0/number.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":884,"count":1},{"startOffset":448,"endOffset":527,"count":0}],"isBlockCoverage":true},{"functionName":"isInteger","ranges":[{"startOffset":452,"endOffset":526,"count":0}],"isBlockCoverage":false},{"functionName":"countBits","ranges":[{"startOffset":776,"endOffset":883,"count":3},{"startOffset":832,"endOffset":866,"count":6}],"isBlockCoverage":true}]},{"scriptId":"216","url":"file:///home/dmonad/ylabs/lib0/error.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":454,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":138,"endOffset":155,"count":4}],"isBlockCoverage":true},{"functionName":"methodUnimplemented","ranges":[{"startOffset":261,"endOffset":309,"count":0}],"isBlockCoverage":false},{"functionName":"unexpectedCase","ranges":[{"startOffset":410,"endOffset":453,"count":0}],"isBlockCoverage":false}]},{"scriptId":"217","url":"file:///home/dmonad/ylabs/lib0/prng/Xoroshiro128plus.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3408,"count":1}],"isBlockCoverage":true},{"functionName":"Xoroshiro128plus","ranges":[{"startOffset":1054,"endOffset":1369,"count":87972},{"startOffset":1279,"endOffset":1342,"count":351888}],"isBlockCoverage":true},{"functionName":"next","ranges":[{"startOffset":1429,"endOffset":2337,"count":11152171},{"startOffset":1489,"endOffset":1587,"count":5611676},{"startOffset":1587,"endOffset":2333,"count":5540495}],"isBlockCoverage":true}]},{"scriptId":"218","url":"file:///home/dmonad/ylabs/lib0/prng/Xorshift32.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":603,"count":1}],"isBlockCoverage":true},{"functionName":"Xorshift32","ranges":[{"startOffset":237,"endOffset":343,"count":87973}],"isBlockCoverage":true},{"functionName":"next","ranges":[{"startOffset":450,"endOffset":600,"count":401888}],"isBlockCoverage":true}]},{"scriptId":"219","url":"file:///home/dmonad/ylabs/lib0/prng/Mt19937.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2007,"count":1}],"isBlockCoverage":true},{"functionName":"twist","ranges":[{"startOffset":192,"endOffset":278,"count":50544},{"startOffset":260,"endOffset":272,"count":25205},{"startOffset":273,"endOffset":276,"count":25339}],"isBlockCoverage":true},{"functionName":"nextState","ranges":[{"startOffset":336,"endOffset":618,"count":81},{"startOffset":399,"endOffset":464,"count":18387},{"startOffset":489,"endOffset":558,"count":32076}],"isBlockCoverage":true},{"functionName":"Mt19937","ranges":[{"startOffset":1278,"endOffset":1588,"count":1},{"startOffset":1409,"endOffset":1517,"count":623}],"isBlockCoverage":true},{"functionName":"next","ranges":[{"startOffset":1695,"endOffset":2004,"count":50000},{"startOffset":1728,"endOffset":1819,"count":80}],"isBlockCoverage":true}]},{"scriptId":"220","url":"file:///home/dmonad/ylabs/lib0/dom.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":6297,"count":1},{"startOffset":286,"endOffset":296,"count":0},{"startOffset":733,"endOffset":750,"count":0}],"isBlockCoverage":true},{"functionName":"createElement","ranges":[{"startOffset":390,"endOffset":421,"count":0}],"isBlockCoverage":false},{"functionName":"createDocumentFragment","ranges":[{"startOffset":499,"endOffset":533,"count":0}],"isBlockCoverage":false},{"functionName":"createTextNode","ranges":[{"startOffset":615,"endOffset":647,"count":0}],"isBlockCoverage":false},{"functionName":"emitCustomEvent","ranges":[{"startOffset":874,"endOffset":939,"count":0}],"isBlockCoverage":false},{"functionName":"setAttributes","ranges":[{"startOffset":1105,"endOffset":1374,"count":0}],"isBlockCoverage":false},{"functionName":"setAttributesMap","ranges":[{"startOffset":1523,"endOffset":1618,"count":0}],"isBlockCoverage":false},{"functionName":"fragment","ranges":[{"startOffset":1730,"endOffset":1896,"count":0}],"isBlockCoverage":false},{"functionName":"append","ranges":[{"startOffset":2006,"endOffset":2083,"count":0}],"isBlockCoverage":false},{"functionName":"remove","ranges":[{"startOffset":2142,"endOffset":2159,"count":0}],"isBlockCoverage":false},{"functionName":"addEventListener","ranges":[{"startOffset":2280,"endOffset":2325,"count":0}],"isBlockCoverage":false},{"functionName":"removeEventListener","ranges":[{"startOffset":2449,"endOffset":2497,"count":0}],"isBlockCoverage":false},{"functionName":"addEventListeners","ranges":[{"startOffset":2641,"endOffset":2751,"count":0}],"isBlockCoverage":false},{"functionName":"removeEventListeners","ranges":[{"startOffset":2898,"endOffset":3011,"count":0}],"isBlockCoverage":false},{"functionName":"element","ranges":[{"startOffset":3223,"endOffset":3321,"count":0}],"isBlockCoverage":false},{"functionName":"canvas","ranges":[{"startOffset":3404,"endOffset":3546,"count":0}],"isBlockCoverage":false},{"functionName":"pairToStyleString","ranges":[{"startOffset":3714,"endOffset":3751,"count":0}],"isBlockCoverage":false},{"functionName":"pairsToStyleString","ranges":[{"startOffset":3865,"endOffset":3911,"count":0}],"isBlockCoverage":false},{"functionName":"mapToStyleString","ranges":[{"startOffset":4006,"endOffset":4066,"count":0}],"isBlockCoverage":false},{"functionName":"querySelector","ranges":[{"startOffset":4249,"endOffset":4287,"count":0}],"isBlockCoverage":false},{"functionName":"querySelectorAll","ranges":[{"startOffset":4429,"endOffset":4470,"count":0}],"isBlockCoverage":false},{"functionName":"getElementById","ranges":[{"startOffset":4557,"endOffset":4614,"count":0}],"isBlockCoverage":false},{"functionName":"_parse","ranges":[{"startOffset":4688,"endOffset":4776,"count":0}],"isBlockCoverage":false},{"functionName":"parseFragment","ranges":[{"startOffset":4869,"endOffset":4931,"count":0}],"isBlockCoverage":false},{"functionName":"parseElement","ranges":[{"startOffset":5018,"endOffset":5083,"count":0}],"isBlockCoverage":false},{"functionName":"replaceWith","ranges":[{"startOffset":5197,"endOffset":5239,"count":0}],"isBlockCoverage":false},{"functionName":"insertBefore","ranges":[{"startOffset":5386,"endOffset":5435,"count":0}],"isBlockCoverage":false},{"functionName":"appendChild","ranges":[{"startOffset":5537,"endOffset":5581,"count":0}],"isBlockCoverage":false},{"functionName":"checkNodeType","ranges":[{"startOffset":6021,"endOffset":6059,"count":0}],"isBlockCoverage":false},{"functionName":"isParentOf","ranges":[{"startOffset":6149,"endOffset":6275,"count":0}],"isBlockCoverage":false}]},{"scriptId":"221","url":"file:///home/dmonad/ylabs/lib0/logging.common.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2853,"count":1}],"isBlockCoverage":true},{"functionName":"computeNoColorLoggingArgs","ranges":[{"startOffset":708,"endOffset":1341,"count":730},{"startOffset":742,"endOffset":778,"count":4},{"startOffset":780,"endOffset":886,"count":1},{"startOffset":1036,"endOffset":1322,"count":3872},{"startOffset":1089,"endOffset":1131,"count":1},{"startOffset":1131,"endOffset":1318,"count":3871},{"startOffset":1168,"endOffset":1197,"count":1945},{"startOffset":1199,"endOffset":1233,"count":1929},{"startOffset":1233,"endOffset":1318,"count":1942},{"startOffset":1271,"endOffset":1318,"count":5}],"isBlockCoverage":true},{"functionName":"createModuleLogger","ranges":[{"startOffset":1646,"endOffset":2831,"count":1},{"startOffset":1803,"endOffset":1919,"count":0},{"startOffset":2033,"endOffset":2829,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2035,"endOffset":2829,"count":0}],"isBlockCoverage":false}]},{"scriptId":"222","url":"file:///home/dmonad/ylabs/lib0/indexeddb.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7011,"count":1}],"isBlockCoverage":true},{"functionName":"rtop","ranges":[{"startOffset":320,"endOffset":530,"count":0}],"isBlockCoverage":false},{"functionName":"openDB","ranges":[{"startOffset":707,"endOffset":1224,"count":0}],"isBlockCoverage":false},{"functionName":"deleteDB","ranges":[{"startOffset":1282,"endOffset":1326,"count":0}],"isBlockCoverage":false},{"functionName":"createStores","ranges":[{"startOffset":1485,"endOffset":1584,"count":0}],"isBlockCoverage":false},{"functionName":"transact","ranges":[{"startOffset":1757,"endOffset":1910,"count":0}],"isBlockCoverage":false},{"functionName":"count","ranges":[{"startOffset":2035,"endOffset":2079,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":2280,"endOffset":2318,"count":0}],"isBlockCoverage":false},{"functionName":"del","ranges":[{"startOffset":2461,"endOffset":2502,"count":0}],"isBlockCoverage":false},{"functionName":"put","ranges":[{"startOffset":2696,"endOffset":2746,"count":0}],"isBlockCoverage":false},{"functionName":"add","ranges":[{"startOffset":2966,"endOffset":3016,"count":0}],"isBlockCoverage":false},{"functionName":"addAutoKey","ranges":[{"startOffset":3195,"endOffset":3235,"count":0}],"isBlockCoverage":false},{"functionName":"getAll","ranges":[{"startOffset":3392,"endOffset":3451,"count":0}],"isBlockCoverage":false},{"functionName":"getAllKeys","ranges":[{"startOffset":3612,"endOffset":3675,"count":0}],"isBlockCoverage":false},{"functionName":"queryFirst","ranges":[{"startOffset":3867,"endOffset":4058,"count":0}],"isBlockCoverage":false},{"functionName":"getLastKey","ranges":[{"startOffset":4186,"endOffset":4243,"count":0}],"isBlockCoverage":false},{"functionName":"getFirstKey","ranges":[{"startOffset":4372,"endOffset":4429,"count":0}],"isBlockCoverage":false},{"functionName":"getAllKeysValues","ranges":[{"startOffset":4709,"endOffset":4883,"count":0}],"isBlockCoverage":false},{"functionName":"iterateOnRequest","ranges":[{"startOffset":5047,"endOffset":5357,"count":0}],"isBlockCoverage":false},{"functionName":"iterate","ranges":[{"startOffset":5656,"endOffset":5796,"count":0}],"isBlockCoverage":false},{"functionName":"iterateKeys","ranges":[{"startOffset":6098,"endOffset":6227,"count":0}],"isBlockCoverage":false},{"functionName":"getStore","ranges":[{"startOffset":6375,"endOffset":6409,"count":0}],"isBlockCoverage":false},{"functionName":"createIDBKeyRangeBound","ranges":[{"startOffset":6561,"endOffset":6654,"count":0}],"isBlockCoverage":false},{"functionName":"createIDBKeyRangeUpperBound","ranges":[{"startOffset":6759,"endOffset":6821,"count":0}],"isBlockCoverage":false},{"functionName":"createIDBKeyRangeLowerBound","ranges":[{"startOffset":6926,"endOffset":6988,"count":0}],"isBlockCoverage":false}]},{"scriptId":"223","url":"file:///home/dmonad/ylabs/lib0/queue.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1338,"count":1}],"isBlockCoverage":true},{"functionName":"QueueNode","ranges":[{"startOffset":27,"endOffset":114,"count":60}],"isBlockCoverage":true},{"functionName":"QueueValue","ranges":[{"startOffset":217,"endOffset":265,"count":60}],"isBlockCoverage":true},{"functionName":"Queue","ranges":[{"startOffset":327,"endOffset":469,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":658,"endOffset":675,"count":1}],"isBlockCoverage":true},{"functionName":"isEmpty","ranges":[{"startOffset":737,"endOffset":766,"count":63}],"isBlockCoverage":true},{"functionName":"enqueue","ranges":[{"startOffset":898,"endOffset":1037,"count":60},{"startOffset":940,"endOffset":986,"count":58},{"startOffset":986,"endOffset":1035,"count":2}],"isBlockCoverage":true},{"functionName":"dequeue","ranges":[{"startOffset":1146,"endOffset":1337,"count":63},{"startOffset":1199,"endOffset":1321,"count":60},{"startOffset":1274,"endOffset":1304,"count":2},{"startOffset":1321,"endOffset":1336,"count":3}],"isBlockCoverage":true}]},{"scriptId":"224","url":"file:///home/dmonad/ylabs/lib0/eventloop.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2434,"count":1}],"isBlockCoverage":true},{"functionName":"_runQueue","ranges":[{"startOffset":257,"endOffset":341,"count":1},{"startOffset":306,"endOffset":326,"count":12}],"isBlockCoverage":true},{"functionName":"enqueue","ranges":[{"startOffset":404,"endOffset":489,"count":12},{"startOffset":453,"endOffset":487,"count":1}],"isBlockCoverage":true},{"functionName":"createTimeoutClass","ranges":[{"startOffset":664,"endOffset":837,"count":4}],"isBlockCoverage":true},{"functionName":"TT","ranges":[{"startOffset":737,"endOffset":789,"count":6}],"isBlockCoverage":true},{"functionName":"destroy","ranges":[{"startOffset":793,"endOffset":835,"count":2}],"isBlockCoverage":true},{"functionName":"timeout","ranges":[{"startOffset":1004,"endOffset":1069,"count":4}],"isBlockCoverage":true},{"functionName":"interval","ranges":[{"startOffset":1239,"endOffset":1306,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1373,"endOffset":1453,"count":0}],"isBlockCoverage":false},{"functionName":"animationFrame","ranges":[{"startOffset":1579,"endOffset":1689,"count":1},{"startOffset":1647,"endOffset":1689,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":1758,"endOffset":1833,"count":0}],"isBlockCoverage":false},{"functionName":"idleCallback","ranges":[{"startOffset":2034,"endOffset":2138,"count":1},{"startOffset":2083,"endOffset":2118,"count":0}],"isBlockCoverage":true},{"functionName":"createDebouncer","ranges":[{"startOffset":2281,"endOffset":2433,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2320,"endOffset":2431,"count":2}],"isBlockCoverage":true}]},{"scriptId":"225","url":"file:///home/dmonad/ylabs/lib0/pair.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":885,"count":1}],"isBlockCoverage":true},{"functionName":"Pair","ranges":[{"startOffset":159,"endOffset":234,"count":3}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":347,"endOffset":385,"count":2}],"isBlockCoverage":true},{"functionName":"createReversed","ranges":[{"startOffset":504,"endOffset":542,"count":1}],"isBlockCoverage":true},{"functionName":"forEach","ranges":[{"startOffset":658,"endOffset":706,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":682,"endOffset":705,"count":3}],"isBlockCoverage":true},{"functionName":"map","ranges":[{"startOffset":840,"endOffset":884,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":860,"endOffset":883,"count":6}],"isBlockCoverage":true}]},{"scriptId":"226","url":"file:///home/dmonad/ylabs/lib0/observable.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3680,"count":1}],"isBlockCoverage":true},{"functionName":"ObservableV2","ranges":[{"startOffset":438,"endOffset":564,"count":1}],"isBlockCoverage":true},{"functionName":"on","ranges":[{"startOffset":677,"endOffset":797,"count":3}],"isBlockCoverage":true},{"functionName":"once","ranges":[{"startOffset":910,"endOffset":1117,"count":1}],"isBlockCoverage":true},{"functionName":"_f","ranges":[{"startOffset":987,"endOffset":1070,"count":1}],"isBlockCoverage":true},{"functionName":"off","ranges":[{"startOffset":1230,"endOffset":1443,"count":2},{"startOffset":1387,"endOffset":1433,"count":1}],"isBlockCoverage":true},{"functionName":"emit","ranges":[{"startOffset":1810,"endOffset":2084,"count":6},{"startOffset":2029,"endOffset":2044,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2064,"endOffset":2079,"count":6}],"isBlockCoverage":true},{"functionName":"destroy","ranges":[{"startOffset":2088,"endOffset":2139,"count":1}],"isBlockCoverage":true},{"functionName":"Observable","ranges":[{"startOffset":2259,"endOffset":2375,"count":0}],"isBlockCoverage":false},{"functionName":"on","ranges":[{"startOffset":2437,"endOffset":2520,"count":0}],"isBlockCoverage":false},{"functionName":"once","ranges":[{"startOffset":2582,"endOffset":2747,"count":0}],"isBlockCoverage":false},{"functionName":"off","ranges":[{"startOffset":2809,"endOffset":3022,"count":0}],"isBlockCoverage":false},{"functionName":"emit","ranges":[{"startOffset":3328,"endOffset":3602,"count":0}],"isBlockCoverage":false},{"functionName":"destroy","ranges":[{"startOffset":3606,"endOffset":3657,"count":0}],"isBlockCoverage":false}]},{"scriptId":"227","url":"file:///home/dmonad/ylabs/lib0/set.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":472,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":86,"endOffset":101,"count":7}],"isBlockCoverage":true},{"functionName":"toArray","ranges":[{"startOffset":194,"endOffset":216,"count":1}],"isBlockCoverage":true},{"functionName":"first","ranges":[{"startOffset":300,"endOffset":347,"count":3},{"startOffset":335,"endOffset":347,"count":1}],"isBlockCoverage":true},{"functionName":"from","ranges":[{"startOffset":444,"endOffset":471,"count":4}],"isBlockCoverage":true}]},{"scriptId":"228","url":"file:///home/dmonad/ylabs/lib0/sort.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":2173,"count":1}],"isBlockCoverage":true},{"functionName":"_insertionSort","ranges":[{"startOffset":476,"endOffset":697,"count":23162},{"startOffset":541,"endOffset":695,"count":573638},{"startOffset":569,"endOffset":603,"count":80027093},{"startOffset":610,"endOffset":691,"count":79453664}],"isBlockCoverage":true},{"functionName":"insertionSort","ranges":[{"startOffset":835,"endOffset":906,"count":31}],"isBlockCoverage":true},{"functionName":"_quickSort","ranges":[{"startOffset":1060,"endOffset":1651,"count":46226},{"startOffset":1108,"endOffset":1154,"count":23131},{"startOffset":1154,"endOffset":1649,"count":23095},{"startOffset":1258,"endOffset":1569,"count":1803418},{"startOffset":1301,"endOffset":1322,"count":2569781},{"startOffset":1364,"endOffset":1385,"count":2573121},{"startOffset":1404,"endOffset":1427,"count":23095},{"startOffset":1427,"endOffset":1569,"count":1780323}],"isBlockCoverage":true},{"functionName":"quicksort","ranges":[{"startOffset":2105,"endOffset":2172,"count":36}],"isBlockCoverage":true}]},{"scriptId":"229","url":"file:///home/dmonad/ylabs/lib0/url.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":875,"count":1}],"isBlockCoverage":true},{"functionName":"decodeQueryParams","ranges":[{"startOffset":244,"endOffset":659,"count":9},{"startOffset":466,"endOffset":642,"count":12},{"startOffset":519,"endOffset":638,"count":9},{"startOffset":626,"endOffset":631,"count":2}],"isBlockCoverage":true},{"functionName":"encodeQueryParams","ranges":[{"startOffset":763,"endOffset":874,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":794,"endOffset":863,"count":3}],"isBlockCoverage":true}]},{"scriptId":"230","url":"file:///home/dmonad/ylabs/lib0/metric.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1563,"count":1}],"isBlockCoverage":true},{"functionName":"prefix","ranges":[{"startOffset":1077,"endOffset":1562,"count":424},{"startOffset":1129,"endOffset":1132,"count":1},{"startOffset":1133,"endOffset":1148,"count":423},{"startOffset":1189,"endOffset":1211,"count":244},{"startOffset":1213,"endOffset":1250,"count":243},{"startOffset":1281,"endOffset":1302,"count":54},{"startOffset":1304,"endOffset":1341,"count":53},{"startOffset":1378,"endOffset":1407,"count":403},{"startOffset":1408,"endOffset":1434,"count":21},{"startOffset":1474,"endOffset":1500,"count":18},{"startOffset":1501,"endOffset":1528,"count":406}],"isBlockCoverage":true}]},{"scriptId":"231","url":"file:///home/dmonad/ylabs/lib0/storage.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1755,"count":1},{"startOffset":753,"endOffset":768,"count":0},{"startOffset":770,"endOffset":832,"count":0},{"startOffset":835,"endOffset":848,"count":0}],"isBlockCoverage":true},{"functionName":"VarStoragePolyfill","ranges":[{"startOffset":216,"endOffset":261,"count":1}],"isBlockCoverage":true},{"functionName":"setItem","ranges":[{"startOffset":329,"endOffset":390,"count":1}],"isBlockCoverage":true},{"functionName":"getItem","ranges":[{"startOffset":431,"endOffset":479,"count":0}],"isBlockCoverage":false},{"functionName":"onChange","ranges":[{"startOffset":1285,"endOffset":1378,"count":1},{"startOffset":1313,"endOffset":1378,"count":0}],"isBlockCoverage":true},{"functionName":"offChange","ranges":[{"startOffset":1658,"endOffset":1754,"count":0}],"isBlockCoverage":false}]},{"scriptId":"232","url":"file:///home/dmonad/ylabs/lib0/conditions.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":218,"count":1}],"isBlockCoverage":true},{"functionName":"undefinedToNull","ranges":[{"startOffset":186,"endOffset":217,"count":2},{"startOffset":214,"endOffset":217,"count":0}],"isBlockCoverage":true}]},{"scriptId":"233","url":"file:///home/dmonad/ylabs/lib0/symbol.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":264,"count":1}],"isBlockCoverage":true},{"functionName":"isSymbol","ranges":[{"startOffset":237,"endOffset":263,"count":1}],"isBlockCoverage":true}]},{"scriptId":"234","url":"file:///home/dmonad/ylabs/lib0/list.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3473,"count":1}],"isBlockCoverage":true},{"functionName":"ListNode","ranges":[{"startOffset":98,"endOffset":242,"count":64}],"isBlockCoverage":true},{"functionName":"List","ranges":[{"startOffset":302,"endOffset":461,"count":3}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":651,"endOffset":667,"count":3}],"isBlockCoverage":true},{"functionName":"isEmpty","ranges":[{"startOffset":755,"endOffset":784,"count":63}],"isBlockCoverage":true},{"functionName":"remove","ranges":[{"startOffset":1002,"endOffset":1244,"count":74},{"startOffset":1083,"endOffset":1109,"count":3},{"startOffset":1109,"endOffset":1143,"count":71},{"startOffset":1156,"endOffset":1182,"count":65},{"startOffset":1182,"endOffset":1214,"count":9}],"isBlockCoverage":true},{"functionName":"insertBetween","ranges":[{"startOffset":1500,"endOffset":1861,"count":75},{"startOffset":1575,"endOffset":1597,"count":66},{"startOffset":1599,"endOffset":1637,"count":0},{"startOffset":1673,"endOffset":1699,"count":66},{"startOffset":1699,"endOffset":1733,"count":9},{"startOffset":1747,"endOffset":1774,"count":1},{"startOffset":1774,"endOffset":1806,"count":74}],"isBlockCoverage":true},{"functionName":"replace","ranges":[{"startOffset":2102,"endOffset":2202,"count":1}],"isBlockCoverage":true},{"functionName":"pushEnd","ranges":[{"startOffset":2306,"endOffset":2362,"count":72}],"isBlockCoverage":true},{"functionName":"pushFront","ranges":[{"startOffset":2468,"endOffset":2526,"count":1}],"isBlockCoverage":true},{"functionName":"popFront","ranges":[{"startOffset":2635,"endOffset":2693,"count":65},{"startOffset":2656,"endOffset":2686,"count":62},{"startOffset":2687,"endOffset":2693,"count":3}],"isBlockCoverage":true},{"functionName":"popEnd","ranges":[{"startOffset":2800,"endOffset":2854,"count":3},{"startOffset":2819,"endOffset":2847,"count":2},{"startOffset":2848,"endOffset":2854,"count":1}],"isBlockCoverage":true},{"functionName":"map","ranges":[{"startOffset":3002,"endOffset":3155,"count":2},{"startOffset":3101,"endOffset":3140,"count":6}],"isBlockCoverage":true},{"functionName":"toArray","ranges":[{"startOffset":3242,"endOffset":3263,"count":1}],"isBlockCoverage":true},{"functionName":"forEach","ranges":[{"startOffset":3393,"endOffset":3472,"count":1},{"startOffset":3441,"endOffset":3470,"count":3}],"isBlockCoverage":true}]},{"scriptId":"235","url":"file:///home/dmonad/ylabs/lib0/cache.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":3970,"count":1}],"isBlockCoverage":true},{"functionName":"Entry","ranges":[{"startOffset":355,"endOffset":587,"count":5}],"isBlockCoverage":true},{"functionName":"Cache","ranges":[{"startOffset":681,"endOffset":895,"count":1}],"isBlockCoverage":true},{"functionName":"removeStale","ranges":[{"startOffset":1035,"endOffset":1235,"count":26},{"startOffset":1117,"endOffset":1157,"count":20},{"startOffset":1159,"endOffset":1220,"count":2}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":1353,"endOffset":1673,"count":7},{"startOffset":1473,"endOffset":1565,"count":5},{"startOffset":1565,"endOffset":1671,"count":2}],"isBlockCoverage":true},{"functionName":"getNode","ranges":[{"startOffset":1805,"endOffset":1905,"count":15},{"startOffset":1885,"endOffset":1903,"count":11}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":2030,"endOffset":2143,"count":11},{"startOffset":2091,"endOffset":2121,"count":8},{"startOffset":2122,"endOffset":2129,"count":7},{"startOffset":2130,"endOffset":2141,"count":4}],"isBlockCoverage":true},{"functionName":"refreshTimeout","ranges":[{"startOffset":2252,"endOffset":2441,"count":2},{"startOffset":2365,"endOffset":2439,"count":1}],"isBlockCoverage":true},{"functionName":"getAsync","ranges":[{"startOffset":2757,"endOffset":2839,"count":4},{"startOffset":2818,"endOffset":2825,"count":3},{"startOffset":2826,"endOffset":2837,"count":1}],"isBlockCoverage":true},{"functionName":"remove","ranges":[{"startOffset":2940,"endOffset":3134,"count":3},{"startOffset":2999,"endOffset":3132,"count":2},{"startOffset":3078,"endOffset":3108,"count":1},{"startOffset":3109,"endOffset":3116,"count":1},{"startOffset":3117,"endOffset":3128,"count":1}],"isBlockCoverage":true},{"functionName":"setIfUndefined","ranges":[{"startOffset":3440,"endOffset":3881,"count":4},{"startOffset":3567,"endOffset":3589,"count":1},{"startOffset":3589,"endOffset":3879,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3720,"endOffset":3861,"count":3},{"startOffset":3753,"endOffset":3783,"count":2},{"startOffset":3805,"endOffset":3817,"count":1},{"startOffset":3819,"endOffset":3855,"count":1}],"isBlockCoverage":true},{"functionName":"create","ranges":[{"startOffset":3940,"endOffset":3969,"count":1}],"isBlockCoverage":true}]},{"scriptId":"236","url":"file:///home/dmonad/ylabs/lib0/crypto/common.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":445,"count":1}],"isBlockCoverage":true},{"functionName":"exportKeyJwk","ranges":[{"startOffset":107,"endOffset":222,"count":15}],"isBlockCoverage":true},{"functionName":"exportKeyRaw","ranges":[{"startOffset":364,"endOffset":444,"count":4}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":417,"endOffset":443,"count":4}],"isBlockCoverage":true}]},{"scriptId":"237","url":"node:net","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":66240,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1612,"endOffset":1637,"count":0}],"isBlockCoverage":false},{"functionName":"noop","ranges":[{"startOffset":4029,"endOffset":4037,"count":0}],"isBlockCoverage":false},{"functionName":"getFlags","ranges":[{"startOffset":4446,"endOffset":4540,"count":0}],"isBlockCoverage":false},{"functionName":"createHandle","ranges":[{"startOffset":4542,"endOffset":4925,"count":2},{"startOffset":4709,"endOffset":4731,"count":0},{"startOffset":4766,"endOffset":4924,"count":0}],"isBlockCoverage":true},{"functionName":"getNewAsyncId","ranges":[{"startOffset":4928,"endOffset":5066,"count":2},{"startOffset":5023,"endOffset":5041,"count":0}],"isBlockCoverage":true},{"functionName":"isPipeName","ranges":[{"startOffset":5069,"endOffset":5152,"count":0}],"isBlockCoverage":false},{"functionName":"createServer","ranges":[{"startOffset":5353,"endOffset":5457,"count":0}],"isBlockCoverage":false},{"functionName":"connect","ranges":[{"startOffset":5680,"endOffset":6081,"count":0}],"isBlockCoverage":false},{"functionName":"getDefaultAutoSelectFamily","ranges":[{"startOffset":6083,"endOffset":6158,"count":0}],"isBlockCoverage":false},{"functionName":"setDefaultAutoSelectFamily","ranges":[{"startOffset":6160,"endOffset":6276,"count":0}],"isBlockCoverage":false},{"functionName":"getDefaultAutoSelectFamilyAttemptTimeout","ranges":[{"startOffset":6278,"endOffset":6381,"count":0}],"isBlockCoverage":false},{"functionName":"setDefaultAutoSelectFamilyAttemptTimeout","ranges":[{"startOffset":6383,"endOffset":6570,"count":0}],"isBlockCoverage":false},{"functionName":"normalizeArgs","ranges":[{"startOffset":7064,"endOffset":7790,"count":0}],"isBlockCoverage":false},{"functionName":"initSocketHandle","ranges":[{"startOffset":7862,"endOffset":8465,"count":2},{"startOffset":8218,"endOffset":8459,"count":0}],"isBlockCoverage":true},{"functionName":"closeSocketHandle","ranges":[{"startOffset":8467,"endOffset":8807,"count":0}],"isBlockCoverage":false},{"functionName":"Socket","ranges":[{"startOffset":9059,"endOffset":13678,"count":2},{"startOffset":9119,"endOffset":9146,"count":0},{"startOffset":9174,"endOffset":9303,"count":0},{"startOffset":9373,"endOffset":9621,"count":0},{"startOffset":9683,"endOffset":9879,"count":0},{"startOffset":10441,"endOffset":10467,"count":0},{"startOffset":10873,"endOffset":10981,"count":0},{"startOffset":11509,"endOffset":11543,"count":0},{"startOffset":11619,"endOffset":11630,"count":1},{"startOffset":11688,"endOffset":12217,"count":0},{"startOffset":12308,"endOffset":12385,"count":0},{"startOffset":12386,"endOffset":12432,"count":0},{"startOffset":12434,"endOffset":12649,"count":0},{"startOffset":13184,"endOffset":13449,"count":0},{"startOffset":13473,"endOffset":13525,"count":0}],"isBlockCoverage":true},{"functionName":"_unrefTimer","ranges":[{"startOffset":13851,"endOffset":13981,"count":558},{"startOffset":13953,"endOffset":13975,"count":0}],"isBlockCoverage":true},{"functionName":"Socket._final","ranges":[{"startOffset":14101,"endOffset":14717,"count":0}],"isBlockCoverage":false},{"functionName":"afterShutdown","ranges":[{"startOffset":14720,"endOffset":14866,"count":0}],"isBlockCoverage":false},{"functionName":"writeAfterFIN","ranges":[{"startOffset":15073,"endOffset":15581,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._onTimeout","ranges":[{"startOffset":15663,"endOffset":16167,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.setNoDelay","ranges":[{"startOffset":16201,"endOffset":16578,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.setKeepAlive","ranges":[{"startOffset":16614,"endOffset":17220,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.address","ranges":[{"startOffset":17251,"endOffset":17295,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":17381,"endOffset":17425,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":17505,"endOffset":17561,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":17672,"endOffset":17987,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":18076,"endOffset":18156,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":18244,"endOffset":18289,"count":0}],"isBlockCoverage":false},{"functionName":"tryReadStart","ranges":[{"startOffset":18297,"endOffset":18543,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._read","ranges":[{"startOffset":18635,"endOffset":18954,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.end","ranges":[{"startOffset":18981,"endOffset":19137,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.resetAndDestroy","ranges":[{"startOffset":19175,"endOffset":19525,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.pause","ranges":[{"startOffset":19553,"endOffset":19887,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.resume","ranges":[{"startOffset":19917,"endOffset":20101,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.read","ranges":[{"startOffset":20129,"endOffset":20315,"count":0}],"isBlockCoverage":false},{"functionName":"onReadableStreamEnd","ranges":[{"startOffset":20362,"endOffset":20461,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.destroySoon","ranges":[{"startOffset":20495,"endOffset":20642,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._destroy","ranges":[{"startOffset":20674,"endOffset":22184,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._reset","ranges":[{"startOffset":22213,"endOffset":22312,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._getpeername","ranges":[{"startOffset":22347,"endOffset":22644,"count":0}],"isBlockCoverage":false},{"functionName":"protoGetter","ranges":[{"startOffset":22647,"endOffset":22829,"count":9}],"isBlockCoverage":true},{"functionName":"bytesRead","ranges":[{"startOffset":22856,"endOffset":22947,"count":0}],"isBlockCoverage":false},{"functionName":"remoteAddress","ranges":[{"startOffset":22980,"endOffset":23046,"count":0}],"isBlockCoverage":false},{"functionName":"remoteFamily","ranges":[{"startOffset":23078,"endOffset":23142,"count":0}],"isBlockCoverage":false},{"functionName":"remotePort","ranges":[{"startOffset":23172,"endOffset":23232,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._getsockname","ranges":[{"startOffset":23269,"endOffset":23545,"count":0}],"isBlockCoverage":false},{"functionName":"localAddress","ranges":[{"startOffset":23577,"endOffset":23642,"count":0}],"isBlockCoverage":false},{"functionName":"localPort","ranges":[{"startOffset":23672,"endOffset":23731,"count":0}],"isBlockCoverage":false},{"functionName":"localFamily","ranges":[{"startOffset":23762,"endOffset":23825,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.","ranges":[{"startOffset":23866,"endOffset":23913,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._writeGeneric","ranges":[{"startOffset":23949,"endOffset":24861,"count":558},{"startOffset":24171,"endOffset":24515,"count":0},{"startOffset":24596,"endOffset":24652,"count":0},{"startOffset":24706,"endOffset":24742,"count":0},{"startOffset":24821,"endOffset":24859,"count":0}],"isBlockCoverage":true},{"functionName":"connect","ranges":[{"startOffset":24266,"endOffset":24380,"count":0}],"isBlockCoverage":false},{"functionName":"onClose","ranges":[{"startOffset":24387,"endOffset":24466,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._writev","ranges":[{"startOffset":24892,"endOffset":24960,"count":0}],"isBlockCoverage":false},{"functionName":"Socket._write","ranges":[{"startOffset":24990,"endOffset":25071,"count":558}],"isBlockCoverage":true},{"functionName":"_bytesDispatched","ranges":[{"startOffset":25264,"endOffset":25368,"count":0}],"isBlockCoverage":false},{"functionName":"bytesWritten","ranges":[{"startOffset":25400,"endOffset":26329,"count":0}],"isBlockCoverage":false},{"functionName":"checkBindError","ranges":[{"startOffset":26334,"endOffset":27133,"count":0}],"isBlockCoverage":false},{"functionName":"internalConnect","ranges":[{"startOffset":27136,"endOffset":29131,"count":0}],"isBlockCoverage":false},{"functionName":"internalConnectMultiple","ranges":[{"startOffset":29134,"endOffset":31870,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.connect","ranges":[{"startOffset":31899,"endOffset":33495,"count":0}],"isBlockCoverage":false},{"functionName":"reinitializeHandle","ranges":[{"startOffset":33538,"endOffset":33692,"count":0}],"isBlockCoverage":false},{"functionName":"socketToDnsFamily","ranges":[{"startOffset":33695,"endOffset":33841,"count":0}],"isBlockCoverage":false},{"functionName":"lookupAndConnect","ranges":[{"startOffset":33843,"endOffset":37774,"count":0}],"isBlockCoverage":false},{"functionName":"lookupAndConnectMultiple","ranges":[{"startOffset":37776,"endOffset":41750,"count":0}],"isBlockCoverage":false},{"functionName":"connectErrorNT","ranges":[{"startOffset":41752,"endOffset":41811,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.ref","ranges":[{"startOffset":41837,"endOffset":42024,"count":0}],"isBlockCoverage":false},{"functionName":"Socket.unref","ranges":[{"startOffset":42053,"endOffset":42246,"count":0}],"isBlockCoverage":false},{"functionName":"afterConnect","ranges":[{"startOffset":42250,"endOffset":43831,"count":0}],"isBlockCoverage":false},{"functionName":"addClientAbortSignalOption","ranges":[{"startOffset":43833,"endOffset":44256,"count":0}],"isBlockCoverage":false},{"functionName":"createConnectionError","ranges":[{"startOffset":44258,"endOffset":44759,"count":0}],"isBlockCoverage":false},{"functionName":"afterConnectMultiple","ranges":[{"startOffset":44761,"endOffset":45903,"count":0}],"isBlockCoverage":false},{"functionName":"internalConnectMultipleTimeout","ranges":[{"startOffset":45905,"endOffset":46217,"count":0}],"isBlockCoverage":false},{"functionName":"addServerAbortSignalOption","ranges":[{"startOffset":46219,"endOffset":46662,"count":0}],"isBlockCoverage":false},{"functionName":"Server","ranges":[{"startOffset":46664,"endOffset":48251,"count":0}],"isBlockCoverage":false},{"functionName":"toNumber","ranges":[{"startOffset":48362,"endOffset":48427,"count":0}],"isBlockCoverage":false},{"functionName":"createServerHandle","ranges":[{"startOffset":48495,"endOffset":49947,"count":0}],"isBlockCoverage":false},{"functionName":"setupListenHandle","ranges":[{"startOffset":49949,"endOffset":52300,"count":0}],"isBlockCoverage":false},{"functionName":"emitErrorNT","ranges":[{"startOffset":52367,"endOffset":52429,"count":0}],"isBlockCoverage":false},{"functionName":"emitListeningNT","ranges":[{"startOffset":52432,"endOffset":52547,"count":0}],"isBlockCoverage":false},{"functionName":"listenInCluster","ranges":[{"startOffset":52550,"endOffset":53810,"count":0}],"isBlockCoverage":false},{"functionName":"Server.listen","ranges":[{"startOffset":53839,"endOffset":57990,"count":0}],"isBlockCoverage":false},{"functionName":"lookupAndListen","ranges":[{"startOffset":57993,"endOffset":58405,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":58487,"endOffset":58530,"count":0}],"isBlockCoverage":false},{"functionName":"Server.address","ranges":[{"startOffset":58606,"endOffset":58895,"count":0}],"isBlockCoverage":false},{"functionName":"onconnection","ranges":[{"startOffset":58898,"endOffset":60797,"count":0}],"isBlockCoverage":false},{"functionName":"Server.getConnections","ranges":[{"startOffset":60946,"endOffset":61699,"count":0}],"isBlockCoverage":false},{"functionName":"Server.close","ranges":[{"startOffset":61728,"endOffset":62595,"count":0}],"isBlockCoverage":false},{"functionName":"Server.","ranges":[{"startOffset":62637,"endOffset":62757,"count":0}],"isBlockCoverage":false},{"functionName":"Server._emitCloseIfDrained","ranges":[{"startOffset":62799,"endOffset":63185,"count":0}],"isBlockCoverage":false},{"functionName":"emitCloseNT","ranges":[{"startOffset":63189,"endOffset":63272,"count":0}],"isBlockCoverage":false},{"functionName":"Server.","ranges":[{"startOffset":63331,"endOffset":63493,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":63715,"endOffset":63751,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":63755,"endOffset":63796,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":63876,"endOffset":63907,"count":574}],"isBlockCoverage":true},{"functionName":"set","ranges":[{"startOffset":63911,"endOffset":63947,"count":2}],"isBlockCoverage":true},{"functionName":"Server._setupWorker","ranges":[{"startOffset":63986,"endOffset":64227,"count":0}],"isBlockCoverage":false},{"functionName":"Server.ref","ranges":[{"startOffset":64253,"endOffset":64351,"count":0}],"isBlockCoverage":false},{"functionName":"Server.unref","ranges":[{"startOffset":64379,"endOffset":64478,"count":0}],"isBlockCoverage":false},{"functionName":"_setSimultaneousAccepts","ranges":[{"startOffset":64620,"endOffset":65289,"count":0}],"isBlockCoverage":false},{"functionName":"_setSimultaneousAccepts","ranges":[{"startOffset":65328,"endOffset":65569,"count":0}],"isBlockCoverage":false},{"functionName":"get BlockList","ranges":[{"startOffset":65698,"endOffset":65800,"count":0}],"isBlockCoverage":false},{"functionName":"get SocketAddress","ranges":[{"startOffset":65804,"endOffset":65926,"count":0}],"isBlockCoverage":false}]},{"scriptId":"238","url":"node:internal/stream_base_commons","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7041,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":1010,"endOffset":1035,"count":0}],"isBlockCoverage":false},{"functionName":"handleWriteReq","ranges":[{"startOffset":1154,"endOffset":2009,"count":558},{"startOffset":1254,"endOffset":1421,"count":0},{"startOffset":1426,"endOffset":1440,"count":0},{"startOffset":1445,"endOffset":1509,"count":0},{"startOffset":1597,"endOffset":1659,"count":0},{"startOffset":1664,"endOffset":1676,"count":0},{"startOffset":1681,"endOffset":1694,"count":0},{"startOffset":1699,"endOffset":1714,"count":0},{"startOffset":1719,"endOffset":1783,"count":0},{"startOffset":1788,"endOffset":2003,"count":0}],"isBlockCoverage":true},{"functionName":"onWriteComplete","ranges":[{"startOffset":2011,"endOffset":2696,"count":0}],"isBlockCoverage":false},{"functionName":"createWriteWrap","ranges":[{"startOffset":2698,"endOffset":2936,"count":558}],"isBlockCoverage":true},{"functionName":"writevGeneric","ranges":[{"startOffset":2938,"endOffset":3577,"count":0}],"isBlockCoverage":false},{"functionName":"writeGeneric","ranges":[{"startOffset":3579,"endOffset":3784,"count":558}],"isBlockCoverage":true},{"functionName":"afterWriteDispatched","ranges":[{"startOffset":3786,"endOffset":4089,"count":558},{"startOffset":3953,"endOffset":4004,"count":0}],"isBlockCoverage":true},{"functionName":"onStreamRead","ranges":[{"startOffset":4091,"endOffset":6022,"count":0}],"isBlockCoverage":false},{"functionName":"setStreamTimeout","ranges":[{"startOffset":6024,"endOffset":6834,"count":0}],"isBlockCoverage":false}]},{"scriptId":"239","url":"node:diagnostics_channel","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":9791,"count":1}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":734,"endOffset":1143,"count":1}],"isBlockCoverage":false},{"functionName":"#finalizers","ranges":[{"startOffset":814,"endOffset":850,"count":0}],"isBlockCoverage":false},{"functionName":"set","ranges":[{"startOffset":856,"endOffset":973,"count":2}],"isBlockCoverage":true},{"functionName":"get","ranges":[{"startOffset":977,"endOffset":1025,"count":2},{"startOffset":1013,"endOffset":1018,"count":0}],"isBlockCoverage":true},{"functionName":"incRef","ranges":[{"startOffset":1029,"endOffset":1083,"count":0}],"isBlockCoverage":false},{"functionName":"decRef","ranges":[{"startOffset":1087,"endOffset":1141,"count":0}],"isBlockCoverage":false},{"functionName":"markActive","ranges":[{"startOffset":1145,"endOffset":1350,"count":0}],"isBlockCoverage":false},{"functionName":"maybeMarkInactive","ranges":[{"startOffset":1352,"endOffset":1720,"count":0}],"isBlockCoverage":false},{"functionName":"defaultTransform","ranges":[{"startOffset":1722,"endOffset":1772,"count":0}],"isBlockCoverage":false},{"functionName":"wrapStoreRun","ranges":[{"startOffset":1774,"endOffset":2102,"count":0}],"isBlockCoverage":false},{"functionName":"subscribe","ranges":[{"startOffset":2184,"endOffset":2354,"count":0}],"isBlockCoverage":false},{"functionName":"unsubscribe","ranges":[{"startOffset":2358,"endOffset":2635,"count":0}],"isBlockCoverage":false},{"functionName":"bindStore","ranges":[{"startOffset":2639,"endOffset":2807,"count":0}],"isBlockCoverage":false},{"functionName":"unbindStore","ranges":[{"startOffset":2811,"endOffset":3010,"count":0}],"isBlockCoverage":false},{"functionName":"get hasSubscribers","ranges":[{"startOffset":3014,"endOffset":3057,"count":0}],"isBlockCoverage":false},{"functionName":"publish","ranges":[{"startOffset":3061,"endOffset":3370,"count":0}],"isBlockCoverage":false},{"functionName":"runStores","ranges":[{"startOffset":3374,"endOffset":3713,"count":0}],"isBlockCoverage":false},{"functionName":"Channel","ranges":[{"startOffset":3735,"endOffset":3876,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3887,"endOffset":4072,"count":0}],"isBlockCoverage":false},{"functionName":"subscribe","ranges":[{"startOffset":4076,"endOffset":4161,"count":0}],"isBlockCoverage":false},{"functionName":"unsubscribe","ranges":[{"startOffset":4165,"endOffset":4202,"count":0}],"isBlockCoverage":false},{"functionName":"bindStore","ranges":[{"startOffset":4206,"endOffset":4299,"count":0}],"isBlockCoverage":false},{"functionName":"unbindStore","ranges":[{"startOffset":4303,"endOffset":4340,"count":0}],"isBlockCoverage":false},{"functionName":"get hasSubscribers","ranges":[{"startOffset":4344,"endOffset":4388,"count":0}],"isBlockCoverage":false},{"functionName":"publish","ranges":[{"startOffset":4392,"endOffset":4404,"count":0}],"isBlockCoverage":false},{"functionName":"runStores","ranges":[{"startOffset":4408,"endOffset":4495,"count":0}],"isBlockCoverage":false},{"functionName":"channel","ranges":[{"startOffset":4535,"endOffset":4801,"count":2},{"startOffset":4613,"endOffset":4628,"count":0},{"startOffset":4661,"endOffset":4688,"count":0},{"startOffset":4690,"endOffset":4770,"count":0}],"isBlockCoverage":true},{"functionName":"subscribe","ranges":[{"startOffset":4803,"endOffset":4893,"count":0}],"isBlockCoverage":false},{"functionName":"unsubscribe","ranges":[{"startOffset":4895,"endOffset":4989,"count":0}],"isBlockCoverage":false},{"functionName":"hasSubscribers","ranges":[{"startOffset":4991,"endOffset":5126,"count":0}],"isBlockCoverage":false},{"functionName":"assertChannel","ranges":[{"startOffset":5215,"endOffset":5357,"count":0}],"isBlockCoverage":false},{"functionName":"TracingChannel","ranges":[{"startOffset":5384,"endOffset":6531,"count":0}],"isBlockCoverage":false},{"functionName":"subscribe","ranges":[{"startOffset":6535,"endOffset":6687,"count":0}],"isBlockCoverage":false},{"functionName":"unsubscribe","ranges":[{"startOffset":6691,"endOffset":6924,"count":0}],"isBlockCoverage":false},{"functionName":"traceSync","ranges":[{"startOffset":6928,"endOffset":7354,"count":0}],"isBlockCoverage":false},{"functionName":"tracePromise","ranges":[{"startOffset":7358,"endOffset":8459,"count":0}],"isBlockCoverage":false},{"functionName":"traceCallback","ranges":[{"startOffset":8463,"endOffset":9589,"count":0}],"isBlockCoverage":false},{"functionName":"tracingChannel","ranges":[{"startOffset":9593,"endOffset":9681,"count":0}],"isBlockCoverage":false}]},{"scriptId":"240","url":"node:internal/worker/io","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":15479,"count":1}],"isBlockCoverage":false},{"functionName":"MessagePort.hasRef","ranges":[{"startOffset":3683,"endOffset":3766,"count":0}],"isBlockCoverage":false},{"functionName":"validateMessagePort","ranges":[{"startOffset":3769,"endOffset":3907,"count":0}],"isBlockCoverage":false},{"functionName":"isMessageEvent","ranges":[{"startOffset":3909,"endOffset":3985,"count":0}],"isBlockCoverage":false},{"functionName":"MessageEvent","ranges":[{"startOffset":4024,"endOffset":4540,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4628,"endOffset":4752,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":4862,"endOffset":4988,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":5103,"endOffset":5234,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":5344,"endOffset":5470,"count":0}],"isBlockCoverage":false},{"functionName":"get","ranges":[{"startOffset":5579,"endOffset":5704,"count":0}],"isBlockCoverage":false},{"functionName":"value","ranges":[{"startOffset":5946,"endOffset":6264,"count":0}],"isBlockCoverage":false},{"functionName":"oninit","ranges":[{"startOffset":6403,"endOffset":6546,"count":2}],"isBlockCoverage":true},{"functionName":"MessagePortCloseEvent","ranges":[{"startOffset":6848,"endOffset":6887,"count":1}],"isBlockCoverage":true},{"functionName":"onclose","ranges":[{"startOffset":6960,"endOffset":7033,"count":1}],"isBlockCoverage":true},{"functionName":"MessagePort.close","ranges":[{"startOffset":7214,"endOffset":7349,"count":1},{"startOffset":7265,"endOffset":7288,"count":0}],"isBlockCoverage":true},{"functionName":"inspect","ranges":[{"startOffset":7482,"endOffset":8110,"count":0}],"isBlockCoverage":false},{"functionName":"setupPortReferencing","ranges":[{"startOffset":8117,"endOffset":9480,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8478,"endOffset":8573,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":8612,"endOffset":8710,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":8812,"endOffset":8957,"count":4},{"startOffset":8872,"endOffset":8894,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9068,"endOffset":9215,"count":2},{"startOffset":9128,"endOffset":9149,"count":1}],"isBlockCoverage":true},{"functionName":"newListener","ranges":[{"startOffset":9221,"endOffset":9362,"count":2}],"isBlockCoverage":true},{"functionName":"removeListener","ranges":[{"startOffset":9366,"endOffset":9478,"count":1}],"isBlockCoverage":true},{"functionName":"ReadableWorkerStdio","ranges":[{"startOffset":9530,"endOffset":9879,"count":0}],"isBlockCoverage":false},{"functionName":"_read","ranges":[{"startOffset":9883,"endOffset":10189,"count":0}],"isBlockCoverage":false},{"functionName":"WritableWorkerStdio","ranges":[{"startOffset":10240,"endOffset":10389,"count":0}],"isBlockCoverage":false},{"functionName":"_writev","ranges":[{"startOffset":10393,"endOffset":10769,"count":0}],"isBlockCoverage":false},{"functionName":"_final","ranges":[{"startOffset":10773,"endOffset":10953,"count":0}],"isBlockCoverage":false},{"functionName":"","ranges":[{"startOffset":10957,"endOffset":11204,"count":0}],"isBlockCoverage":false},{"functionName":"createWorkerStdio","ranges":[{"startOffset":11208,"endOffset":11478,"count":0}],"isBlockCoverage":false},{"functionName":"receiveMessageOnPort","ranges":[{"startOffset":11480,"endOffset":11660,"count":0}],"isBlockCoverage":false},{"functionName":"onMessageEvent","ranges":[{"startOffset":11662,"endOffset":11757,"count":0}],"isBlockCoverage":false},{"functionName":"isBroadcastChannel","ranges":[{"startOffset":11759,"endOffset":11845,"count":5}],"isBlockCoverage":true},{"functionName":"BroadcastChannel","ranges":[{"startOffset":11932,"endOffset":12446,"count":2},{"startOffset":11990,"endOffset":12025,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":12450,"endOffset":12863,"count":0}],"isBlockCoverage":false},{"functionName":"get name","ranges":[{"startOffset":12899,"endOffset":13028,"count":0}],"isBlockCoverage":false},{"functionName":"close","ranges":[{"startOffset":13065,"endOffset":13463,"count":1},{"startOffset":13116,"endOffset":13163,"count":0},{"startOffset":13207,"endOffset":13214,"count":0}],"isBlockCoverage":true},{"functionName":"postMessage","ranges":[{"startOffset":13531,"endOffset":13941,"count":4},{"startOffset":13595,"endOffset":13642,"count":0},{"startOffset":13681,"endOffset":13719,"count":0},{"startOffset":13763,"endOffset":13817,"count":0},{"startOffset":13882,"endOffset":13937,"count":0}],"isBlockCoverage":true},{"functionName":"ref","ranges":[{"startOffset":14224,"endOffset":14391,"count":0}],"isBlockCoverage":false},{"functionName":"unref","ranges":[{"startOffset":14676,"endOffset":14847,"count":0}],"isBlockCoverage":false}]},{"scriptId":"241","url":"node:internal/util/colors","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":1122,"count":1}],"isBlockCoverage":false},{"functionName":"lazyInternalTTY","ranges":[{"startOffset":32,"endOffset":127,"count":0}],"isBlockCoverage":false},{"functionName":"shouldColorize","ranges":[{"startOffset":244,"endOffset":504,"count":558},{"startOffset":316,"endOffset":375,"count":0},{"startOffset":401,"endOffset":499,"count":0}],"isBlockCoverage":true},{"functionName":"refresh","ranges":[{"startOffset":508,"endOffset":1090,"count":1},{"startOffset":550,"endOffset":1086,"count":0}],"isBlockCoverage":true}]},{"scriptId":"242","url":"node:internal/crypto/webidl","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":17440,"count":1}],"isBlockCoverage":false},{"functionName":"codedTypeError","ranges":[{"startOffset":1157,"endOffset":1366,"count":0}],"isBlockCoverage":false},{"functionName":"makeException","ranges":[{"startOffset":1368,"endOffset":1687,"count":0}],"isBlockCoverage":false},{"functionName":"toNumber","ranges":[{"startOffset":1730,"endOffset":2131,"count":20},{"startOffset":1847,"endOffset":1963,"count":0},{"startOffset":1968,"endOffset":2084,"count":0},{"startOffset":2089,"endOffset":2125,"count":0}],"isBlockCoverage":true},{"functionName":"type","ranges":[{"startOffset":2133,"endOffset":2876,"count":88394},{"startOffset":2174,"endOffset":2188,"count":0},{"startOffset":2216,"endOffset":2259,"count":0},{"startOffset":2264,"endOffset":2303,"count":0},{"startOffset":2308,"endOffset":2345,"count":0},{"startOffset":2350,"endOffset":2387,"count":40044},{"startOffset":2392,"endOffset":2429,"count":0},{"startOffset":2434,"endOffset":2471,"count":0},{"startOffset":2476,"endOffset":2490,"count":48350},{"startOffset":2511,"endOffset":2527,"count":48350},{"startOffset":2548,"endOffset":2870,"count":48350}],"isBlockCoverage":true},{"functionName":"createIntegerConversion","ranges":[{"startOffset":2987,"endOffset":3881,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3167,"endOffset":3878,"count":20},{"startOffset":3288,"endOffset":3380,"count":0},{"startOffset":3453,"endOffset":3646,"count":0},{"startOffset":3669,"endOffset":3708,"count":0},{"startOffset":3710,"endOffset":3802,"count":0},{"startOffset":3804,"endOffset":3877,"count":0}],"isBlockCoverage":true},{"functionName":"converters.boolean","ranges":[{"startOffset":3928,"endOffset":3942,"count":56}],"isBlockCoverage":true},{"functionName":"converters.DOMString","ranges":[{"startOffset":4134,"endOffset":4374,"count":84288},{"startOffset":4217,"endOffset":4373,"count":0}],"isBlockCoverage":true},{"functionName":"converters.object","ranges":[{"startOffset":4397,"endOffset":4525,"count":2060},{"startOffset":4440,"endOffset":4510,"count":0}],"isBlockCoverage":true},{"functionName":"isNonSharedArrayBuffer","ranges":[{"startOffset":4528,"endOffset":4630,"count":8}],"isBlockCoverage":true},{"functionName":"isSharedArrayBuffer","ranges":[{"startOffset":4632,"endOffset":4872,"count":44060},{"startOffset":4854,"endOffset":4871,"count":0}],"isBlockCoverage":true},{"functionName":"converters.Uint8Array","ranges":[{"startOffset":4898,"endOffset":5289,"count":4},{"startOffset":5024,"endOffset":5105,"count":0},{"startOffset":5166,"endOffset":5274,"count":0}],"isBlockCoverage":true},{"functionName":"converters.BufferSource","ranges":[{"startOffset":5318,"endOffset":5744,"count":44064},{"startOffset":5376,"endOffset":5576,"count":44056},{"startOffset":5441,"endOffset":5557,"count":0},{"startOffset":5576,"endOffset":5612,"count":8},{"startOffset":5612,"endOffset":5729,"count":0},{"startOffset":5729,"endOffset":5743,"count":8}],"isBlockCoverage":true},{"functionName":"requiredArguments","ranges":[{"startOffset":5834,"endOffset":6147,"count":501476},{"startOffset":5927,"endOffset":6145,"count":0}],"isBlockCoverage":true},{"functionName":"createDictionaryConverter","ranges":[{"startOffset":6149,"endOffset":7954,"count":22},{"startOffset":6309,"endOffset":6456,"count":72},{"startOffset":6372,"endOffset":6408,"count":45}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6490,"endOffset":6589,"count":104},{"startOffset":6527,"endOffset":6550,"count":0},{"startOffset":6576,"endOffset":6580,"count":54},{"startOffset":6581,"endOffset":6584,"count":50}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":6602,"endOffset":7951,"count":44174},{"startOffset":6691,"endOffset":6708,"count":0},{"startOffset":6715,"endOffset":6727,"count":0},{"startOffset":6770,"endOffset":6874,"count":0},{"startOffset":6983,"endOffset":7001,"count":0},{"startOffset":7003,"endOffset":7032,"count":0},{"startOffset":7094,"endOffset":7926,"count":50448},{"startOffset":7205,"endOffset":7249,"count":0},{"startOffset":7342,"endOffset":7696,"count":46315},{"startOffset":7439,"endOffset":7443,"count":0},{"startOffset":7696,"endOffset":7920,"count":4133},{"startOffset":7723,"endOffset":7920,"count":0}],"isBlockCoverage":true},{"functionName":"createEnumConverter","ranges":[{"startOffset":7956,"endOffset":8317,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8044,"endOffset":8314,"count":119},{"startOffset":8124,"endOffset":8295,"count":0}],"isBlockCoverage":true},{"functionName":"createSequenceConverter","ranges":[{"startOffset":8319,"endOffset":9162,"count":3}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":8374,"endOffset":9159,"count":56},{"startOffset":8439,"endOffset":8533,"count":0},{"startOffset":8604,"endOffset":8698,"count":0},{"startOffset":8738,"endOffset":9137,"count":139},{"startOffset":8803,"endOffset":8905,"count":0},{"startOffset":8935,"endOffset":8941,"count":56},{"startOffset":8941,"endOffset":9137,"count":83}],"isBlockCoverage":true},{"functionName":"createInterfaceConverter","ranges":[{"startOffset":9164,"endOffset":9399,"count":1}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":9226,"endOffset":9396,"count":2043},{"startOffset":9294,"endOffset":9378,"count":0}],"isBlockCoverage":true},{"functionName":"converters.AlgorithmIdentifier","ranges":[{"startOffset":9434,"endOffset":9600,"count":42104},{"startOffset":9514,"endOffset":9558,"count":2060},{"startOffset":9558,"endOffset":9599,"count":40044}],"isBlockCoverage":true},{"functionName":"converter","ranges":[{"startOffset":10384,"endOffset":10466,"count":4}],"isBlockCoverage":true},{"functionName":"converter","ranges":[{"startOffset":11876,"endOffset":11961,"count":0}],"isBlockCoverage":false},{"functionName":"converter","ranges":[{"startOffset":12276,"endOffset":12360,"count":0}],"isBlockCoverage":false},{"functionName":"converter","ranges":[{"startOffset":12542,"endOffset":12626,"count":0}],"isBlockCoverage":false},{"functionName":"converter","ranges":[{"startOffset":13373,"endOffset":13457,"count":0}],"isBlockCoverage":false},{"functionName":"simpleDomStringKey","ranges":[{"startOffset":13500,"endOffset":13551,"count":18}],"isBlockCoverage":true},{"functionName":"converter","ranges":[{"startOffset":15299,"endOffset":15383,"count":8}],"isBlockCoverage":true},{"functionName":"converter","ranges":[{"startOffset":15693,"endOffset":15778,"count":8}],"isBlockCoverage":true},{"functionName":"converter","ranges":[{"startOffset":16294,"endOffset":16367,"count":0}],"isBlockCoverage":false},{"functionName":"converter","ranges":[{"startOffset":16728,"endOffset":16801,"count":0}],"isBlockCoverage":false}]},{"scriptId":"243","url":"node:internal/crypto/aes","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8645,"count":1}],"isBlockCoverage":false},{"functionName":"getAlgorithmName","ranges":[{"startOffset":1271,"endOffset":1510,"count":4},{"startOffset":1335,"endOffset":1374,"count":0},{"startOffset":1379,"endOffset":1418,"count":0},{"startOffset":1467,"endOffset":1504,"count":0}],"isBlockCoverage":true},{"functionName":"validateKeyLength","ranges":[{"startOffset":1512,"endOffset":1671,"count":19},{"startOffset":1611,"endOffset":1669,"count":0}],"isBlockCoverage":true},{"functionName":"getVariant","ranges":[{"startOffset":1673,"endOffset":2576,"count":2006},{"startOffset":1731,"endOffset":1938,"count":0},{"startOffset":1943,"endOffset":2150,"count":0},{"startOffset":2203,"endOffset":2243,"count":0},{"startOffset":2252,"endOffset":2292,"count":0},{"startOffset":2349,"endOffset":2362,"count":0},{"startOffset":2367,"endOffset":2570,"count":0}],"isBlockCoverage":true},{"functionName":"asyncAesCtrCipher","ranges":[{"startOffset":2578,"endOffset":3183,"count":0}],"isBlockCoverage":false},{"functionName":"asyncAesCbcCipher","ranges":[{"startOffset":3185,"endOffset":3460,"count":0}],"isBlockCoverage":false},{"functionName":"asyncAesKwCipher","ranges":[{"startOffset":3462,"endOffset":3673,"count":0}],"isBlockCoverage":false},{"functionName":"asyncAesGcmCipher","ranges":[{"startOffset":3675,"endOffset":5100,"count":2006},{"startOffset":3826,"endOffset":3956,"count":0},{"startOffset":4042,"endOffset":4120,"count":0},{"startOffset":4205,"endOffset":4816,"count":1003},{"startOffset":4316,"endOffset":4343,"count":0},{"startOffset":4620,"endOffset":4751,"count":0},{"startOffset":4821,"endOffset":4890,"count":1003}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":4916,"endOffset":5096,"count":2006}],"isBlockCoverage":true},{"functionName":"aesCipher","ranges":[{"startOffset":5102,"endOffset":5467,"count":2006},{"startOffset":5183,"endOffset":5252,"count":0},{"startOffset":5257,"endOffset":5326,"count":0},{"startOffset":5405,"endOffset":5461,"count":0}],"isBlockCoverage":true},{"functionName":"aesGenerateKey","ranges":[{"startOffset":5469,"endOffset":6414,"count":0}],"isBlockCoverage":false},{"functionName":"aesImportKey","ranges":[{"startOffset":6416,"endOffset":8554,"count":10},{"startOffset":6759,"endOffset":6860,"count":0},{"startOffset":6917,"endOffset":7042,"count":9},{"startOffset":7047,"endOffset":8194,"count":1},{"startOffset":7093,"endOffset":7148,"count":0},{"startOffset":7191,"endOffset":7258,"count":0},{"startOffset":7328,"endOffset":7362,"count":0},{"startOffset":7364,"endOffset":7449,"count":0},{"startOffset":7573,"endOffset":7606,"count":0},{"startOffset":7608,"endOffset":7731,"count":0},{"startOffset":8006,"endOffset":8119,"count":0},{"startOffset":8199,"endOffset":8325,"count":0},{"startOffset":8359,"endOffset":8449,"count":9}],"isBlockCoverage":true}]},{"scriptId":"244","url":"node:internal/crypto/ec","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":7924,"count":1}],"isBlockCoverage":false},{"functionName":"verifyAcceptableEcKeyUse","ranges":[{"startOffset":811,"endOffset":1333,"count":7},{"startOffset":909,"endOffset":996,"count":0},{"startOffset":1041,"endOffset":1053,"count":4},{"startOffset":1054,"endOffset":1064,"count":3},{"startOffset":1083,"endOffset":1185,"count":0},{"startOffset":1227,"endOffset":1331,"count":0}],"isBlockCoverage":true},{"functionName":"createECPublicKeyRaw","ranges":[{"startOffset":1335,"endOffset":1601,"count":1},{"startOffset":1495,"endOffset":1560,"count":0}],"isBlockCoverage":true},{"functionName":"ecGenerateKey","ranges":[{"startOffset":1603,"endOffset":3297,"count":4},{"startOffset":1787,"endOffset":1881,"count":0},{"startOffset":2015,"endOffset":2134,"count":0},{"startOffset":2152,"endOffset":2345,"count":0},{"startOffset":2804,"endOffset":2929,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2441,"endOffset":2593,"count":0}],"isBlockCoverage":false},{"functionName":"ecExportKey","ranges":[{"startOffset":3299,"endOffset":3447,"count":2}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3355,"endOffset":3443,"count":2}],"isBlockCoverage":true},{"functionName":"ecImportKey","ranges":[{"startOffset":3449,"endOffset":7157,"count":7},{"startOffset":3660,"endOffset":3754,"count":0},{"startOffset":3841,"endOffset":4191,"count":0},{"startOffset":4196,"endOffset":4550,"count":0},{"startOffset":4555,"endOffset":6357,"count":6},{"startOffset":4601,"endOffset":4656,"count":0},{"startOffset":4697,"endOffset":4764,"count":0},{"startOffset":4811,"endOffset":4920,"count":0},{"startOffset":5081,"endOffset":5264,"count":0},{"startOffset":5388,"endOffset":5421,"count":0},{"startOffset":5423,"endOffset":5546,"count":0},{"startOffset":5615,"endOffset":6026,"count":0},{"startOffset":6166,"endOffset":6217,"count":0},{"startOffset":6261,"endOffset":6299,"count":3},{"startOffset":6300,"endOffset":6337,"count":3},{"startOffset":6362,"endOffset":6510,"count":1},{"startOffset":6657,"endOffset":6713,"count":0},{"startOffset":6776,"endOffset":6841,"count":0},{"startOffset":6988,"endOffset":7048,"count":0}],"isBlockCoverage":true},{"functionName":"ecdsaSignVerify","ranges":[{"startOffset":7159,"endOffset":7834,"count":7},{"startOffset":7263,"endOffset":7281,"count":3},{"startOffset":7282,"endOffset":7302,"count":4},{"startOffset":7345,"endOffset":7356,"count":3},{"startOffset":7357,"endOffset":7367,"count":4},{"startOffset":7399,"endOffset":7473,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":7545,"endOffset":7830,"count":7}],"isBlockCoverage":true}]},{"scriptId":"245","url":"node:internal/crypto/rsa","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":8570,"count":1}],"isBlockCoverage":false},{"functionName":"verifyAcceptableRsaKeyUse","ranges":[{"startOffset":1159,"endOffset":1758,"count":4},{"startOffset":1301,"endOffset":1325,"count":2},{"startOffset":1326,"endOffset":1352,"count":2},{"startOffset":1371,"endOffset":1386,"count":0},{"startOffset":1413,"endOffset":1502,"count":0},{"startOffset":1507,"endOffset":1609,"count":0},{"startOffset":1651,"endOffset":1756,"count":0}],"isBlockCoverage":true},{"functionName":"rsaOaepCipher","ranges":[{"startOffset":1760,"endOffset":2331,"count":2},{"startOffset":1861,"endOffset":1871,"count":1},{"startOffset":1872,"endOffset":1883,"count":1},{"startOffset":1910,"endOffset":2039,"count":0},{"startOffset":2067,"endOffset":2127,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":2149,"endOffset":2327,"count":2}],"isBlockCoverage":true},{"functionName":"rsaKeyGenerate","ranges":[{"startOffset":2333,"endOffset":4356,"count":4},{"startOffset":2660,"endOffset":2793,"count":0},{"startOffset":2937,"endOffset":3053,"count":0},{"startOffset":3071,"endOffset":3249,"count":0},{"startOffset":3892,"endOffset":4034,"count":0}],"isBlockCoverage":true},{"functionName":"","ranges":[{"startOffset":3379,"endOffset":3531,"count":0}],"isBlockCoverage":false},{"functionName":"rsaExportKey","ranges":[{"startOffset":4358,"endOffset":4546,"count":0}],"isBlockCoverage":false},{"functionName":"rsaImportKey","ranges":[{"startOffset":4548,"endOffset":7497,"count":4},{"startOffset":4726,"endOffset":5087,"count":0},{"startOffset":5092,"endOffset":5457,"count":0},{"startOffset":5508,"endOffset":5563,"count":0},{"startOffset":5606,"endOffset":5673,"count":0},{"startOffset":5845,"endOffset":6042,"count":0},{"startOffset":6166,"endOffset":6199,"count":0},{"startOffset":6201,"endOffset":6324,"count":0},{"startOffset":6517,"endOffset":6630,"count":0},{"startOffset":6766,"endOffset":6817,"count":0},{"startOffset":6862,"endOffset":6900,"count":2},{"startOffset":6901,"endOffset":6938,"count":2},{"startOffset":6964,"endOffset":7090,"count":0},{"startOffset":7141,"endOffset":7207,"count":0}],"isBlockCoverage":true},{"functionName":"rsaSignVerify","ranges":[{"startOffset":7499,"endOffset":8450,"count":0}],"isBlockCoverage":false}]},{"scriptId":"246","url":"file:///home/dmonad/ylabs/lib0/hash/sha256.node.js","functions":[{"functionName":"","ranges":[{"startOffset":0,"endOffset":197,"count":1}],"isBlockCoverage":true},{"functionName":"digest","ranges":[{"startOffset":100,"endOffset":196,"count":20000}],"isBlockCoverage":true}]}],"timestamp":35580.462092} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto.test.d.ts b/nodejs/node_modules/lib0/crypto.test.d.ts new file mode 100644 index 00000000..050692d3 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto.test.d.ts @@ -0,0 +1,9 @@ +export function testJwt(_tc: t.TestCase): Promise; +export function testEncryption(tc: t.TestCase): Promise; +export function testReapeatEncryption(tc: t.TestCase): Promise; +export function testImportExport(tc: t.TestCase): Promise; +export function testEncryptionPerformance(tc: t.TestCase): Promise; +export function testConsistentKeyGeneration(_tc: t.TestCase): Promise; +export function testSigning(tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=crypto.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto.test.d.ts.map b/nodejs/node_modules/lib0/crypto.test.d.ts.map new file mode 100644 index 00000000..7117f006 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.test.d.ts","sourceRoot":"","sources":["crypto.test.js"],"names":[],"mappings":"AAYO,6BAFI,EAAE,QAAQ,iBA8BpB;AAKM,mCAFI,EAAE,QAAQ,iBAoCpB;AAKM,0CAFI,EAAE,QAAQ,iBA8BpB;AAKM,qCAFI,EAAE,QAAQ,iBAgDpB;AAKM,8CAFI,EAAE,QAAQ,iBAwCpB;AAKM,iDAFI,EAAE,QAAQ,iBA2EpB;AAKM,gCAFI,EAAE,QAAQ,iBAapB;mBAvSkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/aes-gcm.d.ts b/nodejs/node_modules/lib0/crypto/aes-gcm.d.ts new file mode 100644 index 00000000..11509cb1 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/aes-gcm.d.ts @@ -0,0 +1,17 @@ +export function encrypt(key: CryptoKey, data: Uint8Array): Promise; +export function decrypt(key: CryptoKey, data: Uint8Array): PromiseLike; +export function importKeyJwk(jwk: any, { usages, extractable }?: { + usages?: Usages | undefined; + extractable?: boolean | undefined; +}): Promise; +export function importKeyRaw(raw: Uint8Array, { usages, extractable }?: { + usages?: Usages | undefined; + extractable?: boolean | undefined; +}): Promise; +export function deriveKey(secret: Uint8Array | string, salt: Uint8Array | string, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export type Usages = Array<'encrypt' | 'decrypt'>; +export { exportKeyJwk, exportKeyRaw } from "./common.js"; +//# sourceMappingURL=aes-gcm.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/aes-gcm.d.ts.map b/nodejs/node_modules/lib0/crypto/aes-gcm.d.ts.map new file mode 100644 index 00000000..d1f309fd --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/aes-gcm.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"aes-gcm.d.ts","sourceRoot":"","sources":["aes-gcm.js"],"names":[],"mappings":"AAuBO,6BAHI,SAAS,QACT,UAAU,uBAkBpB;AAWM,6BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CAclC;AAaM,kCALI,GAAG;IAEW,MAAM;IACL,WAAW;uBAQpC;AAUM,kCALI,UAAU;IAEI,MAAM;IACL,WAAW;uBAG2D;AAmBzF,kCANI,UAAU,GAAC,MAAM,QACjB,UAAU,GAAC,MAAM;IAEF,WAAW;IACZ,MAAM;uBAsB5B;qBAxHU,MAAM,SAAS,GAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/aes-gcm.js b/nodejs/node_modules/lib0/crypto/aes-gcm.js new file mode 100644 index 00000000..b30ec5bc --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/aes-gcm.js @@ -0,0 +1,132 @@ +/** + * AES-GCM is a symmetric key for encryption + */ + +import * as encoding from '../encoding.js' +import * as decoding from '../decoding.js' +import * as webcrypto from 'lib0/webcrypto' +import * as string from '../string.js' +export { exportKeyJwk, exportKeyRaw } from './common.js' + +/** + * @typedef {Array<'encrypt'|'decrypt'>} Usages + */ + +/** + * @type {Usages} + */ +const defaultUsages = ['encrypt', 'decrypt'] + +/** + * @param {CryptoKey} key + * @param {Uint8Array} data + */ +export const encrypt = (key, data) => { + const iv = webcrypto.getRandomValues(new Uint8Array(16)) // 92bit is enough. 128bit is recommended if space is not an issue. + return webcrypto.subtle.encrypt( + { + name: 'AES-GCM', + iv + }, + key, + data + ).then(cipher => { + const encryptedDataEncoder = encoding.createEncoder() + // iv may be sent in the clear to the other peers + encoding.writeUint8Array(encryptedDataEncoder, iv) + encoding.writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher)) + return encoding.toUint8Array(encryptedDataEncoder) + }) +} + +/** + * @experimental The API is not final! + * + * Decrypt some data using AES-GCM method. + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} decrypted buffer + */ +export const decrypt = (key, data) => { + const dataDecoder = decoding.createDecoder(data) + const iv = decoding.readUint8Array(dataDecoder, 16) + const cipher = decoding.readVarUint8Array(dataDecoder) + return webcrypto.subtle.decrypt( + { + name: 'AES-GCM', + iv + }, + key, + cipher + ).then(data => new Uint8Array(data)) +} + +const aesAlgDef = { + name: 'AES-GCM', + length: 256 +} + +/** + * @param {any} jwk + * @param {Object} opts + * @param {Usages} [opts.usages] + * @param {boolean} [opts.extractable] + */ +export const importKeyJwk = (jwk, { usages, extractable = false } = {}) => { + if (usages == null) { + /* c8 ignore next */ + usages = jwk.key_ops || defaultUsages + } + return webcrypto.subtle.importKey('jwk', jwk, 'AES-GCM', extractable, /** @type {Usages} */ (usages)) +} + +/** + * Only suited for importing public keys. + * + * @param {Uint8Array} raw + * @param {Object} opts + * @param {Usages} [opts.usages] + * @param {boolean} [opts.extractable] + */ +export const importKeyRaw = (raw, { usages = defaultUsages, extractable = false } = {}) => + webcrypto.subtle.importKey('raw', raw, aesAlgDef, extractable, /** @type {Usages} */ (usages)) + +/** + * @param {Uint8Array | string} data + */ +/* c8 ignore next */ +const toBinary = data => typeof data === 'string' ? string.encodeUtf8(data) : data + +/** + * @experimental The API is not final! + * + * Derive an symmetric key using the Password-Based-Key-Derivation-Function-2. + * + * @param {Uint8Array|string} secret + * @param {Uint8Array|string} salt + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +export const deriveKey = (secret, salt, { extractable = false, usages = defaultUsages } = {}) => + webcrypto.subtle.importKey( + 'raw', + toBinary(secret), + 'PBKDF2', + false, + ['deriveKey'] + ).then(keyMaterial => + webcrypto.subtle.deriveKey( + { + name: 'PBKDF2', + salt: toBinary(salt), // NIST recommends at least 64 bits + iterations: 600000, // OWASP recommends 600k iterations + hash: 'SHA-256' + }, + keyMaterial, + aesAlgDef, + extractable, + usages + ) + ) diff --git a/nodejs/node_modules/lib0/crypto/common.d.ts b/nodejs/node_modules/lib0/crypto/common.d.ts new file mode 100644 index 00000000..8ab27bbf --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/common.d.ts @@ -0,0 +1,3 @@ +export function exportKeyJwk(key: CryptoKey): Promise; +export function exportKeyRaw(key: CryptoKey): Promise; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/common.d.ts.map b/nodejs/node_modules/lib0/crypto/common.d.ts.map new file mode 100644 index 00000000..13675809 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["common.js"],"names":[],"mappings":"AAKO,kCAFI,SAAS,uBAMnB;AAQM,kCAHI,SAAS,GACR,QAAQ,UAAU,CAAC,CAG0C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/common.js b/nodejs/node_modules/lib0/crypto/common.js new file mode 100644 index 00000000..eaa4390f --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/common.js @@ -0,0 +1,19 @@ +import * as webcrypto from 'lib0/webcrypto' + +/** + * @param {CryptoKey} key + */ +export const exportKeyJwk = async key => { + const jwk = await webcrypto.subtle.exportKey('jwk', key) + jwk.key_ops = key.usages + return jwk +} + +/** + * Only suited for exporting public keys. + * + * @param {CryptoKey} key + * @return {Promise} + */ +export const exportKeyRaw = key => + webcrypto.subtle.exportKey('raw', key).then(key => new Uint8Array(key)) diff --git a/nodejs/node_modules/lib0/crypto/ecdsa.d.ts b/nodejs/node_modules/lib0/crypto/ecdsa.d.ts new file mode 100644 index 00000000..d4dbcd5d --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/ecdsa.d.ts @@ -0,0 +1,17 @@ +export function sign(key: CryptoKey, data: Uint8Array): PromiseLike; +export function verify(key: CryptoKey, signature: Uint8Array, data: Uint8Array): PromiseLike; +export function generateKeyPair({ extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export function importKeyJwk(jwk: any, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export function importKeyRaw(raw: any, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export type Usages = Array<'sign' | 'verify'>; +export { exportKeyJwk, exportKeyRaw } from "./common.js"; +//# sourceMappingURL=ecdsa.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/ecdsa.d.ts.map b/nodejs/node_modules/lib0/crypto/ecdsa.d.ts.map new file mode 100644 index 00000000..5c08e2bb --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/ecdsa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ecdsa.d.ts","sourceRoot":"","sources":["ecdsa.js"],"names":[],"mappings":"AA8BO,0BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CAOa;AAYzC,4BALI,SAAS,aACT,UAAU,QACV,UAAU,GACT,YAAY,OAAO,CAAC,CAQ7B;AAaI;IAHmB,WAAW;IACZ,MAAM;2BAO5B;AAQI,kCALI,GAAG;IAEY,WAAW;IACZ,MAAM;uBAQ9B;AAUM,kCALI,GAAG;IAEY,WAAW;IACZ,MAAM;uBAGmD;qBAxFrE,MAAM,MAAM,GAAC,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/ecdsa.js b/nodejs/node_modules/lib0/crypto/ecdsa.js new file mode 100644 index 00000000..76044a0c --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/ecdsa.js @@ -0,0 +1,97 @@ +/** + * ECDSA is an asymmetric key for signing + */ + +import * as webcrypto from 'lib0/webcrypto' +export { exportKeyJwk, exportKeyRaw } from './common.js' + +/** + * @typedef {Array<'sign'|'verify'>} Usages + */ + +/** + * @type {Usages} + */ +const defaultUsages = ['sign', 'verify'] + +const defaultSignAlgorithm = { + name: 'ECDSA', + hash: 'SHA-384' +} + +/** + * @experimental The API is not final! + * + * Sign a message + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} signature + */ +export const sign = (key, data) => + webcrypto.subtle.sign( + defaultSignAlgorithm, + key, + data + ).then(signature => new Uint8Array(signature)) + +/** + * @experimental The API is not final! + * + * Sign a message + * + * @param {CryptoKey} key + * @param {Uint8Array} signature + * @param {Uint8Array} data + * @return {PromiseLike} signature + */ +export const verify = (key, signature, data) => + webcrypto.subtle.verify( + defaultSignAlgorithm, + key, + signature, + data + ) + +const defaultKeyAlgorithm = { + name: 'ECDSA', + namedCurve: 'P-384' +} + +/* c8 ignore next */ +/** + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +export const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) => + webcrypto.subtle.generateKey( + defaultKeyAlgorithm, + extractable, + usages + ) + +/** + * @param {any} jwk + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +export const importKeyJwk = (jwk, { extractable = false, usages } = {}) => { + if (usages == null) { + /* c8 ignore next 2 */ + usages = jwk.key_ops || defaultUsages + } + return webcrypto.subtle.importKey('jwk', jwk, defaultKeyAlgorithm, extractable, /** @type {Usages} */ (usages)) +} + +/** + * Only suited for importing public keys. + * + * @param {any} raw + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +export const importKeyRaw = (raw, { extractable = false, usages = defaultUsages } = {}) => + webcrypto.subtle.importKey('raw', raw, defaultKeyAlgorithm, extractable, usages) diff --git a/nodejs/node_modules/lib0/crypto/jwt.d.ts b/nodejs/node_modules/lib0/crypto/jwt.d.ts new file mode 100644 index 00000000..0447def9 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/jwt.d.ts @@ -0,0 +1,10 @@ +export function encodeJwt(privateKey: CryptoKey, payload: Object): PromiseLike; +export function verifyJwt(publicKey: CryptoKey, jwt: string): Promise<{ + header: any; + payload: any; +}>; +export function unsafeDecode(jwt: string): { + header: any; + payload: any; +}; +//# sourceMappingURL=jwt.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/jwt.d.ts.map b/nodejs/node_modules/lib0/crypto/jwt.d.ts.map new file mode 100644 index 00000000..96d4eb80 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/jwt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["jwt.js"],"names":[],"mappings":"AAqBO,sCAHI,SAAS,WACT,MAAM,uBAgBhB;AAMM,qCAHI,SAAS,OACT,MAAM;;;GAiBhB;AAOM,kCAFI,MAAM;;;EAQhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/jwt.js b/nodejs/node_modules/lib0/crypto/jwt.js new file mode 100644 index 00000000..cbcc33d9 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/jwt.js @@ -0,0 +1,70 @@ +import * as error from '../error.js' +import * as buffer from '../buffer.js' +import * as string from '../string.js' +import * as json from '../json.js' +import * as ecdsa from '../crypto/ecdsa.js' +import * as time from '../time.js' + +/** + * @param {Object} data + */ +const _stringify = data => buffer.toBase64UrlEncoded(string.encodeUtf8(json.stringify(data))) + +/** + * @param {string} base64url + */ +const _parse = base64url => json.parse(string.decodeUtf8(buffer.fromBase64UrlEncoded(base64url))) + +/** + * @param {CryptoKey} privateKey + * @param {Object} payload + */ +export const encodeJwt = (privateKey, payload) => { + const { name: algName, namedCurve: algCurve } = /** @type {any} */ (privateKey.algorithm) + /* c8 ignore next 3 */ + if (algName !== 'ECDSA' || algCurve !== 'P-384') { + error.unexpectedCase() + } + const header = { + alg: 'ES384', + typ: 'JWT' + } + const jwt = _stringify(header) + '.' + _stringify(payload) + return ecdsa.sign(privateKey, string.encodeUtf8(jwt)).then(signature => + jwt + '.' + buffer.toBase64UrlEncoded(signature) + ) +} + +/** + * @param {CryptoKey} publicKey + * @param {string} jwt + */ +export const verifyJwt = async (publicKey, jwt) => { + const [headerBase64, payloadBase64, signatureBase64] = jwt.split('.') + const verified = await ecdsa.verify(publicKey, buffer.fromBase64UrlEncoded(signatureBase64), string.encodeUtf8(headerBase64 + '.' + payloadBase64)) + /* c8 ignore next 3 */ + if (!verified) { + throw new Error('Invalid JWT') + } + const payload = _parse(payloadBase64) + if (payload.exp != null && time.getUnixTime() > payload.exp) { + throw new Error('Expired JWT') + } + return { + header: _parse(headerBase64), + payload + } +} + +/** + * Decode a jwt without verifying it. Probably a bad idea to use this. Only use if you know the jwt was already verified! + * + * @param {string} jwt + */ +export const unsafeDecode = jwt => { + const [headerBase64, payloadBase64] = jwt.split('.') + return { + header: _parse(headerBase64), + payload: _parse(payloadBase64) + } +} diff --git a/nodejs/node_modules/lib0/crypto/rsa-oaep.d.ts b/nodejs/node_modules/lib0/crypto/rsa-oaep.d.ts new file mode 100644 index 00000000..0a9bde0c --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/rsa-oaep.d.ts @@ -0,0 +1,13 @@ +export { exportKeyJwk } from "./common.js"; +export function encrypt(key: CryptoKey, data: Uint8Array): PromiseLike; +export function decrypt(key: CryptoKey, data: Uint8Array): PromiseLike; +export function generateKeyPair({ extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export function importKeyJwk(jwk: any, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export type Usages = Array<'encrypt' | 'decrypt'>; +//# sourceMappingURL=rsa-oaep.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/rsa-oaep.d.ts.map b/nodejs/node_modules/lib0/crypto/rsa-oaep.d.ts.map new file mode 100644 index 00000000..22fff742 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/rsa-oaep.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rsa-oaep.d.ts","sourceRoot":"","sources":["rsa-oaep.js"],"names":[],"mappings":";AAuBO,6BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CASC;AAW7B,6BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CASG;AAQ/B;IAJmB,WAAW;IACZ,MAAM;IACnB,QAAQ,aAAa,CAAC,CAY/B;AAQI,kCALI,GAAG;IAEY,WAAW;IACZ,MAAM;uBAQ9B;qBAxEY,MAAM,SAAS,GAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/crypto/rsa-oaep.js b/nodejs/node_modules/lib0/crypto/rsa-oaep.js new file mode 100644 index 00000000..82f2fe79 --- /dev/null +++ b/nodejs/node_modules/lib0/crypto/rsa-oaep.js @@ -0,0 +1,81 @@ +/** + * RSA-OAEP is an asymmetric keypair used for encryption + */ + +import * as webcrypto from 'lib0/webcrypto' +export { exportKeyJwk } from './common.js' + +/** + * @typedef {Array<'encrypt'|'decrypt'>} Usages + */ + +/** + * @type {Usages} + */ +const defaultUsages = ['encrypt', 'decrypt'] + +/** + * Note that the max data size is limited by the size of the RSA key. + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} + */ +export const encrypt = (key, data) => + webcrypto.subtle.encrypt( + { + name: 'RSA-OAEP' + }, + key, + data + ).then(buf => new Uint8Array(buf)) + +/** + * @experimental The API is not final! + * + * Decrypt some data using AES-GCM method. + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} decrypted buffer + */ +export const decrypt = (key, data) => + webcrypto.subtle.decrypt( + { + name: 'RSA-OAEP' + }, + key, + data + ).then(data => new Uint8Array(data)) + +/** + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + * @return {Promise} + */ +export const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) => + webcrypto.subtle.generateKey( + { + name: 'RSA-OAEP', + modulusLength: 4096, + publicExponent: new Uint8Array([1, 0, 1]), + hash: 'SHA-256' + }, + extractable, + usages + ) + +/** + * @param {any} jwk + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +export const importKeyJwk = (jwk, { extractable = false, usages } = {}) => { + if (usages == null) { + /* c8 ignore next */ + usages = jwk.key_ops || defaultUsages + } + return webcrypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, extractable, /** @type {Usages} */ (usages)) +} diff --git a/nodejs/node_modules/lib0/decoding.d.ts b/nodejs/node_modules/lib0/decoding.d.ts new file mode 100644 index 00000000..848d8a3f --- /dev/null +++ b/nodejs/node_modules/lib0/decoding.d.ts @@ -0,0 +1,152 @@ +/** + * A Decoder handles the decoding of an Uint8Array. + */ +export class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor(uint8Array: Uint8Array); + /** + * Decoding target. + * + * @type {Uint8Array} + */ + arr: Uint8Array; + /** + * Current decoding position. + * + * @type {number} + */ + pos: number; +} +export function createDecoder(uint8Array: Uint8Array): Decoder; +export function hasContent(decoder: Decoder): boolean; +export function clone(decoder: Decoder, newPos?: number | undefined): Decoder; +export function readUint8Array(decoder: Decoder, len: number): Uint8Array; +export function readVarUint8Array(decoder: Decoder): Uint8Array; +export function readTailAsUint8Array(decoder: Decoder): Uint8Array; +export function skip8(decoder: Decoder): number; +export function readUint8(decoder: Decoder): number; +export function readUint16(decoder: Decoder): number; +export function readUint32(decoder: Decoder): number; +export function readUint32BigEndian(decoder: Decoder): number; +export function peekUint8(decoder: Decoder): number; +export function peekUint16(decoder: Decoder): number; +export function peekUint32(decoder: Decoder): number; +export function readVarUint(decoder: Decoder): number; +export function readVarInt(decoder: Decoder): number; +export function peekVarUint(decoder: Decoder): number; +export function peekVarInt(decoder: Decoder): number; +export function _readVarStringPolyfill(decoder: Decoder): string; +export function _readVarStringNative(decoder: Decoder): string; +export function readVarString(decoder: Decoder): string; +export function readTerminatedUint8Array(decoder: Decoder): Uint8Array; +export function readTerminatedString(decoder: Decoder): string; +export function peekVarString(decoder: Decoder): string; +export function readFromDataView(decoder: Decoder, len: number): DataView; +export function readFloat32(decoder: Decoder): number; +export function readFloat64(decoder: Decoder): number; +export function readBigInt64(decoder: Decoder): any; +export function readBigUint64(decoder: Decoder): any; +export function readAny(decoder: Decoder): any; +/** + * T must not be null. + * + * @template T + */ +export class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor(uint8Array: Uint8Array, reader: (arg0: Decoder) => T); + /** + * The reader + */ + reader: (arg0: Decoder) => T; + /** + * Current state + * @type {T|null} + */ + s: T | null; + count: number; + read(): T; +} +export class IntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor(uint8Array: Uint8Array, start: number); + /** + * Current state + * @type {number} + */ + s: number; + /** + * @return {number} + */ + read(): number; +} +export class RleIntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor(uint8Array: Uint8Array, start: number); + /** + * Current state + * @type {number} + */ + s: number; + count: number; + /** + * @return {number} + */ + read(): number; +} +export class UintOptRleDecoder extends Decoder { + /** + * @type {number} + */ + s: number; + count: number; + read(): number; +} +export class IncUintOptRleDecoder extends Decoder { + /** + * @type {number} + */ + s: number; + count: number; + read(): number; +} +export class IntDiffOptRleDecoder extends Decoder { + /** + * @type {number} + */ + s: number; + count: number; + diff: number; + /** + * @return {number} + */ + read(): number; +} +export class StringDecoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor(uint8Array: Uint8Array); + decoder: UintOptRleDecoder; + str: string; + /** + * @type {number} + */ + spos: number; + /** + * @return {string} + */ + read(): string; +} +//# sourceMappingURL=decoding.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/decoding.d.ts.map b/nodejs/node_modules/lib0/decoding.d.ts.map new file mode 100644 index 00000000..e70ffb9d --- /dev/null +++ b/nodejs/node_modules/lib0/decoding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding.d.ts","sourceRoot":"","sources":["decoding.js"],"names":[],"mappings":"AAsCA;;GAEG;AACH;IACE;;OAEG;IACH,wBAFW,UAAU,EAepB;IAZC;;;;OAIG;IACH,KAFU,UAAU,CAEC;IACrB;;;;OAIG;IACH,KAFU,MAAM,CAEJ;CAEf;AAOM,0CAHI,UAAU,GACT,OAAO,CAE+C;AAO3D,oCAHI,OAAO,GACN,OAAO,CAEoD;AAWhE,+BAJI,OAAO,gCAEN,OAAO,CAMlB;AAaM,wCAJI,OAAO,OACP,MAAM,GACL,UAAU,CAMrB;AAYM,2CAHI,OAAO,GACN,UAAU,CAEmE;AAQlF,8CAHI,OAAO,GACN,UAAU,CAEkF;AAQjG,+BAHI,OAAO,GACN,MAAM,CAE2B;AAQtC,mCAHI,OAAO,GACN,MAAM,CAE4C;AASvD,oCAHI,OAAO,GACN,MAAM,CAQjB;AASM,oCAHI,OAAO,GACN,MAAM,CAUjB;AAUM,6CAHI,OAAO,GACN,MAAM,CAUjB;AAUM,mCAHI,OAAO,GACN,MAAM,CAE0C;AAUrD,oCAHI,OAAO,GACN,MAAM,CAImB;AAU9B,oCAHI,OAAO,GACN,MAAM,CAOX;AAYA,qCA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,QAFY,MAAM,CAgBjB;CACF;AAED;IACE;;OAEG;IACH,wBAFW,UAAU,EASpB;IANC,2BAAgD;IAChD,YAAsC;IACtC;;OAEG;IACH,MAFU,MAAM,CAEH;IAGf;;OAEG;IACH,QAFY,MAAM,CAOjB;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/decoding.js b/nodejs/node_modules/lib0/decoding.js new file mode 100644 index 00000000..c88f9f12 --- /dev/null +++ b/nodejs/node_modules/lib0/decoding.js @@ -0,0 +1,706 @@ +/** + * Efficient schema-less binary decoding with support for variable length encoding. + * + * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module decoding + */ + +import * as binary from './binary.js' +import * as math from './math.js' +import * as number from './number.js' +import * as string from './string.js' +import * as error from './error.js' +import * as encoding from './encoding.js' + +const errorUnexpectedEndOfArray = error.create('Unexpected end of array') +const errorIntegerOutOfRange = error.create('Integer out of Range') + +/** + * A Decoder handles the decoding of an Uint8Array. + */ +export class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor (uint8Array) { + /** + * Decoding target. + * + * @type {Uint8Array} + */ + this.arr = uint8Array + /** + * Current decoding position. + * + * @type {number} + */ + this.pos = 0 + } +} + +/** + * @function + * @param {Uint8Array} uint8Array + * @return {Decoder} + */ +export const createDecoder = uint8Array => new Decoder(uint8Array) + +/** + * @function + * @param {Decoder} decoder + * @return {boolean} + */ +export const hasContent = decoder => decoder.pos !== decoder.arr.length + +/** + * Clone a decoder instance. + * Optionally set a new position parameter. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} [newPos] Defaults to current position + * @return {Decoder} A clone of `decoder` + */ +export const clone = (decoder, newPos = decoder.pos) => { + const _decoder = createDecoder(decoder.arr) + _decoder.pos = newPos + return _decoder +} + +/** + * Create an Uint8Array view of the next `len` bytes and advance the position by `len`. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} len The length of bytes to read + * @return {Uint8Array} + */ +export const readUint8Array = (decoder, len) => { + const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len) + decoder.pos += len + return view +} + +/** + * Read variable length Uint8Array. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ +export const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder)) + +/** + * Read the rest of the content as an ArrayBuffer + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ +export const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos) + +/** + * Skip one byte, jump to the next position. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} The next position + */ +export const skip8 = decoder => decoder.pos++ + +/** + * Read one byte as unsigned integer. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} Unsigned 8-bit integer + */ +export const readUint8 = decoder => decoder.arr[decoder.pos++] + +/** + * Read 2 bytes as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +export const readUint16 = decoder => { + const uint = + decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8) + decoder.pos += 2 + return uint +} + +/** + * Read 4 bytes as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +export const readUint32 = decoder => { + const uint = + (decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8) + + (decoder.arr[decoder.pos + 2] << 16) + + (decoder.arr[decoder.pos + 3] << 24)) >>> 0 + decoder.pos += 4 + return uint +} + +/** + * Read 4 bytes as unsigned integer in big endian order. + * (most significant byte first) + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +export const readUint32BigEndian = decoder => { + const uint = + (decoder.arr[decoder.pos + 3] + + (decoder.arr[decoder.pos + 2] << 8) + + (decoder.arr[decoder.pos + 1] << 16) + + (decoder.arr[decoder.pos] << 24)) >>> 0 + decoder.pos += 4 + return uint +} + +/** + * Look ahead without incrementing the position + * to the next byte and read it as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +export const peekUint8 = decoder => decoder.arr[decoder.pos] + +/** + * Look ahead without incrementing the position + * to the next byte and read it as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +export const peekUint16 = decoder => + decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8) + +/** + * Look ahead without incrementing the position + * to the next byte and read it as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +export const peekUint32 = decoder => ( + decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8) + + (decoder.arr[decoder.pos + 2] << 16) + + (decoder.arr[decoder.pos + 3] << 24) +) >>> 0 + +/** + * Read unsigned integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ +export const readVarUint = decoder => { + let num = 0 + let mult = 1 + const len = decoder.arr.length + while (decoder.pos < len) { + const r = decoder.arr[decoder.pos++] + // num = num | ((r & binary.BITS7) << len) + num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num + mult *= 128 // next iteration, shift 7 "more" to the left + if (r < binary.BIT8) { + return num + } + /* c8 ignore start */ + if (num > number.MAX_SAFE_INTEGER) { + throw errorIntegerOutOfRange + } + /* c8 ignore stop */ + } + throw errorUnexpectedEndOfArray +} + +/** + * Read signed integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ +export const readVarInt = decoder => { + let r = decoder.arr[decoder.pos++] + let num = r & binary.BITS6 + let mult = 64 + const sign = (r & binary.BIT7) > 0 ? -1 : 1 + if ((r & binary.BIT8) === 0) { + // don't continue reading + return sign * num + } + const len = decoder.arr.length + while (decoder.pos < len) { + r = decoder.arr[decoder.pos++] + // num = num | ((r & binary.BITS7) << len) + num = num + (r & binary.BITS7) * mult + mult *= 128 + if (r < binary.BIT8) { + return sign * num + } + /* c8 ignore start */ + if (num > number.MAX_SAFE_INTEGER) { + throw errorIntegerOutOfRange + } + /* c8 ignore stop */ + } + throw errorUnexpectedEndOfArray +} + +/** + * Look ahead and read varUint without incrementing position + * + * @function + * @param {Decoder} decoder + * @return {number} + */ +export const peekVarUint = decoder => { + const pos = decoder.pos + const s = readVarUint(decoder) + decoder.pos = pos + return s +} + +/** + * Look ahead and read varUint without incrementing position + * + * @function + * @param {Decoder} decoder + * @return {number} + */ +export const peekVarInt = decoder => { + const pos = decoder.pos + const s = readVarInt(decoder) + decoder.pos = pos + return s +} + +/** + * We don't test this function anymore as we use native decoding/encoding by default now. + * Better not modify this anymore.. + * + * Transforming utf8 to a string is pretty expensive. The code performs 10x better + * when String.fromCodePoint is fed with all characters as arguments. + * But most environments have a maximum number of arguments per functions. + * For effiency reasons we apply a maximum of 10000 characters at once. + * + * @function + * @param {Decoder} decoder + * @return {String} The read String. + */ +/* c8 ignore start */ +export const _readVarStringPolyfill = decoder => { + let remainingLen = readVarUint(decoder) + if (remainingLen === 0) { + return '' + } else { + let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen + if (--remainingLen < 100) { // do not create a Uint8Array for small strings + while (remainingLen--) { + encodedString += String.fromCodePoint(readUint8(decoder)) + } + } else { + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000 + // this is dangerous, we create a fresh array view from the existing buffer + const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen) + decoder.pos += nextLen + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)) + remainingLen -= nextLen + } + } + return decodeURIComponent(escape(encodedString)) + } +} +/* c8 ignore stop */ + +/** + * @function + * @param {Decoder} decoder + * @return {String} The read String + */ +export const _readVarStringNative = decoder => + /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder)) + +/** + * Read string of variable length + * * varUint is used to store the length of the string + * + * @function + * @param {Decoder} decoder + * @return {String} The read String + * + */ +/* c8 ignore next */ +export const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill + +/** + * @param {Decoder} decoder + * @return {Uint8Array} + */ +export const readTerminatedUint8Array = decoder => { + const encoder = encoding.createEncoder() + let b + while (true) { + b = readUint8(decoder) + if (b === 0) { + return encoding.toUint8Array(encoder) + } + if (b === 1) { + b = readUint8(decoder) + } + encoding.write(encoder, b) + } +} + +/** + * @param {Decoder} decoder + * @return {string} + */ +export const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder)) + +/** + * Look ahead and read varString without incrementing position + * + * @function + * @param {Decoder} decoder + * @return {string} + */ +export const peekVarString = decoder => { + const pos = decoder.pos + const s = readVarString(decoder) + decoder.pos = pos + return s +} + +/** + * @param {Decoder} decoder + * @param {number} len + * @return {DataView} + */ +export const readFromDataView = (decoder, len) => { + const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len) + decoder.pos += len + return dv +} + +/** + * @param {Decoder} decoder + */ +export const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false) + +/** + * @param {Decoder} decoder + */ +export const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false) + +/** + * @param {Decoder} decoder + */ +export const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false) + +/** + * @param {Decoder} decoder + */ +export const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false) + +/** + * @type {Array} + */ +const readAnyLookupTable = [ + decoder => undefined, // CASE 127: undefined + decoder => null, // CASE 126: null + readVarInt, // CASE 125: integer + readFloat32, // CASE 124: float32 + readFloat64, // CASE 123: float64 + readBigInt64, // CASE 122: bigint + decoder => false, // CASE 121: boolean (false) + decoder => true, // CASE 120: boolean (true) + readVarString, // CASE 119: string + decoder => { // CASE 118: object + const len = readVarUint(decoder) + /** + * @type {Object} + */ + const obj = {} + for (let i = 0; i < len; i++) { + const key = readVarString(decoder) + obj[key] = readAny(decoder) + } + return obj + }, + decoder => { // CASE 117: array + const len = readVarUint(decoder) + const arr = [] + for (let i = 0; i < len; i++) { + arr.push(readAny(decoder)) + } + return arr + }, + readVarUint8Array // CASE 116: Uint8Array +] + +/** + * @param {Decoder} decoder + */ +export const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder) + +/** + * T must not be null. + * + * @template T + */ +export class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor (uint8Array, reader) { + super(uint8Array) + /** + * The reader + */ + this.reader = reader + /** + * Current state + * @type {T|null} + */ + this.s = null + this.count = 0 + } + + read () { + if (this.count === 0) { + this.s = this.reader(this) + if (hasContent(this)) { + this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented + } else { + this.count = -1 // read the current value forever + } + } + this.count-- + return /** @type {T} */ (this.s) + } +} + +export class IntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor (uint8Array, start) { + super(uint8Array) + /** + * Current state + * @type {number} + */ + this.s = start + } + + /** + * @return {number} + */ + read () { + this.s += readVarInt(this) + return this.s + } +} + +export class RleIntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor (uint8Array, start) { + super(uint8Array) + /** + * Current state + * @type {number} + */ + this.s = start + this.count = 0 + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + this.s += readVarInt(this) + if (hasContent(this)) { + this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented + } else { + this.count = -1 // read the current value forever + } + } + this.count-- + return /** @type {number} */ (this.s) + } +} + +export class UintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array) + /** + * @type {number} + */ + this.s = 0 + this.count = 0 + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this) + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = math.isNegativeZero(this.s) + this.count = 1 + if (isNegative) { + this.s = -this.s + this.count = readVarUint(this) + 2 + } + } + this.count-- + return /** @type {number} */ (this.s) + } +} + +export class IncUintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array) + /** + * @type {number} + */ + this.s = 0 + this.count = 0 + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this) + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = math.isNegativeZero(this.s) + this.count = 1 + if (isNegative) { + this.s = -this.s + this.count = readVarUint(this) + 2 + } + } + this.count-- + return /** @type {number} */ (this.s++) + } +} + +export class IntDiffOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array) + /** + * @type {number} + */ + this.s = 0 + this.count = 0 + this.diff = 0 + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + const diff = readVarInt(this) + // if the first bit is set, we read more data + const hasCount = diff & 1 + this.diff = math.floor(diff / 2) // shift >> 1 + this.count = 1 + if (hasCount) { + this.count = readVarUint(this) + 2 + } + } + this.s += this.diff + this.count-- + return this.s + } +} + +export class StringDecoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + this.decoder = new UintOptRleDecoder(uint8Array) + this.str = readVarString(this.decoder) + /** + * @type {number} + */ + this.spos = 0 + } + + /** + * @return {string} + */ + read () { + const end = this.spos + this.decoder.read() + const res = this.str.slice(this.spos, end) + this.spos = end + return res + } +} diff --git a/nodejs/node_modules/lib0/deno.json b/nodejs/node_modules/lib0/deno.json new file mode 100644 index 00000000..6e68cf46 --- /dev/null +++ b/nodejs/node_modules/lib0/deno.json @@ -0,0 +1,12 @@ +{ + "imports": { + "isomorphic.js": "./node_modules/isomorphic.js/node.mjs", + "lib0/logging": "./logging.node.js", + "lib0/performance": "./performance.node.js", + "lib0/crypto/aes-gcm": "./crypto/aes-gcm.js", + "lib0/crypto/rsa-oaep": "./crypto/rsa-oaep.js", + "lib0/crypto/ecdsa": "./crypto/ecdsa.js", + "lib0/crypto/jwt": "./crypto/jwt.js", + "lib0/webcrypto": "./webcrypto.deno.js" + } +} diff --git a/nodejs/node_modules/lib0/deno.lock b/nodejs/node_modules/lib0/deno.lock new file mode 100644 index 00000000..794d4eb6 --- /dev/null +++ b/nodejs/node_modules/lib0/deno.lock @@ -0,0 +1,122 @@ +{ + "version": "2", + "remote": { + "https://deno.land/std@0.177.0/_util/asserts.ts": "178dfc49a464aee693a7e285567b3d0b555dc805ff490505a8aae34f9cfb1462", + "https://deno.land/std@0.177.0/_util/os.ts": "d932f56d41e4f6a6093d56044e29ce637f8dcc43c5a90af43504a889cf1775e3", + "https://deno.land/std@0.177.0/bytes/index_of_needle.ts": "65c939607df609374c4415598fa4dad04a2f14c4d98cd15775216f0aaf597f24", + "https://deno.land/std@0.177.0/crypto/_wasm/lib/deno_std_wasm_crypto.generated.mjs": "5dedb7f9aa05f0e18ed017691c58df5f4686e4cbbd70368c6f896e5cca03f2b4", + "https://deno.land/std@0.177.0/crypto/_wasm/mod.ts": "e2df88236fc061eac7a89e8cb0b97843f5280b08b2a990e473b7397a3e566003", + "https://deno.land/std@0.177.0/crypto/timing_safe_equal.ts": "8d69ab611c67fe51b6127d97fcfb4d8e7d0e1b6b4f3e0cc4ab86744c3691f965", + "https://deno.land/std@0.177.0/encoding/base64.ts": "7de04c2f8aeeb41453b09b186480be90f2ff357613b988e99fabb91d2eeceba1", + "https://deno.land/std@0.177.0/encoding/base64url.ts": "3f1178f6446834457b16bfde8b559c1cd3481727fe384d3385e4a9995dc2d851", + "https://deno.land/std@0.177.0/encoding/hex.ts": "50f8c95b52eae24395d3dfcb5ec1ced37c5fe7610ef6fffdcc8b0fdc38e3b32f", + "https://deno.land/std@0.177.0/flags/mod.ts": "d1cdefa18472ef69858a17df5cf7c98445ed27ac10e1460183081303b0ebc270", + "https://deno.land/std@0.177.0/node/_core.ts": "9a58c0ef98ee77e9b8fcc405511d1b37a003a705eb6a9b6e95f75434d8009adc", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/base/buffer.js": "c9364c761681134015ec8ba6f33b39c067d6e5dd59860d55face8d5be8522744", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/base/node.js": "8f7f23bfa300990bbd6db7e7395e9688b54a04e3eb2fab5cab9a9a72e26c525f", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/base/reporter.js": "788aec7662991da549e5f7f3edbc3e3d6c6cecabc894b18d1a705b0f204e06c3", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/constants/der.js": "57181db0519bb3864a6cdf4e7eb9bfeb1bf5f80605187fbe80e27083b473e367", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/decoders/der.js": "fdc4de98c9b0b59db169a2b225895741e2ab34b00e14315ac2ff5e389d6db16e", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/decoders/pem.js": "fd7f0072c193c82959fec0374f4fd3adf3f4ac38594fd404d66b3e8724107151", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/encoders/der.js": "137bc4f8fe66b9950c743025e199789e25342f791e2d52353ceb016ad2854b42", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/encoders/pem.js": "e43bc706973c4c27e1e2f96262daba3d38822cb10f5b494f6944c726ee655160", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/asn1.js/mod.js": "1f88293688296be7a6c735bd8ea39425f5b274b94db1d6b7968dddfb54ac9d37", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/bn.js/bn.js": "f3f3c1dae1aa55de9e6472af1d6bec5ccda4b4890ee5c52a90961137fe99564e", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/aes.js": "698e1ed386b7dff27b2d59fa1c75f506beceec96b78670a15a734e438c08f138", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/auth_cipher.js": "5c245b5685b066356a7c9529a3a441bf5f57823a6946ce1b0ef2e1af32bb76f4", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/decrypter.js": "39152b2b3409893b8548feeab7e5997ceb1595f31df0dedaf765708be8f025c0", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/encrypter.js": "f9cc703d5a7b5255999c1a3600fbf48ff564b65f827744877526803093ceebff", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/ghash.js": "759d80b760f44cd3a454b4f161fd03a7d6c359901446f0a907a6870cb66d6767", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/incr32.js": "2bdea27b74b3990ee56807a1a5abe335f118826beabeeb905459c8768094b28f", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/mod.js": "fe4affebbd210d885b2e5135c668751f9d10bc14aa0cc3905cbfff66f04b4c58", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/cbc.js": "ff24b4506522a724ba7a03c1403ad8938aba45056f9fd47c7f0b4fcb3a640adf", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/cfb.js": "643720a1db969b6bcc896c95523630838a8335513d02f340514fd524bb4113cb", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/cfb1.js": "01c9a46aa3affd84a54ae33652fb0fa0ff7c862be2a459d9cb188cb8e2c4b11e", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/cfb8.js": "97476cee25103e02a02b196d7fe6f28a9f0f9e47ee344687d7492bc7282a59f8", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/ctr.js": "1e3835adb753cfe6761e4df8c43d190e31e1ca6a586fd582747c8255c82ed78d", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/ecb.js": "79677b96d4af50c49f0a4f698e5c7e5a64f1d2926b799e0d2eac2cdd5ec7488c", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/mod.js": "fe3db429b867a0a8066c64d7b33b840a1f24cad9174156384a763733f68cf518", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/modes/ofb.js": "3553308f98d078e2006eac39bb6d91818f8bb376b01d962ae98eabf6ee79ad4e", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/stream_cipher.js": "70f50f37ddec530ae95911ca2f286ebd2ddbd54d914ab0be461ec1dc3c61990f", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_aes/xor.ts": "7132baacdb39ba82c3bfe325a60e68ca87469c0ed0cdd0508caf6f40bab852b8", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/browserify_rsa.js": "96e0e4fee7c2cf75ef86d958c709bfc239297a080fd17ace5ea5ab699a1b6174", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/cipher_base.js": "9ebc6ccc364cf7b23024821054d2e72a2d8da8d8a2a36cacdc5aa6cc6770ef93", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/evp_bytes_to_key.ts": "7c4c27b6e321b2d7065a6703d90264921e9a805d91d9dfdb21103393228024e2", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/parse_asn1/asn1.js": "7d99b6df508164169a33377346e8840d519fe2defccb362a023c92c5bd503433", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/parse_asn1/certificate.js": "5795348417b3ec7aafa4854ba55f364e0148eadfdd29d1566c90e617237621bb", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/parse_asn1/fix_proc.js": "858dd3e6ce264d75822cadc21bb55114f4e4867a706abde1663548aa2710fc1b", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/parse_asn1/mod.js": "ea164fbd497ce3d710426742d4b72f71da8954c4ebaeb7eadc33316c5b0060f1", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/public_encrypt/mgf.js": "dfac5008a550b3e7e6b851c4fb42e984aa9e7fae64707888f47f2aa0991c004d", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/public_encrypt/mod.js": "0704326ff3ee2bb0764a964995d1aa62b1147b714ad5465e878ba4d57731e3db", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/public_encrypt/private_decrypt.js": "8a1d11edb176d95d1e3bdf1aff5c3248a986bf9734d1a6b07508e29132d2f65c", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/public_encrypt/public_encrypt.js": "f88b0e3c228d84096fdbc03e614e86bef86e56013cb9628b2425e31b3b142b2c", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/public_encrypt/with_public.js": "752da754d253b5743d89c0f2432b6eb6f8815b80efd9ee588683e10a13d34400", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/public_encrypt/xor.js": "087ebef8f6fcb8ca4c7216cc22de728d9a61ec27b9a036b900681ff25d6409af", + "https://deno.land/std@0.177.0/node/_crypto/crypto_browserify/randombytes.ts": "23bde8be640e274d7bb88cf10d1da8bba252654252dc6a877fed86a77da5952c", + "https://deno.land/std@0.177.0/node/_events.d.ts": "1347437fd6b084d7c9a4e16b9fe7435f00b030970086482edeeb3b179d0775af", + "https://deno.land/std@0.177.0/node/_events.mjs": "d4ba4e629abe3db9f1b14659fd5c282b7da8b2b95eaf13238eee4ebb142a2448", + "https://deno.land/std@0.177.0/node/_global.d.ts": "2d88342f38b4083b858998e27c706725fb03a74aa14ef8d985dc18438b5188e4", + "https://deno.land/std@0.177.0/node/_next_tick.ts": "9a3cf107d59b019a355d3cf32275b4c6157282e4b68ea85b46a799cb1d379305", + "https://deno.land/std@0.177.0/node/_process/exiting.ts": "6e336180aaabd1192bf99ffeb0d14b689116a3dec1dfb34a2afbacd6766e98ab", + "https://deno.land/std@0.177.0/node/_process/process.ts": "c96bb1f6253824c372f4866ee006dcefda02b7050d46759736e403f862d91051", + "https://deno.land/std@0.177.0/node/_process/stdio.mjs": "cf17727eac8da3a665851df700b5aca6a12bacc3ebbf33e63e4b919f80ba44a6", + "https://deno.land/std@0.177.0/node/_stream.d.ts": "112e1a0677cd6db932c3ce0e6e5bbdc7a2ac1874572f449044ecc82afcf5ee2e", + "https://deno.land/std@0.177.0/node/_stream.mjs": "d6e2c86c1158ac65b4c2ca4fa019d7e84374ff12e21e2175345fe68c0823efe3", + "https://deno.land/std@0.177.0/node/_utils.ts": "7fd55872a0cf9275e3c080a60e2fa6d45b8de9e956ebcde9053e72a344185884", + "https://deno.land/std@0.177.0/node/buffer.ts": "85617be2063eccaf177dbb84c7580d1e32023724ed14bd9df4e453b152a26167", + "https://deno.land/std@0.177.0/node/crypto.ts": "2c94fa0f76e90190fbc34df891dc5c284bddb86c932fae8ac11747de3f75293c", + "https://deno.land/std@0.177.0/node/events.ts": "d2de352d509de11a375e2cb397d6b98f5fed4e562fc1d41be33214903a38e6b0", + "https://deno.land/std@0.177.0/node/internal/buffer.d.ts": "bdfa991cd88cb02fd08bf8235d2618550e3e511c970b2a8f2e1a6885a2793cac", + "https://deno.land/std@0.177.0/node/internal/buffer.mjs": "e92303a3cc6d9aaabcd270a937ad9319825d9ba08cb332650944df4562029b27", + "https://deno.land/std@0.177.0/node/internal/crypto/_keys.ts": "8f3c3b5a141aa0331a53c205e9338655f1b3b307a08085fd6ff6dda6f7c4190b", + "https://deno.land/std@0.177.0/node/internal/crypto/_randomBytes.ts": "36dd164747f73b830ba86562abb160a8ac5bea34aaeb816a67f3005a00d41177", + "https://deno.land/std@0.177.0/node/internal/crypto/_randomFill.ts": "297186f290eba87a1ad7b8aa42a960ff4278a8b6b0c963fa81918c326d5c0b58", + "https://deno.land/std@0.177.0/node/internal/crypto/_randomInt.ts": "6cf19da9684b67520e67a2d99f2581a3f841140842c7ce2e014d166457550fe1", + "https://deno.land/std@0.177.0/node/internal/crypto/certificate.ts": "b4a6695f82e70a42e85247c74a7691ed4b3a904646451af0287e49efe1a28814", + "https://deno.land/std@0.177.0/node/internal/crypto/cipher.ts": "2bae9b4d94c465e4d1c70e5a9e8fd67ce20bcc66fecd2eec6be00d35144ca4eb", + "https://deno.land/std@0.177.0/node/internal/crypto/constants.ts": "544d605703053218499b08214f2e25cf4310651d535b7ab995891c4b7a217693", + "https://deno.land/std@0.177.0/node/internal/crypto/diffiehellman.ts": "9cfb219c5b2936db773f559b6affe6d25b0e40531010389f05df3f05ce7eebf5", + "https://deno.land/std@0.177.0/node/internal/crypto/hash.ts": "d01f5d3ad5477655b432036d2d553c7a0c31a901ac0e1e9e0d8b3975daae7624", + "https://deno.land/std@0.177.0/node/internal/crypto/hkdf.ts": "5bd801234e56468fbd47466f46e88bdadc66432d625e3616abe38878d410bb66", + "https://deno.land/std@0.177.0/node/internal/crypto/keygen.ts": "530cc1a00acf71a43719bb876a2dc563b6196095d080eba77c92c9f39658a5b9", + "https://deno.land/std@0.177.0/node/internal/crypto/keys.ts": "c4dfa5aa3420cf700178b87203593a0989c8a93934bfef2b29adb3399d687958", + "https://deno.land/std@0.177.0/node/internal/crypto/pbkdf2.ts": "0a0a3e0d3d45db0638fe75a4199c7ed7ca2164405750a520e786e4adebdb45a4", + "https://deno.land/std@0.177.0/node/internal/crypto/random.ts": "85f3147e14cb45c18e016da45d319a5c663309411232a956fdc09c2317acdd9f", + "https://deno.land/std@0.177.0/node/internal/crypto/scrypt.ts": "b55a0fcd12b295af4127d05b1c0bc3098b74fc0e3c62321c2a43c20f9ed18209", + "https://deno.land/std@0.177.0/node/internal/crypto/sig.ts": "25819a89d49c1ebfe3baa1f9464501ec599a36cf53e9b600ec0399e568b9dccc", + "https://deno.land/std@0.177.0/node/internal/crypto/types.ts": "52feb182bcbd59206f3e2f4a3cb8a5775d4452c2a8045c3e613e2178d32c2a86", + "https://deno.land/std@0.177.0/node/internal/crypto/util.ts": "db282c0413aeee28bc0665fcfc1c08a65fc96dc12ed4d03282f2da4907fcf0ce", + "https://deno.land/std@0.177.0/node/internal/crypto/x509.ts": "0e8a541c4f58ecb83862c373d3f7d2371aa8f5108f55bc837b190c4ab3408764", + "https://deno.land/std@0.177.0/node/internal/error_codes.ts": "8495e33f448a484518d76fa3d41d34fc20fe03c14b30130ad8e936b0035d4b8b", + "https://deno.land/std@0.177.0/node/internal/errors.ts": "1c699b8a3cb93174f697a348c004b1c6d576b66688eac8a48ebb78e65c720aae", + "https://deno.land/std@0.177.0/node/internal/fixed_queue.ts": "62bb119afa5b5ae8fc0c7048b50502347bec82e2588017d0b250c4671d6eff8f", + "https://deno.land/std@0.177.0/node/internal/hide_stack_frames.ts": "9dd1bad0a6e62a1042ce3a51eb1b1ecee2f246907bff44835f86e8f021de679a", + "https://deno.land/std@0.177.0/node/internal/normalize_encoding.mjs": "fd1d9df61c44d7196432f6e8244621468715131d18cc79cd299fc78ac549f707", + "https://deno.land/std@0.177.0/node/internal/options.ts": "888f267c3fe8f18dc7b2f2fbdbe7e4a0fd3302ff3e99f5d6645601e924f3e3fb", + "https://deno.land/std@0.177.0/node/internal/primordials.mjs": "a72d86b5aa55d3d50b8e916b6a59b7cc0dc5a31da8937114b4a113ad5aa08c74", + "https://deno.land/std@0.177.0/node/internal/streams/destroy.mjs": "b665fc71178919a34ddeac8389d162a81b4bc693ff7dc2557fa41b3a91011967", + "https://deno.land/std@0.177.0/node/internal/streams/end-of-stream.mjs": "a4fb1c2e32d58dff440d4e716e2c4daaa403b3095304a028bb428575cfeed716", + "https://deno.land/std@0.177.0/node/internal/streams/utils.mjs": "f2fe2e6bdc506da24c758970890cc2a21642045b129dee618bd3827c60dd9e33", + "https://deno.land/std@0.177.0/node/internal/streams/writable.mjs": "775928726d0483ace8e45a35f30db2019a22dd7b9a81b67b158420e21cc692c5", + "https://deno.land/std@0.177.0/node/internal/util.mjs": "f7fe2e1ca5e66f550ad0856b9f5ee4d666f0c071fe212ea7fc7f37cfa81f97a5", + "https://deno.land/std@0.177.0/node/internal/util/inspect.mjs": "11d7c9cab514b8e485acc3978c74b837263ff9c08ae4537fa18ad56bae633259", + "https://deno.land/std@0.177.0/node/internal/util/types.ts": "0e587b44ec5e017cf228589fc5ce9983b75beece6c39409c34170cfad49d6417", + "https://deno.land/std@0.177.0/node/internal/validators.mjs": "e02f2b02dd072a5d623970292588d541204dc82207b4c58985d933a5f4b382e6", + "https://deno.land/std@0.177.0/node/internal_binding/_libuv_winerror.ts": "30c9569603d4b97a1f1a034d88a3f74800d5ea1f12fcc3d225c9899d4e1a518b", + "https://deno.land/std@0.177.0/node/internal_binding/_node.ts": "cb2389b0eab121df99853eb6a5e3a684e4537e065fb8bf2cca0cbf219ce4e32e", + "https://deno.land/std@0.177.0/node/internal_binding/_timingSafeEqual.ts": "7d9732464d3c669ff07713868ce5d25bc974a06112edbfb5f017fc3c70c0853e", + "https://deno.land/std@0.177.0/node/internal_binding/_utils.ts": "7c58a2fbb031a204dee9583ba211cf9c67922112fe77e7f0b3226112469e9fe1", + "https://deno.land/std@0.177.0/node/internal_binding/_winerror.ts": "3e8cfdfe22e89f13d2b28529bab35155e6b1730c0221ec5a6fc7077dc037be13", + "https://deno.land/std@0.177.0/node/internal_binding/buffer.ts": "31729e0537921d6c730ad0afea44a7e8a0a1044d070ade8368226cb6f7390c8b", + "https://deno.land/std@0.177.0/node/internal_binding/constants.ts": "21ff9d1ee71d0a2086541083a7711842fc6ae25e264dbf45c73815aadce06f4c", + "https://deno.land/std@0.177.0/node/internal_binding/crypto.ts": "29e8f94f283a2e7d4229d3551369c6a40c2af9737fad948cb9be56bef6c468cd", + "https://deno.land/std@0.177.0/node/internal_binding/node_options.ts": "0b5cb0bf4379a39278d7b7bb6bb2c2751baf428fe437abe5ed3e8441fae1f18b", + "https://deno.land/std@0.177.0/node/internal_binding/string_decoder.ts": "54c3c1cbd5a9254881be58bf22637965dc69535483014dab60487e299cb95445", + "https://deno.land/std@0.177.0/node/internal_binding/types.ts": "2187595a58d2cf0134f4db6cc2a12bf777f452f52b15b6c3aed73fa072aa5fc3", + "https://deno.land/std@0.177.0/node/internal_binding/util.ts": "808ff3b92740284184ab824adfc420e75398c88c8bccf5111f0c24ac18c48f10", + "https://deno.land/std@0.177.0/node/internal_binding/uv.ts": "eb0048e30af4db407fb3f95563e30d70efd6187051c033713b0a5b768593a3a3", + "https://deno.land/std@0.177.0/node/perf_hooks.ts": "c20e1f02f463e065e8f6c1d4fa97b0d3832dc0db5b5d8ea37f99a962ecf11f35", + "https://deno.land/std@0.177.0/node/stream.ts": "09e348302af40dcc7dc58aa5e40fdff868d11d8d6b0cfb85cbb9c75b9fe450c7", + "https://deno.land/std@0.177.0/node/string_decoder.ts": "1a17e3572037c512cc5fc4b29076613e90f225474362d18da908cb7e5ccb7e88" + } +} diff --git a/nodejs/node_modules/lib0/diff.d.ts b/nodejs/node_modules/lib0/diff.d.ts new file mode 100644 index 00000000..7f9023c4 --- /dev/null +++ b/nodejs/node_modules/lib0/diff.d.ts @@ -0,0 +1,37 @@ +export function simpleDiffString(a: string, b: string): SimpleDiff; +export function simpleDiff(a: string, b: string): SimpleDiff; +export function simpleDiffArray(a: T[], b: T[], compare?: ((arg0: T, arg1: T) => boolean) | undefined): SimpleDiff; +export function simpleDiffStringWithCursor(a: string, b: string, cursor: number): { + index: number; + remove: number; + insert: string; +}; +/** + * A SimpleDiff describes a change on a String. + * + * ```js + * console.log(a) // the old value + * console.log(b) // the updated value + * // Apply changes of diff (pseudocode) + * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters + * a.insert(diff.index, diff.insert) // Insert `diff.insert` + * a === b // values match + * ``` + */ +export type SimpleDiff = { + /** + * The index where changes were applied + */ + index: number; + /** + * The number of characters to delete starting + * at `index`. + */ + remove: number; + /** + * The new text to insert at `index` after applying + * `delete` + */ + insert: T; +}; +//# sourceMappingURL=diff.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/diff.d.ts.map b/nodejs/node_modules/lib0/diff.d.ts.map new file mode 100644 index 00000000..5839793e --- /dev/null +++ b/nodejs/node_modules/lib0/diff.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.d.ts","sourceRoot":"","sources":["diff.js"],"names":[],"mappings":"AA2CO,oCAJI,MAAM,KACN,MAAM,GACL,WAAW,MAAM,CAAC,CAoB7B;AAlBM,8BAJI,MAAM,KACN,MAAM,GACL,WAAW,MAAM,CAAC,CAoB7B;AAuBM,oFAHmB,OAAO,gCAiBhC;AASM,8CAJI,MAAM,KACN,MAAM,UACN,MAAM;;;;EAyChB;;;;;;;;;;;;;;;;;;;;;;;;;;;YA1Ha,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/diff.js b/nodejs/node_modules/lib0/diff.js new file mode 100644 index 00000000..d9bf8e6f --- /dev/null +++ b/nodejs/node_modules/lib0/diff.js @@ -0,0 +1,147 @@ +/** + * Efficient diffs. + * + * @module diff + */ + +import { equalityStrict } from './function.js' + +/** + * A SimpleDiff describes a change on a String. + * + * ```js + * console.log(a) // the old value + * console.log(b) // the updated value + * // Apply changes of diff (pseudocode) + * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters + * a.insert(diff.index, diff.insert) // Insert `diff.insert` + * a === b // values match + * ``` + * + * @typedef {Object} SimpleDiff + * @property {Number} index The index where changes were applied + * @property {Number} remove The number of characters to delete starting + * at `index`. + * @property {T} insert The new text to insert at `index` after applying + * `delete` + * + * @template T + */ + +const highSurrogateRegex = /[\uD800-\uDBFF]/ +const lowSurrogateRegex = /[\uDC00-\uDFFF]/ + +/** + * Create a diff between two strings. This diff implementation is highly + * efficient, but not very sophisticated. + * + * @function + * + * @param {string} a The old version of the string + * @param {string} b The updated version of the string + * @return {SimpleDiff} The diff description. + */ +export const simpleDiffString = (a, b) => { + let left = 0 // number of same characters counting from left + let right = 0 // number of same characters counting from right + while (left < a.length && left < b.length && a[left] === b[left]) { + left++ + } + // If the last same character is a high surrogate, we need to rollback to the previous character + if (left > 0 && highSurrogateRegex.test(a[left - 1])) left-- + while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) { + right++ + } + // If the last same character is a low surrogate, we need to rollback to the previous character + if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right-- + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } +} + +/** + * @todo Remove in favor of simpleDiffString + * @deprecated + */ +export const simpleDiff = simpleDiffString + +/** + * Create a diff between two arrays. This diff implementation is highly + * efficient, but not very sophisticated. + * + * Note: This is basically the same function as above. Another function was created so that the runtime + * can better optimize these function calls. + * + * @function + * @template T + * + * @param {Array} a The old version of the array + * @param {Array} b The updated version of the array + * @param {function(T, T):boolean} [compare] + * @return {SimpleDiff>} The diff description. + */ +export const simpleDiffArray = (a, b, compare = equalityStrict) => { + let left = 0 // number of same characters counting from left + let right = 0 // number of same characters counting from right + while (left < a.length && left < b.length && compare(a[left], b[left])) { + left++ + } + while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) { + right++ + } + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } +} + +/** + * Diff text and try to diff at the current cursor position. + * + * @param {string} a + * @param {string} b + * @param {number} cursor This should refer to the current left cursor-range position + */ +export const simpleDiffStringWithCursor = (a, b, cursor) => { + let left = 0 // number of same characters counting from left + let right = 0 // number of same characters counting from right + // Iterate left to the right until we find a changed character + // First iteration considers the current cursor position + while ( + left < a.length && + left < b.length && + a[left] === b[left] && + left < cursor + ) { + left++ + } + // If the last same character is a high surrogate, we need to rollback to the previous character + if (left > 0 && highSurrogateRegex.test(a[left - 1])) left-- + // Iterate right to the left until we find a changed character + while ( + right + left < a.length && + right + left < b.length && + a[a.length - right - 1] === b[b.length - right - 1] + ) { + right++ + } + // If the last same character is a low surrogate, we need to rollback to the previous character + if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right-- + // Try to iterate left further to the right without caring about the current cursor position + while ( + right + left < a.length && + right + left < b.length && + a[left] === b[left] + ) { + left++ + } + if (left > 0 && highSurrogateRegex.test(a[left - 1])) left-- + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } +} diff --git a/nodejs/node_modules/lib0/diff.test.d.ts b/nodejs/node_modules/lib0/diff.test.d.ts new file mode 100644 index 00000000..5df670c3 --- /dev/null +++ b/nodejs/node_modules/lib0/diff.test.d.ts @@ -0,0 +1,6 @@ +export function testDiffing(tc: t.TestCase): void; +export function testRepeatDiffing(tc: t.TestCase): void; +export function testSimpleDiffWithCursor(tc: t.TestCase): void; +export function testArrayDiffing(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=diff.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/diff.test.d.ts.map b/nodejs/node_modules/lib0/diff.test.d.ts.map new file mode 100644 index 00000000..cb4b7bd3 --- /dev/null +++ b/nodejs/node_modules/lib0/diff.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.test.d.ts","sourceRoot":"","sources":["diff.test.js"],"names":[],"mappings":"AA0BO,gCAFI,EAAE,QAAQ,QAmBpB;AAKM,sCAFI,EAAE,QAAQ,QAQpB;AAKM,6CAFI,EAAE,QAAQ,QA4CpB;AAKM,qCAFI,EAAE,QAAQ,QAQpB;mBA7GkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/aes-gcm.cjs b/nodejs/node_modules/lib0/dist/aes-gcm.cjs new file mode 100644 index 00000000..f51cbacb --- /dev/null +++ b/nodejs/node_modules/lib0/dist/aes-gcm.cjs @@ -0,0 +1,171 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var encoding = require('./encoding-882cb136.cjs'); +var decoding = require('./decoding-000d097f.cjs'); +var webcrypto = require('lib0/webcrypto'); +var string = require('./string-6d104757.cjs'); +var common = require('./common.cjs'); +require('./math-08e068f9.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./error-8582d695.cjs'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var webcrypto__namespace = /*#__PURE__*/_interopNamespace(webcrypto); + +/** + * AES-GCM is a symmetric key for encryption + */ + +/** + * @typedef {Array<'encrypt'|'decrypt'>} Usages + */ + +/** + * @type {Usages} + */ +const defaultUsages = ['encrypt', 'decrypt']; + +/** + * @param {CryptoKey} key + * @param {Uint8Array} data + */ +const encrypt = (key, data) => { + const iv = webcrypto__namespace.getRandomValues(new Uint8Array(16)); // 92bit is enough. 128bit is recommended if space is not an issue. + return webcrypto__namespace.subtle.encrypt( + { + name: 'AES-GCM', + iv + }, + key, + data + ).then(cipher => { + const encryptedDataEncoder = encoding.createEncoder(); + // iv may be sent in the clear to the other peers + encoding.writeUint8Array(encryptedDataEncoder, iv); + encoding.writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher)); + return encoding.toUint8Array(encryptedDataEncoder) + }) +}; + +/** + * @experimental The API is not final! + * + * Decrypt some data using AES-GCM method. + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} decrypted buffer + */ +const decrypt = (key, data) => { + const dataDecoder = decoding.createDecoder(data); + const iv = decoding.readUint8Array(dataDecoder, 16); + const cipher = decoding.readVarUint8Array(dataDecoder); + return webcrypto__namespace.subtle.decrypt( + { + name: 'AES-GCM', + iv + }, + key, + cipher + ).then(data => new Uint8Array(data)) +}; + +const aesAlgDef = { + name: 'AES-GCM', + length: 256 +}; + +/** + * @param {any} jwk + * @param {Object} opts + * @param {Usages} [opts.usages] + * @param {boolean} [opts.extractable] + */ +const importKeyJwk = (jwk, { usages, extractable = false } = {}) => { + if (usages == null) { + /* c8 ignore next */ + usages = jwk.key_ops || defaultUsages; + } + return webcrypto__namespace.subtle.importKey('jwk', jwk, 'AES-GCM', extractable, /** @type {Usages} */ (usages)) +}; + +/** + * Only suited for importing public keys. + * + * @param {Uint8Array} raw + * @param {Object} opts + * @param {Usages} [opts.usages] + * @param {boolean} [opts.extractable] + */ +const importKeyRaw = (raw, { usages = defaultUsages, extractable = false } = {}) => + webcrypto__namespace.subtle.importKey('raw', raw, aesAlgDef, extractable, /** @type {Usages} */ (usages)); + +/** + * @param {Uint8Array | string} data + */ +/* c8 ignore next */ +const toBinary = data => typeof data === 'string' ? string.encodeUtf8(data) : data; + +/** + * @experimental The API is not final! + * + * Derive an symmetric key using the Password-Based-Key-Derivation-Function-2. + * + * @param {Uint8Array|string} secret + * @param {Uint8Array|string} salt + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +const deriveKey = (secret, salt, { extractable = false, usages = defaultUsages } = {}) => + webcrypto__namespace.subtle.importKey( + 'raw', + toBinary(secret), + 'PBKDF2', + false, + ['deriveKey'] + ).then(keyMaterial => + webcrypto__namespace.subtle.deriveKey( + { + name: 'PBKDF2', + salt: toBinary(salt), // NIST recommends at least 64 bits + iterations: 600000, // OWASP recommends 600k iterations + hash: 'SHA-256' + }, + keyMaterial, + aesAlgDef, + extractable, + usages + ) + ); + +exports.exportKeyJwk = common.exportKeyJwk; +exports.exportKeyRaw = common.exportKeyRaw; +exports.decrypt = decrypt; +exports.deriveKey = deriveKey; +exports.encrypt = encrypt; +exports.importKeyJwk = importKeyJwk; +exports.importKeyRaw = importKeyRaw; +//# sourceMappingURL=aes-gcm.cjs.map diff --git a/nodejs/node_modules/lib0/dist/aes-gcm.cjs.map b/nodejs/node_modules/lib0/dist/aes-gcm.cjs.map new file mode 100644 index 00000000..4431bd5a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/aes-gcm.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"aes-gcm.cjs","sources":["../crypto/aes-gcm.js"],"sourcesContent":["/**\n * AES-GCM is a symmetric key for encryption\n */\n\nimport * as encoding from '../encoding.js'\nimport * as decoding from '../decoding.js'\nimport * as webcrypto from 'lib0/webcrypto'\nimport * as string from '../string.js'\nexport { exportKeyJwk, exportKeyRaw } from './common.js'\n\n/**\n * @typedef {Array<'encrypt'|'decrypt'>} Usages\n */\n\n/**\n * @type {Usages}\n */\nconst defaultUsages = ['encrypt', 'decrypt']\n\n/**\n * @param {CryptoKey} key\n * @param {Uint8Array} data\n */\nexport const encrypt = (key, data) => {\n const iv = webcrypto.getRandomValues(new Uint8Array(16)) // 92bit is enough. 128bit is recommended if space is not an issue.\n return webcrypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n data\n ).then(cipher => {\n const encryptedDataEncoder = encoding.createEncoder()\n // iv may be sent in the clear to the other peers\n encoding.writeUint8Array(encryptedDataEncoder, iv)\n encoding.writeVarUint8Array(encryptedDataEncoder, new Uint8Array(cipher))\n return encoding.toUint8Array(encryptedDataEncoder)\n })\n}\n\n/**\n * @experimental The API is not final!\n *\n * Decrypt some data using AES-GCM method.\n *\n * @param {CryptoKey} key\n * @param {Uint8Array} data\n * @return {PromiseLike} decrypted buffer\n */\nexport const decrypt = (key, data) => {\n const dataDecoder = decoding.createDecoder(data)\n const iv = decoding.readUint8Array(dataDecoder, 16)\n const cipher = decoding.readVarUint8Array(dataDecoder)\n return webcrypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv\n },\n key,\n cipher\n ).then(data => new Uint8Array(data))\n}\n\nconst aesAlgDef = {\n name: 'AES-GCM',\n length: 256\n}\n\n/**\n * @param {any} jwk\n * @param {Object} opts\n * @param {Usages} [opts.usages]\n * @param {boolean} [opts.extractable]\n */\nexport const importKeyJwk = (jwk, { usages, extractable = false } = {}) => {\n if (usages == null) {\n /* c8 ignore next */\n usages = jwk.key_ops || defaultUsages\n }\n return webcrypto.subtle.importKey('jwk', jwk, 'AES-GCM', extractable, /** @type {Usages} */ (usages))\n}\n\n/**\n * Only suited for importing public keys.\n *\n * @param {Uint8Array} raw\n * @param {Object} opts\n * @param {Usages} [opts.usages]\n * @param {boolean} [opts.extractable]\n */\nexport const importKeyRaw = (raw, { usages = defaultUsages, extractable = false } = {}) =>\n webcrypto.subtle.importKey('raw', raw, aesAlgDef, extractable, /** @type {Usages} */ (usages))\n\n/**\n * @param {Uint8Array | string} data\n */\n/* c8 ignore next */\nconst toBinary = data => typeof data === 'string' ? string.encodeUtf8(data) : data\n\n/**\n * @experimental The API is not final!\n *\n * Derive an symmetric key using the Password-Based-Key-Derivation-Function-2.\n *\n * @param {Uint8Array|string} secret\n * @param {Uint8Array|string} salt\n * @param {Object} opts\n * @param {boolean} [opts.extractable]\n * @param {Usages} [opts.usages]\n */\nexport const deriveKey = (secret, salt, { extractable = false, usages = defaultUsages } = {}) =>\n webcrypto.subtle.importKey(\n 'raw',\n toBinary(secret),\n 'PBKDF2',\n false,\n ['deriveKey']\n ).then(keyMaterial =>\n webcrypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: toBinary(salt), // NIST recommends at least 64 bits\n iterations: 600000, // OWASP recommends 600k iterations\n hash: 'SHA-256'\n },\n keyMaterial,\n aesAlgDef,\n extractable,\n usages\n )\n )\n"],"names":["webcrypto","encoding.createEncoder","encoding.writeUint8Array","encoding.writeVarUint8Array","encoding.toUint8Array","decoding.createDecoder","decoding.readUint8Array","decoding.readVarUint8Array","string.encodeUtf8"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,SAAS,EAAE,SAAS,EAAC;AAC5C;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,GAAG,EAAE,IAAI,KAAK;AACtC,EAAE,MAAM,EAAE,GAAGA,oBAAS,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,EAAC;AAC1D,EAAE,OAAOA,oBAAS,CAAC,MAAM,CAAC,OAAO;AACjC,IAAI;AACJ,MAAM,IAAI,EAAE,SAAS;AACrB,MAAM,EAAE;AACR,KAAK;AACL,IAAI,GAAG;AACP,IAAI,IAAI;AACR,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI;AACnB,IAAI,MAAM,oBAAoB,GAAGC,sBAAsB,GAAE;AACzD;AACA,IAAIC,wBAAwB,CAAC,oBAAoB,EAAE,EAAE,EAAC;AACtD,IAAIC,2BAA2B,CAAC,oBAAoB,EAAE,IAAI,UAAU,CAAC,MAAM,CAAC,EAAC;AAC7E,IAAI,OAAOC,qBAAqB,CAAC,oBAAoB,CAAC;AACtD,GAAG,CAAC;AACJ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,GAAG,EAAE,IAAI,KAAK;AACtC,EAAE,MAAM,WAAW,GAAGC,sBAAsB,CAAC,IAAI,EAAC;AAClD,EAAE,MAA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AClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,WAAW,GAAG,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,GAAG,EAAE;AAC5F,EAAER,oBAAS,CAAC,MAAM,CAAC,SAAS;AAC5B,IAAI,KAAK;AACT,IAAI,QAAQ,CAAC,MAAM,CAAC;AACpB,IAAI,QAAQ;AACZ,IAAI,KAAK;AACT,IAAI,CAAC,WAAW,CAAC;AACjB,GAAG,CAAC,IAAI,CAAC,WAAW;AACpB,IAAIA,oBAAS,CAAC,MAAM,CAAC,SAAS;AAC9B,MAAM;AACN,QAAQ,IAAI,EAAE,QAAQ;AACtB,QAAQ,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC;AAC5B,QAAQ,UAAU,EAAE,MAAM;AAC1B,QAAQ,IAAI,EAAE,SAAS;AACvB,OAAO;AACP,MAAM,WAAW;AACjB,MAAM,SAAS;AACf,MAAM,WAAW;AACjB,MAAM,MAAM;AACZ,KAAK;AACL;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/array-704ca50e.cjs b/nodejs/node_modules/lib0/dist/array-704ca50e.cjs new file mode 100644 index 00000000..3523671f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array-704ca50e.cjs @@ -0,0 +1,223 @@ +'use strict'; + +var set = require('./set-0f209abb.cjs'); + +/** + * Utility module to work with Arrays. + * + * @module array + */ + +/** + * Return the last element of an array. The element must exist + * + * @template L + * @param {ArrayLike} arr + * @return {L} + */ +const last = arr => arr[arr.length - 1]; + +/** + * @template C + * @return {Array} + */ +const create = () => /** @type {Array} */ ([]); + +/** + * @template D + * @param {Array} a + * @return {Array} + */ +const copy = a => /** @type {Array} */ (a.slice()); + +/** + * Append elements from src to dest + * + * @template M + * @param {Array} dest + * @param {Array} src + */ +const appendTo = (dest, src) => { + for (let i = 0; i < src.length; i++) { + dest.push(src[i]); + } +}; + +/** + * Transforms something array-like to an actual Array. + * + * @function + * @template T + * @param {ArrayLike|Iterable} arraylike + * @return {T} + */ +const from = Array.from; + +/** + * True iff condition holds on every element in the Array. + * + * @function + * @template ITEM + * @template {ArrayLike} ARR + * + * @param {ARR} arr + * @param {function(ITEM, number, ARR):boolean} f + * @return {boolean} + */ +const every = (arr, f) => { + for (let i = 0; i < arr.length; i++) { + if (!f(arr[i], i, arr)) { + return false + } + } + return true +}; + +/** + * True iff condition holds on some element in the Array. + * + * @function + * @template S + * @template {ArrayLike} ARR + * @param {ARR} arr + * @param {function(S, number, ARR):boolean} f + * @return {boolean} + */ +const some = (arr, f) => { + for (let i = 0; i < arr.length; i++) { + if (f(arr[i], i, arr)) { + return true + } + } + return false +}; + +/** + * @template ELEM + * + * @param {ArrayLike} a + * @param {ArrayLike} b + * @return {boolean} + */ +const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index]); + +/** + * @template ELEM + * @param {Array>} arr + * @return {Array} + */ +const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val)); + +/** + * @template T + * @param {number} len + * @param {function(number, Array):T} f + * @return {Array} + */ +const unfold = (len, f) => { + const array = new Array(len); + for (let i = 0; i < len; i++) { + array[i] = f(i, array); + } + return array +}; + +/** + * @template T + * @template RESULT + * @param {Array} arr + * @param {RESULT} seed + * @param {function(RESULT, T, number):RESULT} folder + */ +const fold = (arr, seed, folder) => arr.reduce(folder, seed); + +const isArray = Array.isArray; + +/** + * @template T + * @param {Array} arr + * @return {Array} + */ +const unique = arr => from(set.from(arr)); + +/** + * @template T + * @template M + * @param {ArrayLike} arr + * @param {function(T):M} mapper + * @return {Array} + */ +const uniqueBy = (arr, mapper) => { + /** + * @type {Set} + */ + const happened = set.create(); + /** + * @type {Array} + */ + const result = []; + for (let i = 0; i < arr.length; i++) { + const el = arr[i]; + const mapped = mapper(el); + if (!happened.has(mapped)) { + happened.add(mapped); + result.push(el); + } + } + return result +}; + +/** + * @template {ArrayLike} ARR + * @template {function(ARR extends ArrayLike ? T : never, number, ARR):any} MAPPER + * @param {ARR} arr + * @param {MAPPER} mapper + * @return {Array} + */ +const map = (arr, mapper) => { + /** + * @type {Array} + */ + const res = Array(arr.length); + for (let i = 0; i < arr.length; i++) { + res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr)); + } + return /** @type {any} */ (res) +}; + +var array = /*#__PURE__*/Object.freeze({ + __proto__: null, + last: last, + create: create, + copy: copy, + appendTo: appendTo, + from: from, + every: every, + some: some, + equalFlat: equalFlat, + flatten: flatten, + unfold: unfold, + fold: fold, + isArray: isArray, + unique: unique, + uniqueBy: uniqueBy, + map: map +}); + +exports.appendTo = appendTo; +exports.array = array; +exports.copy = copy; +exports.create = create; +exports.equalFlat = equalFlat; +exports.every = every; +exports.flatten = flatten; +exports.fold = fold; +exports.from = from; +exports.isArray = isArray; +exports.last = last; +exports.map = map; +exports.some = some; +exports.unfold = unfold; +exports.unique = unique; +exports.uniqueBy = uniqueBy; +//# sourceMappingURL=array-704ca50e.cjs.map diff --git a/nodejs/node_modules/lib0/dist/array-704ca50e.cjs.map b/nodejs/node_modules/lib0/dist/array-704ca50e.cjs.map new file mode 100644 index 00000000..2777d4f3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array-704ca50e.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"array-704ca50e.cjs","sources":["../array.js"],"sourcesContent":["/**\n * Utility module to work with Arrays.\n *\n * @module array\n */\n\nimport * as set from './set.js'\n\n/**\n * Return the last element of an array. The element must exist\n *\n * @template L\n * @param {ArrayLike} arr\n * @return {L}\n */\nexport const last = arr => arr[arr.length - 1]\n\n/**\n * @template C\n * @return {Array}\n */\nexport const create = () => /** @type {Array} */ ([])\n\n/**\n * @template D\n * @param {Array} a\n * @return {Array}\n */\nexport const copy = a => /** @type {Array} */ (a.slice())\n\n/**\n * Append elements from src to dest\n *\n * @template M\n * @param {Array} dest\n * @param {Array} src\n */\nexport const appendTo = (dest, src) => {\n for (let i = 0; i < src.length; i++) {\n dest.push(src[i])\n }\n}\n\n/**\n * Transforms something array-like to an actual Array.\n *\n * @function\n * @template T\n * @param {ArrayLike|Iterable} arraylike\n * @return {T}\n */\nexport const from = Array.from\n\n/**\n * True iff condition holds on every element in the Array.\n *\n * @function\n * @template ITEM\n * @template {ArrayLike} ARR\n *\n * @param {ARR} arr\n * @param {function(ITEM, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const every = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (!f(arr[i], i, arr)) {\n return false\n }\n }\n return true\n}\n\n/**\n * True iff condition holds on some element in the Array.\n *\n * @function\n * @template S\n * @template {ArrayLike} ARR\n * @param {ARR} arr\n * @param {function(S, number, ARR):boolean} f\n * @return {boolean}\n */\nexport const some = (arr, f) => {\n for (let i = 0; i < arr.length; i++) {\n if (f(arr[i], i, arr)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @template ELEM\n *\n * @param {ArrayLike} a\n * @param {ArrayLike} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a.length === b.length && every(a, (item, index) => item === b[index])\n\n/**\n * @template ELEM\n * @param {Array>} arr\n * @return {Array}\n */\nexport const flatten = arr => fold(arr, /** @type {Array} */ ([]), (acc, val) => acc.concat(val))\n\n/**\n * @template T\n * @param {number} len\n * @param {function(number, Array):T} f\n * @return {Array}\n */\nexport const unfold = (len, f) => {\n const array = new Array(len)\n for (let i = 0; i < len; i++) {\n array[i] = f(i, array)\n }\n return array\n}\n\n/**\n * @template T\n * @template RESULT\n * @param {Array} arr\n * @param {RESULT} seed\n * @param {function(RESULT, T, number):RESULT} folder\n */\nexport const fold = (arr, seed, folder) => arr.reduce(folder, seed)\n\nexport const isArray = Array.isArray\n\n/**\n * @template T\n * @param {Array} arr\n * @return {Array}\n */\nexport const unique = arr => from(set.from(arr))\n\n/**\n * @template T\n * @template M\n * @param {ArrayLike} arr\n * @param {function(T):M} mapper\n * @return {Array}\n */\nexport const uniqueBy = (arr, mapper) => {\n /**\n * @type {Set}\n */\n const happened = set.create()\n /**\n * @type {Array}\n */\n const result = []\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i]\n const mapped = mapper(el)\n if (!happened.has(mapped)) {\n happened.add(mapped)\n result.push(el)\n }\n }\n return result\n}\n\n/**\n * @template {ArrayLike} ARR\n * @template {function(ARR extends ArrayLike ? T : never, number, ARR):any} MAPPER\n * @param {ARR} arr\n * @param {MAPPER} mapper\n * @return {Array}\n */\nexport const map = (arr, mapper) => {\n /**\n * @type {Array}\n */\n const res = Array(arr.length)\n for (let i = 0; i < arr.length; i++) {\n res[i] = mapper(/** @type {any} */ (arr[i]), i, /** @type {any} */ (arr))\n }\n return /** @type {any} */ (res)\n}\n"],"names":["set.from","set.create"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,EAAC;AAC9C;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,+BAA+B,EAAE,EAAC;AACxD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,CAAC,6BAA6B,CAAC,CAAC,KAAK,EAAE,EAAC;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK;AACvC,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACvC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAC;AACrB,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,KAAK,CAAC,KAAI;AAC9B;AACA;AACA;AACA;AACA;AACA;A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AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,KAAK;AACpC;AACA;AACA;AACA,EAAE,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,EAAC;AAC/B,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACvC,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,qBAAqB,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,sBAAsB,GAAG,GAAE;AAC7E,GAAG;AACH,EAAE,2BAA2B,GAAG,CAAC;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/array.cjs b/nodejs/node_modules/lib0/dist/array.cjs new file mode 100644 index 00000000..e2c35e00 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array.cjs @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./set-0f209abb.cjs'); +var array = require('./array-704ca50e.cjs'); + + + +exports.appendTo = array.appendTo; +exports.copy = array.copy; +exports.create = array.create; +exports.equalFlat = array.equalFlat; +exports.every = array.every; +exports.flatten = array.flatten; +exports.fold = array.fold; +exports.from = array.from; +exports.isArray = array.isArray; +exports.last = array.last; +exports.map = array.map; +exports.some = array.some; +exports.unfold = array.unfold; +exports.unique = array.unique; +exports.uniqueBy = array.uniqueBy; +//# sourceMappingURL=array.cjs.map diff --git a/nodejs/node_modules/lib0/dist/array.cjs.map b/nodejs/node_modules/lib0/dist/array.cjs.map new file mode 100644 index 00000000..5a485256 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"array.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/array.d.ts b/nodejs/node_modules/lib0/dist/array.d.ts new file mode 100644 index 00000000..e794d243 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array.d.ts @@ -0,0 +1,29 @@ +export function last(arr: ArrayLike): L; +export function create(): C[]; +export function copy(a: D[]): D[]; +export function appendTo(dest: M[], src: M[]): void; +/** + * Transforms something array-like to an actual Array. + * + * @function + * @template T + * @param {ArrayLike|Iterable} arraylike + * @return {T} + */ +export const from: { + (arrayLike: ArrayLike): T_1[]; + (arrayLike: ArrayLike, mapfn: (v: T_2, k: number) => U, thisArg?: any): U[]; + (iterable: Iterable | ArrayLike): T_3[]; + (iterable: Iterable | ArrayLike, mapfn: (v: T_4, k: number) => U_1, thisArg?: any): U_1[]; +}; +export function every>(arr: ARR, f: (arg0: ITEM, arg1: number, arg2: ARR) => boolean): boolean; +export function some>(arr: ARR, f: (arg0: S, arg1: number, arg2: ARR) => boolean): boolean; +export function equalFlat(a: ArrayLike, b: ArrayLike): boolean; +export function flatten(arr: ELEM[][]): ELEM[]; +export function unfold(len: number, f: (arg0: number, arg1: T_1[]) => T_1): T_1[]; +export function fold(arr: T_1[], seed: RESULT, folder: (arg0: RESULT, arg1: T_1, arg2: number) => RESULT): RESULT; +export const isArray: (arg: any) => arg is any[]; +export function unique(arr: T_1[]): T_1[]; +export function uniqueBy(arr: ArrayLike, mapper: (arg0: T_1) => M): T_1[]; +export function map, MAPPER extends (arg0: ARR extends ArrayLike ? T_1 : never, arg1: number, arg2: ARR) => any>(arr: ARR, mapper: MAPPER): (MAPPER extends (...arg0: any[]) => infer M ? M : never)[]; +//# sourceMappingURL=array.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/array.d.ts.map b/nodejs/node_modules/lib0/dist/array.d.ts.map new file mode 100644 index 00000000..7281b81a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.d.ts","sourceRoot":"","sources":["../array.js"],"names":[],"mappings":"AAeO,8CAAuC;AAMvC,iCAAiD;AAOjD,qCAAqD;AASrD,uDAIN;AAED;;;;;;;GAOG;AACH;;;;;EAA8B;AAavB,yFAHmB,MAAM,gBAAO,OAAO,GAClC,OAAO,CASlB;AAYM,+EAHgB,MAAM,gBAAO,OAAO,GAC/B,OAAO,CASlB;AASM,yEAFK,OAAO,CAEqF;AAOjG,qDAAgG;AAQhG,iCAJI,MAAM,YACG,MAAM,8BASzB;AASM,oGAFwB,MAAM,qBAE8B;AAEnE,iDAAoC;AAO7B,+CAAyC;AASzC,uFAkBN;AASM,4HAL4D,MAAM,gBAAO,GAAG,uDAGtC,GAAG,8BAW/C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/array.test.d.ts b/nodejs/node_modules/lib0/dist/array.test.d.ts new file mode 100644 index 00000000..a68d4ac9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array.test.d.ts @@ -0,0 +1,10 @@ +export function testIsarrayPerformance(_tc: t.TestCase): void; +export function testAppend(_tc: t.TestCase): void; +export function testBasic(_tc: t.TestCase): void; +export function testflatten(_tc: t.TestCase): void; +export function testFolding(_tc: t.TestCase): void; +export function testEvery(_tc: t.TestCase): void; +export function testIsArray(_tc: t.TestCase): void; +export function testUnique(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=array.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/array.test.d.ts.map b/nodejs/node_modules/lib0/dist/array.test.d.ts.map new file mode 100644 index 00000000..6576cf44 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/array.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.test.d.ts","sourceRoot":"","sources":["../array.test.js"],"names":[],"mappings":"AAMO,4CAFI,EAAE,QAAQ,QAkCpB;AAKM,gCAFI,EAAE,QAAQ,QAMpB;AAKM,+BAFI,EAAE,QAAQ,QAMpB;AAKM,iCAFI,EAAE,QAAQ,QAKpB;AAKM,iCAFI,EAAE,QAAQ,QAkBpB;AAKM,+BAFI,EAAE,QAAQ,QAQpB;AAKM,iCAFI,EAAE,QAAQ,QASpB;AAKM,gCAFI,EAAE,QAAQ,QAOpB;mBArHkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/0ecdsa-generate-keypair.d.ts b/nodejs/node_modules/lib0/dist/bin/0ecdsa-generate-keypair.d.ts new file mode 100644 index 00000000..71a08e30 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/0ecdsa-generate-keypair.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=0ecdsa-generate-keypair.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/0ecdsa-generate-keypair.d.ts.map b/nodejs/node_modules/lib0/dist/bin/0ecdsa-generate-keypair.d.ts.map new file mode 100644 index 00000000..58c48c6a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/0ecdsa-generate-keypair.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"0ecdsa-generate-keypair.d.ts","sourceRoot":"","sources":["../../bin/0ecdsa-generate-keypair.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/0serve.d.ts b/nodejs/node_modules/lib0/dist/bin/0serve.d.ts new file mode 100644 index 00000000..97bafa42 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/0serve.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=0serve.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/0serve.d.ts.map b/nodejs/node_modules/lib0/dist/bin/0serve.d.ts.map new file mode 100644 index 00000000..8e6e013b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/0serve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"0serve.d.ts","sourceRoot":"","sources":["../../bin/0serve.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/gendocs.d.ts b/nodejs/node_modules/lib0/dist/bin/gendocs.d.ts new file mode 100644 index 00000000..422e1199 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/gendocs.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=gendocs.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/gendocs.d.ts.map b/nodejs/node_modules/lib0/dist/bin/gendocs.d.ts.map new file mode 100644 index 00000000..9ea4ead1 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/gendocs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"gendocs.d.ts","sourceRoot":"","sources":["../../bin/gendocs.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/gentesthtml.d.ts b/nodejs/node_modules/lib0/dist/bin/gentesthtml.d.ts new file mode 100644 index 00000000..39f067bc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/gentesthtml.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=gentesthtml.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/bin/gentesthtml.d.ts.map b/nodejs/node_modules/lib0/dist/bin/gentesthtml.d.ts.map new file mode 100644 index 00000000..f4bf70a2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/bin/gentesthtml.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"gentesthtml.d.ts","sourceRoot":"","sources":["../../bin/gentesthtml.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/binary-ac8e39e2.cjs b/nodejs/node_modules/lib0/dist/binary-ac8e39e2.cjs new file mode 100644 index 00000000..7b705b83 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary-ac8e39e2.cjs @@ -0,0 +1,229 @@ +'use strict'; + +/* eslint-env browser */ + +/** + * Binary data constants. + * + * @module binary + */ + +/** + * n-th bit activated. + * + * @type {number} + */ +const BIT1 = 1; +const BIT2 = 2; +const BIT3 = 4; +const BIT4 = 8; +const BIT5 = 16; +const BIT6 = 32; +const BIT7 = 64; +const BIT8 = 128; +const BIT9 = 256; +const BIT10 = 512; +const BIT11 = 1024; +const BIT12 = 2048; +const BIT13 = 4096; +const BIT14 = 8192; +const BIT15 = 16384; +const BIT16 = 32768; +const BIT17 = 65536; +const BIT18 = 1 << 17; +const BIT19 = 1 << 18; +const BIT20 = 1 << 19; +const BIT21 = 1 << 20; +const BIT22 = 1 << 21; +const BIT23 = 1 << 22; +const BIT24 = 1 << 23; +const BIT25 = 1 << 24; +const BIT26 = 1 << 25; +const BIT27 = 1 << 26; +const BIT28 = 1 << 27; +const BIT29 = 1 << 28; +const BIT30 = 1 << 29; +const BIT31 = 1 << 30; +const BIT32 = 1 << 31; + +/** + * First n bits activated. + * + * @type {number} + */ +const BITS0 = 0; +const BITS1 = 1; +const BITS2 = 3; +const BITS3 = 7; +const BITS4 = 15; +const BITS5 = 31; +const BITS6 = 63; +const BITS7 = 127; +const BITS8 = 255; +const BITS9 = 511; +const BITS10 = 1023; +const BITS11 = 2047; +const BITS12 = 4095; +const BITS13 = 8191; +const BITS14 = 16383; +const BITS15 = 32767; +const BITS16 = 65535; +const BITS17 = BIT18 - 1; +const BITS18 = BIT19 - 1; +const BITS19 = BIT20 - 1; +const BITS20 = BIT21 - 1; +const BITS21 = BIT22 - 1; +const BITS22 = BIT23 - 1; +const BITS23 = BIT24 - 1; +const BITS24 = BIT25 - 1; +const BITS25 = BIT26 - 1; +const BITS26 = BIT27 - 1; +const BITS27 = BIT28 - 1; +const BITS28 = BIT29 - 1; +const BITS29 = BIT30 - 1; +const BITS30 = BIT31 - 1; +/** + * @type {number} + */ +const BITS31 = 0x7FFFFFFF; +/** + * @type {number} + */ +const BITS32 = 0xFFFFFFFF; + +var binary = /*#__PURE__*/Object.freeze({ + __proto__: null, + BIT1: BIT1, + BIT2: BIT2, + BIT3: BIT3, + BIT4: BIT4, + BIT5: BIT5, + BIT6: BIT6, + BIT7: BIT7, + BIT8: BIT8, + BIT9: BIT9, + BIT10: BIT10, + BIT11: BIT11, + BIT12: BIT12, + BIT13: BIT13, + BIT14: BIT14, + BIT15: BIT15, + BIT16: BIT16, + BIT17: BIT17, + BIT18: BIT18, + BIT19: BIT19, + BIT20: BIT20, + BIT21: BIT21, + BIT22: BIT22, + BIT23: BIT23, + BIT24: BIT24, + BIT25: BIT25, + BIT26: BIT26, + BIT27: BIT27, + BIT28: BIT28, + BIT29: BIT29, + BIT30: BIT30, + BIT31: BIT31, + BIT32: BIT32, + BITS0: BITS0, + BITS1: BITS1, + BITS2: BITS2, + BITS3: BITS3, + BITS4: BITS4, + BITS5: BITS5, + BITS6: BITS6, + BITS7: BITS7, + BITS8: BITS8, + BITS9: BITS9, + BITS10: BITS10, + BITS11: BITS11, + BITS12: BITS12, + BITS13: BITS13, + BITS14: BITS14, + BITS15: BITS15, + BITS16: BITS16, + BITS17: BITS17, + BITS18: BITS18, + BITS19: BITS19, + BITS20: BITS20, + BITS21: BITS21, + BITS22: BITS22, + BITS23: BITS23, + BITS24: BITS24, + BITS25: BITS25, + BITS26: BITS26, + BITS27: BITS27, + BITS28: BITS28, + BITS29: BITS29, + BITS30: BITS30, + BITS31: BITS31, + BITS32: BITS32 +}); + +exports.BIT1 = BIT1; +exports.BIT10 = BIT10; +exports.BIT11 = BIT11; +exports.BIT12 = BIT12; +exports.BIT13 = BIT13; +exports.BIT14 = BIT14; +exports.BIT15 = BIT15; +exports.BIT16 = BIT16; +exports.BIT17 = BIT17; +exports.BIT18 = BIT18; +exports.BIT19 = BIT19; +exports.BIT2 = BIT2; +exports.BIT20 = BIT20; +exports.BIT21 = BIT21; +exports.BIT22 = BIT22; +exports.BIT23 = BIT23; +exports.BIT24 = BIT24; +exports.BIT25 = BIT25; +exports.BIT26 = BIT26; +exports.BIT27 = BIT27; +exports.BIT28 = BIT28; +exports.BIT29 = BIT29; +exports.BIT3 = BIT3; +exports.BIT30 = BIT30; +exports.BIT31 = BIT31; +exports.BIT32 = BIT32; +exports.BIT4 = BIT4; +exports.BIT5 = BIT5; +exports.BIT6 = BIT6; +exports.BIT7 = BIT7; +exports.BIT8 = BIT8; +exports.BIT9 = BIT9; +exports.BITS0 = BITS0; +exports.BITS1 = BITS1; +exports.BITS10 = BITS10; +exports.BITS11 = BITS11; +exports.BITS12 = BITS12; +exports.BITS13 = BITS13; +exports.BITS14 = BITS14; +exports.BITS15 = BITS15; +exports.BITS16 = BITS16; +exports.BITS17 = BITS17; +exports.BITS18 = BITS18; +exports.BITS19 = BITS19; +exports.BITS2 = BITS2; +exports.BITS20 = BITS20; +exports.BITS21 = BITS21; +exports.BITS22 = BITS22; +exports.BITS23 = BITS23; +exports.BITS24 = BITS24; +exports.BITS25 = BITS25; +exports.BITS26 = BITS26; +exports.BITS27 = BITS27; +exports.BITS28 = BITS28; +exports.BITS29 = BITS29; +exports.BITS3 = BITS3; +exports.BITS30 = BITS30; +exports.BITS31 = BITS31; +exports.BITS32 = BITS32; +exports.BITS4 = BITS4; +exports.BITS5 = BITS5; +exports.BITS6 = BITS6; +exports.BITS7 = BITS7; +exports.BITS8 = BITS8; +exports.BITS9 = BITS9; +exports.binary = binary; +//# sourceMappingURL=binary-ac8e39e2.cjs.map diff --git a/nodejs/node_modules/lib0/dist/binary-ac8e39e2.cjs.map b/nodejs/node_modules/lib0/dist/binary-ac8e39e2.cjs.map new file mode 100644 index 00000000..cee5b9b9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary-ac8e39e2.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-ac8e39e2.cjs","sources":["../binary.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Binary data constants.\n *\n * @module binary\n */\n\n/**\n * n-th bit activated.\n *\n * @type {number}\n */\nexport const BIT1 = 1\nexport const BIT2 = 2\nexport const BIT3 = 4\nexport const BIT4 = 8\nexport const BIT5 = 16\nexport const BIT6 = 32\nexport const BIT7 = 64\nexport const BIT8 = 128\nexport const BIT9 = 256\nexport const BIT10 = 512\nexport const BIT11 = 1024\nexport const BIT12 = 2048\nexport const BIT13 = 4096\nexport const BIT14 = 8192\nexport const BIT15 = 16384\nexport const BIT16 = 32768\nexport const BIT17 = 65536\nexport const BIT18 = 1 << 17\nexport const BIT19 = 1 << 18\nexport const BIT20 = 1 << 19\nexport const BIT21 = 1 << 20\nexport const BIT22 = 1 << 21\nexport const BIT23 = 1 << 22\nexport const BIT24 = 1 << 23\nexport const BIT25 = 1 << 24\nexport const BIT26 = 1 << 25\nexport const BIT27 = 1 << 26\nexport const BIT28 = 1 << 27\nexport const BIT29 = 1 << 28\nexport const BIT30 = 1 << 29\nexport const BIT31 = 1 << 30\nexport const BIT32 = 1 << 31\n\n/**\n * First n bits activated.\n *\n * @type {number}\n */\nexport const BITS0 = 0\nexport const BITS1 = 1\nexport const BITS2 = 3\nexport const BITS3 = 7\nexport const BITS4 = 15\nexport const BITS5 = 31\nexport const BITS6 = 63\nexport const BITS7 = 127\nexport const BITS8 = 255\nexport const BITS9 = 511\nexport const BITS10 = 1023\nexport const BITS11 = 2047\nexport const BITS12 = 4095\nexport const BITS13 = 8191\nexport const BITS14 = 16383\nexport const BITS15 = 32767\nexport const BITS16 = 65535\nexport const BITS17 = BIT18 - 1\nexport const BITS18 = BIT19 - 1\nexport const BITS19 = BIT20 - 1\nexport const BITS20 = BIT21 - 1\nexport const BITS21 = BIT22 - 1\nexport const BITS22 = BIT23 - 1\nexport const BITS23 = BIT24 - 1\nexport const BITS24 = BIT25 - 1\nexport const BITS25 = BIT26 - 1\nexport const BITS26 = BIT27 - 1\nexport const BITS27 = BIT28 - 1\nexport const BITS28 = BIT29 - 1\nexport const BITS29 = BIT30 - 1\nexport const BITS30 = BIT31 - 1\n/**\n * @type {number}\n */\nexport const BITS31 = 0x7FFFFFFF\n/**\n * @type {number}\n */\nexport const BITS32 = 0xFFFFFFFF\n"],"names":[],"mappings":";;A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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/binary.cjs b/nodejs/node_modules/lib0/dist/binary.cjs new file mode 100644 index 00000000..ea72a374 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary.cjs @@ -0,0 +1,74 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var binary = require('./binary-ac8e39e2.cjs'); + + + +exports.BIT1 = binary.BIT1; +exports.BIT10 = binary.BIT10; +exports.BIT11 = binary.BIT11; +exports.BIT12 = binary.BIT12; +exports.BIT13 = binary.BIT13; +exports.BIT14 = binary.BIT14; +exports.BIT15 = binary.BIT15; +exports.BIT16 = binary.BIT16; +exports.BIT17 = binary.BIT17; +exports.BIT18 = binary.BIT18; +exports.BIT19 = binary.BIT19; +exports.BIT2 = binary.BIT2; +exports.BIT20 = binary.BIT20; +exports.BIT21 = binary.BIT21; +exports.BIT22 = binary.BIT22; +exports.BIT23 = binary.BIT23; +exports.BIT24 = binary.BIT24; +exports.BIT25 = binary.BIT25; +exports.BIT26 = binary.BIT26; +exports.BIT27 = binary.BIT27; +exports.BIT28 = binary.BIT28; +exports.BIT29 = binary.BIT29; +exports.BIT3 = binary.BIT3; +exports.BIT30 = binary.BIT30; +exports.BIT31 = binary.BIT31; +exports.BIT32 = binary.BIT32; +exports.BIT4 = binary.BIT4; +exports.BIT5 = binary.BIT5; +exports.BIT6 = binary.BIT6; +exports.BIT7 = binary.BIT7; +exports.BIT8 = binary.BIT8; +exports.BIT9 = binary.BIT9; +exports.BITS0 = binary.BITS0; +exports.BITS1 = binary.BITS1; +exports.BITS10 = binary.BITS10; +exports.BITS11 = binary.BITS11; +exports.BITS12 = binary.BITS12; +exports.BITS13 = binary.BITS13; +exports.BITS14 = binary.BITS14; +exports.BITS15 = binary.BITS15; +exports.BITS16 = binary.BITS16; +exports.BITS17 = binary.BITS17; +exports.BITS18 = binary.BITS18; +exports.BITS19 = binary.BITS19; +exports.BITS2 = binary.BITS2; +exports.BITS20 = binary.BITS20; +exports.BITS21 = binary.BITS21; +exports.BITS22 = binary.BITS22; +exports.BITS23 = binary.BITS23; +exports.BITS24 = binary.BITS24; +exports.BITS25 = binary.BITS25; +exports.BITS26 = binary.BITS26; +exports.BITS27 = binary.BITS27; +exports.BITS28 = binary.BITS28; +exports.BITS29 = binary.BITS29; +exports.BITS3 = binary.BITS3; +exports.BITS30 = binary.BITS30; +exports.BITS31 = binary.BITS31; +exports.BITS32 = binary.BITS32; +exports.BITS4 = binary.BITS4; +exports.BITS5 = binary.BITS5; +exports.BITS6 = binary.BITS6; +exports.BITS7 = binary.BITS7; +exports.BITS8 = binary.BITS8; +exports.BITS9 = binary.BITS9; +//# sourceMappingURL=binary.cjs.map diff --git a/nodejs/node_modules/lib0/dist/binary.cjs.map b/nodejs/node_modules/lib0/dist/binary.cjs.map new file mode 100644 index 00000000..eaadb4cb --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/binary.d.ts b/nodejs/node_modules/lib0/dist/binary.d.ts new file mode 100644 index 00000000..890f0c47 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary.d.ts @@ -0,0 +1,87 @@ +/** + * Binary data constants. + * + * @module binary + */ +/** + * n-th bit activated. + * + * @type {number} + */ +export const BIT1: number; +export const BIT2: 2; +export const BIT3: 4; +export const BIT4: 8; +export const BIT5: 16; +export const BIT6: 32; +export const BIT7: 64; +export const BIT8: 128; +export const BIT9: 256; +export const BIT10: 512; +export const BIT11: 1024; +export const BIT12: 2048; +export const BIT13: 4096; +export const BIT14: 8192; +export const BIT15: 16384; +export const BIT16: 32768; +export const BIT17: 65536; +export const BIT18: number; +export const BIT19: number; +export const BIT20: number; +export const BIT21: number; +export const BIT22: number; +export const BIT23: number; +export const BIT24: number; +export const BIT25: number; +export const BIT26: number; +export const BIT27: number; +export const BIT28: number; +export const BIT29: number; +export const BIT30: number; +export const BIT31: number; +export const BIT32: number; +/** + * First n bits activated. + * + * @type {number} + */ +export const BITS0: number; +export const BITS1: 1; +export const BITS2: 3; +export const BITS3: 7; +export const BITS4: 15; +export const BITS5: 31; +export const BITS6: 63; +export const BITS7: 127; +export const BITS8: 255; +export const BITS9: 511; +export const BITS10: 1023; +export const BITS11: 2047; +export const BITS12: 4095; +export const BITS13: 8191; +export const BITS14: 16383; +export const BITS15: 32767; +export const BITS16: 65535; +export const BITS17: number; +export const BITS18: number; +export const BITS19: number; +export const BITS20: number; +export const BITS21: number; +export const BITS22: number; +export const BITS23: number; +export const BITS24: number; +export const BITS25: number; +export const BITS26: number; +export const BITS27: number; +export const BITS28: number; +export const BITS29: number; +export const BITS30: number; +/** + * @type {number} + */ +export const BITS31: number; +/** + * @type {number} + */ +export const BITS32: number; +//# sourceMappingURL=binary.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/binary.d.ts.map b/nodejs/node_modules/lib0/dist/binary.d.ts.map new file mode 100644 index 00000000..182d8bef --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.d.ts","sourceRoot":"","sources":["../binary.js"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH;;;;GAIG;AACH,mBAFU,MAAM,CAEK;AACrB,qBAAqB;AACrB,qBAAqB;AACrB,qBAAqB;AACrB,sBAAsB;AACtB,sBAAsB;AACtB,sBAAsB;AACtB,uBAAuB;AACvB,uBAAuB;AACvB,wBAAwB;AACxB,yBAAyB;AACzB,yBAAyB;AACzB,yBAAyB;AACzB,yBAAyB;AACzB,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAC5B,2BAA4B;AAE5B;;;;GAIG;AACH,oBAFU,MAAM,CAEM;AACtB,sBAAsB;AACtB,sBAAsB;AACtB,sBAAsB;AACtB,uBAAuB;AACvB,uBAAuB;AACvB,uBAAuB;AACvB,wBAAwB;AACxB,wBAAwB;AACxB,wBAAwB;AACxB,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B,2BAA2B;AAC3B,2BAA2B;AAC3B,2BAA2B;AAC3B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B,4BAA+B;AAC/B;;GAEG;AACH,qBAFU,MAAM,CAEgB;AAChC;;GAEG;AACH,qBAFU,MAAM,CAEgB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/binary.test.d.ts b/nodejs/node_modules/lib0/dist/binary.test.d.ts new file mode 100644 index 00000000..1c2e5865 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary.test.d.ts @@ -0,0 +1,4 @@ +export function testBitx(tc: t.TestCase): void; +export function testBitsx(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=binary.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/binary.test.d.ts.map b/nodejs/node_modules/lib0/dist/binary.test.d.ts.map new file mode 100644 index 00000000..25e738de --- /dev/null +++ b/nodejs/node_modules/lib0/dist/binary.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary.test.d.ts","sourceRoot":"","sources":["../binary.test.js"],"names":[],"mappings":"AAMO,6BAFI,EAAE,QAAQ,QAOpB;AAKM,8BAFI,EAAE,QAAQ,QAWpB;mBAxBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel-80813eea.cjs b/nodejs/node_modules/lib0/dist/broadcastchannel-80813eea.cjs new file mode 100644 index 00000000..01ef25e8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel-80813eea.cjs @@ -0,0 +1,128 @@ +'use strict'; + +var map = require('./map-0dabcc55.cjs'); +var set = require('./set-0f209abb.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); +var storage = require('./storage.cjs'); + +/* eslint-env browser */ + +/** + * @typedef {Object} Channel + * @property {Set} Channel.subs + * @property {any} Channel.bc + */ + +/** + * @type {Map} + */ +const channels = new Map(); + +/* c8 ignore start */ +class LocalStoragePolyfill { + /** + * @param {string} room + */ + constructor (room) { + this.room = room; + /** + * @type {null|function({data:ArrayBuffer}):void} + */ + this.onmessage = null; + /** + * @param {any} e + */ + this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') }); + storage.onChange(this._onChange); + } + + /** + * @param {ArrayBuffer} buf + */ + postMessage (buf) { + storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf))); + } + + close () { + storage.offChange(this._onChange); + } +} +/* c8 ignore stop */ + +// Use BroadcastChannel or Polyfill +/* c8 ignore next */ +const BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel; + +/** + * @param {string} room + * @return {Channel} + */ +const getChannel = room => + map.setIfUndefined(channels, room, () => { + const subs = set.create(); + const bc = new BC(room); + /** + * @param {{data:ArrayBuffer}} e + */ + /* c8 ignore next */ + bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel')); + return { + bc, subs + } + }); + +/** + * Subscribe to global `publish` events. + * + * @function + * @param {string} room + * @param {function(any, any):any} f + */ +const subscribe = (room, f) => { + getChannel(room).subs.add(f); + return f +}; + +/** + * Unsubscribe from `publish` global events. + * + * @function + * @param {string} room + * @param {function(any, any):any} f + */ +const unsubscribe = (room, f) => { + const channel = getChannel(room); + const unsubscribed = channel.subs.delete(f); + if (unsubscribed && channel.subs.size === 0) { + channel.bc.close(); + channels.delete(room); + } + return unsubscribed +}; + +/** + * Publish data to all subscribers (including subscribers on this tab) + * + * @function + * @param {string} room + * @param {any} data + * @param {any} [origin] + */ +const publish = (room, data, origin = null) => { + const c = getChannel(room); + c.bc.postMessage(data); + c.subs.forEach(sub => sub(data, origin)); +}; + +var broadcastchannel = /*#__PURE__*/Object.freeze({ + __proto__: null, + subscribe: subscribe, + unsubscribe: unsubscribe, + publish: publish +}); + +exports.broadcastchannel = broadcastchannel; +exports.publish = publish; +exports.subscribe = subscribe; +exports.unsubscribe = unsubscribe; +//# sourceMappingURL=broadcastchannel-80813eea.cjs.map diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel-80813eea.cjs.map b/nodejs/node_modules/lib0/dist/broadcastchannel-80813eea.cjs.map new file mode 100644 index 00000000..2c2e3a37 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel-80813eea.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"broadcastchannel-80813eea.cjs","sources":["../broadcastchannel.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Helpers for cross-tab communication using broadcastchannel with LocalStorage fallback.\n *\n * ```js\n * // In browser window A:\n * broadcastchannel.subscribe('my events', data => console.log(data))\n * broadcastchannel.publish('my events', 'Hello world!') // => A: 'Hello world!' fires synchronously in same tab\n *\n * // In browser window B:\n * broadcastchannel.publish('my events', 'hello from tab B') // => A: 'hello from tab B'\n * ```\n *\n * @module broadcastchannel\n */\n\n// @todo before next major: use Uint8Array instead as buffer object\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as buffer from './buffer.js'\nimport * as storage from './storage.js'\n\n/**\n * @typedef {Object} Channel\n * @property {Set} Channel.subs\n * @property {any} Channel.bc\n */\n\n/**\n * @type {Map}\n */\nconst channels = new Map()\n\n/* c8 ignore start */\nclass LocalStoragePolyfill {\n /**\n * @param {string} room\n */\n constructor (room) {\n this.room = room\n /**\n * @type {null|function({data:ArrayBuffer}):void}\n */\n this.onmessage = null\n /**\n * @param {any} e\n */\n this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })\n storage.onChange(this._onChange)\n }\n\n /**\n * @param {ArrayBuffer} buf\n */\n postMessage (buf) {\n storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf)))\n }\n\n close () {\n storage.offChange(this._onChange)\n }\n}\n/* c8 ignore stop */\n\n// Use BroadcastChannel or Polyfill\n/* c8 ignore next */\nconst BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel\n\n/**\n * @param {string} room\n * @return {Channel}\n */\nconst getChannel = room =>\n map.setIfUndefined(channels, room, () => {\n const subs = set.create()\n const bc = new BC(room)\n /**\n * @param {{data:ArrayBuffer}} e\n */\n /* c8 ignore next */\n bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'))\n return {\n bc, subs\n }\n })\n\n/**\n * Subscribe to global `publish` events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const subscribe = (room, f) => {\n getChannel(room).subs.add(f)\n return f\n}\n\n/**\n * Unsubscribe from `publish` global events.\n *\n * @function\n * @param {string} room\n * @param {function(any, any):any} f\n */\nexport const unsubscribe = (room, f) => {\n const channel = getChannel(room)\n const unsubscribed = channel.subs.delete(f)\n if (unsubscribed && channel.subs.size === 0) {\n channel.bc.close()\n channels.delete(room)\n }\n return unsubscribed\n}\n\n/**\n * Publish data to all subscribers (including subscribers on this tab)\n *\n * @function\n * @param {string} room\n * @param {any} data\n * @param {any} [origin]\n */\nexport const publish = (room, data, origin = null) => {\n const c = getChannel(room)\n c.bc.postMessage(data)\n c.subs.forEach(sub => sub(data, origin))\n}\n"],"names":["buffer.fromBase64","storage.onChange","storage.varStorage","buffer.toBase64","buffer.createUint8ArrayFromArrayBuffer","storage.offChange","map.setIfUndefined","set.create"],"mappings":";;;;;;;AAAA;AAuBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,IAAI,GAAG,GAAE;AAC1B;AACA;AACA,MAAM,oBAAoB,CAAC;AAC3B;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE;AACrB,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB;AACA;AACA;AACA,IAAI,IAAI,CAAC,SAAS,GAAG,KAAI;AACzB;AACA;AACA;AACA,IAAI,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,IAAI,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAEA,iBAAiB,CAAC,CAAC,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,EAAC;AACpI,IAAIC,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAC;AACpC,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,GAAG,EAAE;AACpB,IAAIC,kBAAkB,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAEC,eAAe,CAACC,sCAAsC,CAAC,GAAG,CAAC,CAAC,EAAC;AACvG,GAAG;AACH;AACA,EAAE,KAAK,CAAC,GAAG;AACX,IAAIC,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAC;AACrC,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA,MAAM,EAAE,GAAG,OAAO,gBAAgB,KAAK,WAAW,GAAG,oBAAoB,GAAG,iBAAgB;AAC5F;AACA;A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MAAM,CAAC,GAAG,UAAU,CAAC,IAAI,EAAC;AAC5B,EAAE,CAAC,CAAC,EAAE,CAAC,WAAW,CAAC,IAAI,EAAC;AACxB,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,EAAC;AAC1C;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel.cjs b/nodejs/node_modules/lib0/dist/broadcastchannel.cjs new file mode 100644 index 00000000..f8c1875d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel.cjs @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./map-0dabcc55.cjs'); +require('./set-0f209abb.cjs'); +require('./buffer-f11b8d4d.cjs'); +require('./storage.cjs'); +var broadcastchannel = require('./broadcastchannel-80813eea.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./math-08e068f9.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./decoding-000d097f.cjs'); +require('./error-8582d695.cjs'); + + + +exports.publish = broadcastchannel.publish; +exports.subscribe = broadcastchannel.subscribe; +exports.unsubscribe = broadcastchannel.unsubscribe; +//# sourceMappingURL=broadcastchannel.cjs.map diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel.cjs.map b/nodejs/node_modules/lib0/dist/broadcastchannel.cjs.map new file mode 100644 index 00000000..38206ece --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"broadcastchannel.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel.d.ts b/nodejs/node_modules/lib0/dist/broadcastchannel.d.ts new file mode 100644 index 00000000..d8f048e5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel.d.ts @@ -0,0 +1,8 @@ +export function subscribe(room: string, f: (arg0: any, arg1: any) => any): (arg0: any, arg1: any) => any; +export function unsubscribe(room: string, f: (arg0: any, arg1: any) => any): boolean; +export function publish(room: string, data: any, origin?: any): void; +export type Channel = { + subs: Set<(arg0: any, arg1: any) => any>; + bc: any; +}; +//# sourceMappingURL=broadcastchannel.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel.d.ts.map b/nodejs/node_modules/lib0/dist/broadcastchannel.d.ts.map new file mode 100644 index 00000000..962d5bea --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"broadcastchannel.d.ts","sourceRoot":"","sources":["../broadcastchannel.js"],"names":[],"mappings":"AA+FO,gCAHI,MAAM,YACG,GAAG,QAAE,GAAG,KAAE,GAAG,UAAb,GAAG,QAAE,GAAG,KAAE,GAAG,CAKhC;AASM,kCAHI,MAAM,YACG,GAAG,QAAE,GAAG,KAAE,GAAG,WAUhC;AAUM,8BAJI,MAAM,QACN,GAAG,WACH,GAAG,QAMb;;UAvGa,WAAa,GAAG,QAAE,GAAG,KAAE,GAAG,CAAC;QAC3B,GAAG"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel.test.d.ts b/nodejs/node_modules/lib0/dist/broadcastchannel.test.d.ts new file mode 100644 index 00000000..a746c1dd --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel.test.d.ts @@ -0,0 +1,3 @@ +export function testBroadcastChannel(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=broadcastchannel.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/broadcastchannel.test.d.ts.map b/nodejs/node_modules/lib0/dist/broadcastchannel.test.d.ts.map new file mode 100644 index 00000000..7566f2f7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/broadcastchannel.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"broadcastchannel.test.d.ts","sourceRoot":"","sources":["../broadcastchannel.test.js"],"names":[],"mappings":"AAMO,yCAFI,EAAE,QAAQ,QAkBpB;mBAtBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/buffer-f11b8d4d.cjs b/nodejs/node_modules/lib0/dist/buffer-f11b8d4d.cjs new file mode 100644 index 00000000..8286d581 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer-f11b8d4d.cjs @@ -0,0 +1,198 @@ +'use strict'; + +var string = require('./string-6d104757.cjs'); +var environment = require('./environment-f4d7c3e5.cjs'); +var array = require('./array-704ca50e.cjs'); +var math = require('./math-08e068f9.cjs'); +var encoding = require('./encoding-882cb136.cjs'); +var decoding = require('./decoding-000d097f.cjs'); + +/** + * Utility functions to work with buffers (Uint8Array). + * + * @module buffer + */ + +/** + * @param {number} len + */ +const createUint8ArrayFromLen = len => new Uint8Array(len); + +/** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + * @param {number} byteOffset + * @param {number} length + */ +const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length); + +/** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + */ +const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer); + +/* c8 ignore start */ +/** + * @param {Uint8Array} bytes + * @return {string} + */ +const toBase64Browser = bytes => { + let s = ''; + for (let i = 0; i < bytes.byteLength; i++) { + s += string.fromCharCode(bytes[i]); + } + // eslint-disable-next-line no-undef + return btoa(s) +}; +/* c8 ignore stop */ + +/** + * @param {Uint8Array} bytes + * @return {string} + */ +const toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64'); + +/* c8 ignore start */ +/** + * @param {string} s + * @return {Uint8Array} + */ +const fromBase64Browser = s => { + // eslint-disable-next-line no-undef + const a = atob(s); + const bytes = createUint8ArrayFromLen(a.length); + for (let i = 0; i < a.length; i++) { + bytes[i] = a.charCodeAt(i); + } + return bytes +}; +/* c8 ignore stop */ + +/** + * @param {string} s + */ +const fromBase64Node = s => { + const buf = Buffer.from(s, 'base64'); + return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength) +}; + +/* c8 ignore next */ +const toBase64 = environment.isBrowser ? toBase64Browser : toBase64Node; + +/* c8 ignore next */ +const fromBase64 = environment.isBrowser ? fromBase64Browser : fromBase64Node; + +/** + * Implements base64url - see https://datatracker.ietf.org/doc/html/rfc4648#section-5 + * @param {Uint8Array} buf + */ +const toBase64UrlEncoded = buf => toBase64(buf).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); + +/** + * @param {string} base64 + */ +const fromBase64UrlEncoded = base64 => fromBase64(base64.replaceAll('-', '+').replaceAll('_', '/')); + +/** + * Base64 is always a more efficient choice. This exists for utility purposes only. + * + * @param {Uint8Array} buf + */ +const toHexString = buf => array.map(buf, b => b.toString(16).padStart(2, '0')).join(''); + +/** + * Note: This function expects that the hex doesn't start with 0x.. + * + * @param {string} hex + */ +const fromHexString = hex => { + const hlen = hex.length; + const buf = new Uint8Array(math.ceil(hlen / 2)); + for (let i = 0; i < hlen; i += 2) { + buf[buf.length - i / 2 - 1] = Number.parseInt(hex.slice(hlen - i - 2, hlen - i), 16); + } + return buf +}; + +/** + * Copy the content of an Uint8Array view to a new ArrayBuffer. + * + * @param {Uint8Array} uint8Array + * @return {Uint8Array} + */ +const copyUint8Array = uint8Array => { + const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); + newBuf.set(uint8Array); + return newBuf +}; + +/** + * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type. + * See encoding.writeAny for more information. + * + * @param {any} data + * @return {Uint8Array} + */ +const encodeAny = data => + encoding.encode(encoder => encoding.writeAny(encoder, data)); + +/** + * Decode an any-encoded value. + * + * @param {Uint8Array} buf + * @return {any} + */ +const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf)); + +/** + * Shift Byte Array {N} bits to the left. Does not expand byte array. + * + * @param {Uint8Array} bs + * @param {number} N should be in the range of [0-7] + */ +const shiftNBitsLeft = (bs, N) => { + if (N === 0) return bs + bs = new Uint8Array(bs); + bs[0] <<= N; + for (let i = 1; i < bs.length; i++) { + bs[i - 1] |= bs[i] >>> (8 - N); + bs[i] <<= N; + } + return bs +}; + +var buffer = /*#__PURE__*/Object.freeze({ + __proto__: null, + createUint8ArrayFromLen: createUint8ArrayFromLen, + createUint8ArrayViewFromArrayBuffer: createUint8ArrayViewFromArrayBuffer, + createUint8ArrayFromArrayBuffer: createUint8ArrayFromArrayBuffer, + toBase64: toBase64, + fromBase64: fromBase64, + toBase64UrlEncoded: toBase64UrlEncoded, + fromBase64UrlEncoded: fromBase64UrlEncoded, + toHexString: toHexString, + fromHexString: fromHexString, + copyUint8Array: copyUint8Array, + encodeAny: encodeAny, + decodeAny: decodeAny, + shiftNBitsLeft: shiftNBitsLeft +}); + +exports.buffer = buffer; +exports.copyUint8Array = copyUint8Array; +exports.createUint8ArrayFromArrayBuffer = createUint8ArrayFromArrayBuffer; +exports.createUint8ArrayFromLen = createUint8ArrayFromLen; +exports.createUint8ArrayViewFromArrayBuffer = createUint8ArrayViewFromArrayBuffer; +exports.decodeAny = decodeAny; +exports.encodeAny = encodeAny; +exports.fromBase64 = fromBase64; +exports.fromBase64UrlEncoded = fromBase64UrlEncoded; +exports.fromHexString = fromHexString; +exports.shiftNBitsLeft = shiftNBitsLeft; +exports.toBase64 = toBase64; +exports.toBase64UrlEncoded = toBase64UrlEncoded; +exports.toHexString = toHexString; +//# sourceMappingURL=buffer-f11b8d4d.cjs.map diff --git a/nodejs/node_modules/lib0/dist/buffer-f11b8d4d.cjs.map b/nodejs/node_modules/lib0/dist/buffer-f11b8d4d.cjs.map new file mode 100644 index 00000000..b70aba26 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer-f11b8d4d.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer-f11b8d4d.cjs","sources":["../buffer.js"],"sourcesContent":["/**\n * Utility functions to work with buffers (Uint8Array).\n *\n * @module buffer\n */\n\nimport * as string from './string.js'\nimport * as env from './environment.js'\nimport * as array from './array.js'\nimport * as math from './math.js'\nimport * as encoding from './encoding.js'\nimport * as decoding from './decoding.js'\n\n/**\n * @param {number} len\n */\nexport const createUint8ArrayFromLen = len => new Uint8Array(len)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n * @param {number} byteOffset\n * @param {number} length\n */\nexport const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length)\n\n/**\n * Create Uint8Array with initial content from buffer\n *\n * @param {ArrayBuffer} buffer\n */\nexport const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer)\n\n/* c8 ignore start */\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Browser = bytes => {\n let s = ''\n for (let i = 0; i < bytes.byteLength; i++) {\n s += string.fromCharCode(bytes[i])\n }\n // eslint-disable-next-line no-undef\n return btoa(s)\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} bytes\n * @return {string}\n */\nconst toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')\n\n/* c8 ignore start */\n/**\n * @param {string} s\n * @return {Uint8Array}\n */\nconst fromBase64Browser = s => {\n // eslint-disable-next-line no-undef\n const a = atob(s)\n const bytes = createUint8ArrayFromLen(a.length)\n for (let i = 0; i < a.length; i++) {\n bytes[i] = a.charCodeAt(i)\n }\n return bytes\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} s\n */\nconst fromBase64Node = s => {\n const buf = Buffer.from(s, 'base64')\n return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n\n/* c8 ignore next */\nexport const toBase64 = env.isBrowser ? toBase64Browser : toBase64Node\n\n/* c8 ignore next */\nexport const fromBase64 = env.isBrowser ? fromBase64Browser : fromBase64Node\n\n/**\n * Implements base64url - see https://datatracker.ietf.org/doc/html/rfc4648#section-5\n * @param {Uint8Array} buf\n */\nexport const toBase64UrlEncoded = buf => toBase64(buf).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')\n\n/**\n * @param {string} base64\n */\nexport const fromBase64UrlEncoded = base64 => fromBase64(base64.replaceAll('-', '+').replaceAll('_', '/'))\n\n/**\n * Base64 is always a more efficient choice. This exists for utility purposes only.\n *\n * @param {Uint8Array} buf\n */\nexport const toHexString = buf => array.map(buf, b => b.toString(16).padStart(2, '0')).join('')\n\n/**\n * Note: This function expects that the hex doesn't start with 0x..\n *\n * @param {string} hex\n */\nexport const fromHexString = hex => {\n const hlen = hex.length\n const buf = new Uint8Array(math.ceil(hlen / 2))\n for (let i = 0; i < hlen; i += 2) {\n buf[buf.length - i / 2 - 1] = Number.parseInt(hex.slice(hlen - i - 2, hlen - i), 16)\n }\n return buf\n}\n\n/**\n * Copy the content of an Uint8Array view to a new ArrayBuffer.\n *\n * @param {Uint8Array} uint8Array\n * @return {Uint8Array}\n */\nexport const copyUint8Array = uint8Array => {\n const newBuf = createUint8ArrayFromLen(uint8Array.byteLength)\n newBuf.set(uint8Array)\n return newBuf\n}\n\n/**\n * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type.\n * See encoding.writeAny for more information.\n *\n * @param {any} data\n * @return {Uint8Array}\n */\nexport const encodeAny = data =>\n encoding.encode(encoder => encoding.writeAny(encoder, data))\n\n/**\n * Decode an any-encoded value.\n *\n * @param {Uint8Array} buf\n * @return {any}\n */\nexport const decodeAny = buf => decoding.readAny(decoding.createDecoder(buf))\n\n/**\n * Shift Byte Array {N} bits to the left. Does not expand byte array.\n *\n * @param {Uint8Array} bs\n * @param {number} N should be in the range of [0-7]\n */\nexport const shiftNBitsLeft = (bs, N) => {\n if (N === 0) return bs\n bs = new Uint8Array(bs)\n bs[0] <<= N\n for (let i = 1; i < bs.length; i++) {\n bs[i - 1] |= bs[i] >>> (8 - N)\n bs[i] <<= N\n }\n return bs\n}\n"],"names":["string.fromCharCode","env.isBrowser","array.map","math.ceil","encoding.encode","encoding.writeAny","decoding.readAny","decoding.createDecoder"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACY,MAAC,uBAAuB,GAAG,GAAG,IAAI,IAAI,UAAU,CAAC,GAAG,EAAC;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,mCAAmC,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,IAAI,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAC;AAC7H;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,+BAA+B,GAAG,MAAM,IAAI,IAAI,UAAU,CAAC,MAAM,EAAC;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,eAAe,GAAG,KAAK,IAAI;AACjC,EAAE,IAAI,CAAC,GAAG,GAAE;AACZ,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;AAC7C,IAAI,CAAC,IAAIA,mBAAmB,CAAC,KAAK,CAAC,CAAC,CAAC,EAAC;AACtC,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,CAAC,CAAC;AAChB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,QAAQ,EAAC;AAC9G;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAi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AACY,MAAC,cAAc,GAAG,CAAC,EAAE,EAAE,CAAC,KAAK;AACzC,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE;AACxB,EAAE,EAAE,GAAG,IAAI,UAAU,CAAC,EAAE,EAAC;AACzB,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,EAAC;AACb,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACtC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAC;AAClC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,EAAC;AACf,GAAG;AACH,EAAE,OAAO,EAAE;AACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/buffer.cjs b/nodejs/node_modules/lib0/dist/buffer.cjs new file mode 100644 index 00000000..f54423e0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer.cjs @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./string-6d104757.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./array-704ca50e.cjs'); +require('./math-08e068f9.cjs'); +require('./encoding-882cb136.cjs'); +require('./decoding-000d097f.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); +require('./map-0dabcc55.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./set-0f209abb.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./error-8582d695.cjs'); + + + +exports.copyUint8Array = buffer.copyUint8Array; +exports.createUint8ArrayFromArrayBuffer = buffer.createUint8ArrayFromArrayBuffer; +exports.createUint8ArrayFromLen = buffer.createUint8ArrayFromLen; +exports.createUint8ArrayViewFromArrayBuffer = buffer.createUint8ArrayViewFromArrayBuffer; +exports.decodeAny = buffer.decodeAny; +exports.encodeAny = buffer.encodeAny; +exports.fromBase64 = buffer.fromBase64; +exports.fromBase64UrlEncoded = buffer.fromBase64UrlEncoded; +exports.fromHexString = buffer.fromHexString; +exports.shiftNBitsLeft = buffer.shiftNBitsLeft; +exports.toBase64 = buffer.toBase64; +exports.toBase64UrlEncoded = buffer.toBase64UrlEncoded; +exports.toHexString = buffer.toHexString; +//# sourceMappingURL=buffer.cjs.map diff --git a/nodejs/node_modules/lib0/dist/buffer.cjs.map b/nodejs/node_modules/lib0/dist/buffer.cjs.map new file mode 100644 index 00000000..35bebb3c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/buffer.d.ts b/nodejs/node_modules/lib0/dist/buffer.d.ts new file mode 100644 index 00000000..23660269 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer.d.ts @@ -0,0 +1,22 @@ +export function createUint8ArrayFromLen(len: number): Uint8Array; +export function createUint8ArrayViewFromArrayBuffer(buffer: ArrayBuffer, byteOffset: number, length: number): Uint8Array; +export function createUint8ArrayFromArrayBuffer(buffer: ArrayBuffer): Uint8Array; +/** + * @param {Uint8Array} bytes + * @return {string} + */ +export function toBase64(bytes: Uint8Array): string; +/** + * @param {string} s + * @return {Uint8Array} + */ +export function fromBase64(s: string): Uint8Array; +export function toBase64UrlEncoded(buf: Uint8Array): string; +export function fromBase64UrlEncoded(base64: string): Uint8Array; +export function toHexString(buf: Uint8Array): string; +export function fromHexString(hex: string): Uint8Array; +export function copyUint8Array(uint8Array: Uint8Array): Uint8Array; +export function encodeAny(data: any): Uint8Array; +export function decodeAny(buf: Uint8Array): any; +export function shiftNBitsLeft(bs: Uint8Array, N: number): Uint8Array; +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/buffer.d.ts.map b/nodejs/node_modules/lib0/dist/buffer.d.ts.map new file mode 100644 index 00000000..876a697f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../buffer.js"],"names":[],"mappings":"AAgBO,6CAFI,MAAM,cAEgD;AAS1D,4DAJI,WAAW,cACX,MAAM,UACN,MAAM,cAE4G;AAOtH,wDAFI,WAAW,cAEyD;AAG/E;;;GAGG;AACH,gCAHW,UAAU,GACT,MAAM,CASjB;AAUD;;;GAGG;AACH,8BAHW,MAAM,GACL,UAAU,CAUrB;AAqBM,wCAFI,UAAU,UAE+F;AAK7G,6CAFI,MAAM,cAEyF;AAOnG,iCAFI,UAAU,UAE0E;AAOxF,mCAFI,MAAM,cAShB;AAQM,2CAHI,UAAU,GACT,UAAU,CAMrB;AASM,gCAHI,GAAG,GACF,UAAU,CAGwC;AAQvD,+BAHI,UAAU,GACT,GAAG,CAE8D;AAQtE,mCAHI,UAAU,KACV,MAAM,cAWhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/buffer.test.d.ts b/nodejs/node_modules/lib0/dist/buffer.test.d.ts new file mode 100644 index 00000000..0bd7014c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer.test.d.ts @@ -0,0 +1,6 @@ +export function testRepeatBase64urlEncoding(tc: t.TestCase): void; +export function testRepeatBase64Encoding(tc: t.TestCase): void; +export function testRepeatHexEncoding(tc: t.TestCase): void; +export function testAnyEncoding(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=buffer.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/buffer.test.d.ts.map b/nodejs/node_modules/lib0/dist/buffer.test.d.ts.map new file mode 100644 index 00000000..edb2df08 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/buffer.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.test.d.ts","sourceRoot":"","sources":["../buffer.test.js"],"names":[],"mappings":"AA2BO,gDAFI,EAAE,QAAQ,QAIpB;AAKM,6CAFI,EAAE,QAAQ,QAIpB;AAKM,0CAFI,EAAE,QAAQ,QAIpB;AAKM,qCAFI,EAAE,QAAQ,QAMpB;mBApDkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/cache.cjs b/nodejs/node_modules/lib0/dist/cache.cjs new file mode 100644 index 00000000..ea380982 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/cache.cjs @@ -0,0 +1,222 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var list = require('./list.cjs'); +var map = require('./map-0dabcc55.cjs'); +var time = require('./time-bc2081b9.cjs'); +require('./function-314fdc56.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./object-fecf6a7b.cjs'); +require('./error-8582d695.cjs'); +require('./metric.cjs'); +require('./math-08e068f9.cjs'); + +/* eslint-env browser */ + +/** + * @template K, V + * + * @implements {list.ListNode} + */ +class Entry { + /** + * @param {K} key + * @param {V | Promise} val + */ + constructor (key, val) { + /** + * @type {this | null} + */ + this.prev = null; + /** + * @type {this | null} + */ + this.next = null; + this.created = time.getUnixTime(); + this.val = val; + this.key = key; + } +} + +/** + * @template K, V + */ +class Cache { + /** + * @param {number} timeout + */ + constructor (timeout) { + this.timeout = timeout; + /** + * @type list.List> + */ + this._q = list.create(); + /** + * @type {Map>} + */ + this._map = map.create(); + } +} + +/** + * @template K, V + * + * @param {Cache} cache + * @return {number} Returns the current timestamp + */ +const removeStale = cache => { + const now = time.getUnixTime(); + const q = cache._q; + while (q.start && now - q.start.created > cache.timeout) { + cache._map.delete(q.start.key); + list.popFront(q); + } + return now +}; + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @param {V} value + */ +const set = (cache, key, value) => { + const now = removeStale(cache); + const q = cache._q; + const n = cache._map.get(key); + if (n) { + list.removeNode(q, n); + list.pushEnd(q, n); + n.created = now; + n.val = value; + } else { + const node = new Entry(key, value); + list.pushEnd(q, node); + cache._map.set(key, node); + } +}; + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @return {Entry | undefined} + */ +const getNode = (cache, key) => { + removeStale(cache); + const n = cache._map.get(key); + if (n) { + return n + } +}; + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @return {V | undefined} + */ +const get = (cache, key) => { + const n = getNode(cache, key); + return n && !(n.val instanceof Promise) ? n.val : undefined +}; + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + */ +const refreshTimeout = (cache, key) => { + const now = time.getUnixTime(); + const q = cache._q; + const n = cache._map.get(key); + if (n) { + list.removeNode(q, n); + list.pushEnd(q, n); + n.created = now; + } +}; + +/** + * Works well in conjunktion with setIfUndefined which has an async init function. + * Using getAsync & setIfUndefined ensures that the init function is only called once. + * + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @return {V | Promise | undefined} + */ +const getAsync = (cache, key) => { + const n = getNode(cache, key); + return n ? n.val : undefined +}; + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + */ +const remove = (cache, key) => { + const n = cache._map.get(key); + if (n) { + list.removeNode(cache._q, n); + cache._map.delete(key); + return n.val && !(n.val instanceof Promise) ? n.val : undefined + } +}; + +/** + * @template K, V + * + * @param {Cache} cache + * @param {K} key + * @param {function():Promise} init + * @param {boolean} removeNull Optional argument that automatically removes values that resolve to null/undefined from the cache. + * @return {Promise | V} + */ +const setIfUndefined = (cache, key, init, removeNull = false) => { + removeStale(cache); + const q = cache._q; + const n = cache._map.get(key); + if (n) { + return n.val + } else { + const p = init(); + const node = new Entry(key, p); + list.pushEnd(q, node); + cache._map.set(key, node); + p.then(v => { + if (p === node.val) { + node.val = v; + } + if (removeNull && v == null) { + remove(cache, key); + } + }); + return p + } +}; + +/** + * @param {number} timeout + */ +const create = timeout => new Cache(timeout); + +exports.Cache = Cache; +exports.create = create; +exports.get = get; +exports.getAsync = getAsync; +exports.refreshTimeout = refreshTimeout; +exports.remove = remove; +exports.removeStale = removeStale; +exports.set = set; +exports.setIfUndefined = setIfUndefined; +//# sourceMappingURL=cache.cjs.map diff --git a/nodejs/node_modules/lib0/dist/cache.cjs.map b/nodejs/node_modules/lib0/dist/cache.cjs.map new file mode 100644 index 00000000..94c8123b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/cache.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.cjs","sources":["../cache.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * An implementation of a map which has keys that expire.\n *\n * @module cache\n */\n\nimport * as list from './list.js'\nimport * as map from './map.js'\nimport * as time from './time.js'\n\n/**\n * @template K, V\n *\n * @implements {list.ListNode}\n */\nclass Entry {\n /**\n * @param {K} key\n * @param {V | Promise} val\n */\n constructor (key, val) {\n /**\n * @type {this | null}\n */\n this.prev = null\n /**\n * @type {this | null}\n */\n this.next = null\n this.created = time.getUnixTime()\n this.val = val\n this.key = key\n }\n}\n\n/**\n * @template K, V\n */\nexport class Cache {\n /**\n * @param {number} timeout\n */\n constructor (timeout) {\n this.timeout = timeout\n /**\n * @type list.List>\n */\n this._q = list.create()\n /**\n * @type {Map>}\n */\n this._map = map.create()\n }\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @return {number} Returns the current timestamp\n */\nexport const removeStale = cache => {\n const now = time.getUnixTime()\n const q = cache._q\n while (q.start && now - q.start.created > cache.timeout) {\n cache._map.delete(q.start.key)\n list.popFront(q)\n }\n return now\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n * @param {V} value\n */\nexport const set = (cache, key, value) => {\n const now = removeStale(cache)\n const q = cache._q\n const n = cache._map.get(key)\n if (n) {\n list.removeNode(q, n)\n list.pushEnd(q, n)\n n.created = now\n n.val = value\n } else {\n const node = new Entry(key, value)\n list.pushEnd(q, node)\n cache._map.set(key, node)\n }\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n * @return {Entry | undefined}\n */\nconst getNode = (cache, key) => {\n removeStale(cache)\n const n = cache._map.get(key)\n if (n) {\n return n\n }\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n * @return {V | undefined}\n */\nexport const get = (cache, key) => {\n const n = getNode(cache, key)\n return n && !(n.val instanceof Promise) ? n.val : undefined\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n */\nexport const refreshTimeout = (cache, key) => {\n const now = time.getUnixTime()\n const q = cache._q\n const n = cache._map.get(key)\n if (n) {\n list.removeNode(q, n)\n list.pushEnd(q, n)\n n.created = now\n }\n}\n\n/**\n * Works well in conjunktion with setIfUndefined which has an async init function.\n * Using getAsync & setIfUndefined ensures that the init function is only called once.\n *\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n * @return {V | Promise | undefined}\n */\nexport const getAsync = (cache, key) => {\n const n = getNode(cache, key)\n return n ? n.val : undefined\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n */\nexport const remove = (cache, key) => {\n const n = cache._map.get(key)\n if (n) {\n list.removeNode(cache._q, n)\n cache._map.delete(key)\n return n.val && !(n.val instanceof Promise) ? n.val : undefined\n }\n}\n\n/**\n * @template K, V\n *\n * @param {Cache} cache\n * @param {K} key\n * @param {function():Promise} init\n * @param {boolean} removeNull Optional argument that automatically removes values that resolve to null/undefined from the cache.\n * @return {Promise | V}\n */\nexport const setIfUndefined = (cache, key, init, removeNull = false) => {\n removeStale(cache)\n const q = cache._q\n const n = cache._map.get(key)\n if (n) {\n return n.val\n } else {\n const p = init()\n const node = new Entry(key, p)\n list.pushEnd(q, node)\n cache._map.set(key, node)\n p.then(v => {\n if (p === node.val) {\n node.val = v\n }\n if (removeNull && v == null) {\n remove(cache, key)\n }\n })\n return p\n }\n}\n\n/**\n * @param {number} timeout\n */\nexport const create = timeout => new Cache(timeout)\n"],"names":["time.getUnixTime","list.create","map.create","list.popFront","list.removeNode","list.pushEnd"],"mappings":";;;;;;;;;;;;;;;AAAA;AAWA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,KAAK,CAAC;AACZ;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE;AACzB;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB,IAAI,IAAI,CAAC,OAAO,GAAGA,gBAAgB,GAAE;AACrC,IAAI,IAAI,CAAC,GAAG,GAAG,IAAG;AAClB,IAAI,IAAI,CAAC,GAAG,GAAG,IAAG;AAClB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACO,MAAM,KAAK,CAAC;AACnB;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,OAAO,EAAE;AACxB,IAAI,IAAI,CAAC,OAAO,GAAG,QAAO;AAC1B;AACA;AACA;AACA,IAAI,IAAI,CAAC,EAAE,GAAGC,WAAW,GAAE;AAC3B;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAGC,UAAU,GAAE;AAC5B,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,KAAK,IAAI;AACpC,EAAE,MAAM,GAAG,GAAGF,gBAAgB,GAAE;AAChC,EAAE,MAAM,CAAC,GAAG,KAAK,CAAC,GAAE;AACpB,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,EAAE;AAC3D,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAC;AAClC,IAAIG,aAAa,CAAC,CAAC,EAAC;AACpB,GAAG;AACH,EAA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,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,GAAG,KAAK,KAAK;AACxE,EAAE,WAAW,CAAC,KAAK,EAAC;AACpB,EAAE,MAAM,CAAC,GAAG,KAAK,CAAC,GAAE;AACpB,EAAE,MAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAC;AAC/B,EAAE,IAAI,CAAC,EAAE;AACT,IAAI,OAAO,CAAC,CAAC,GAAG;AAChB,GAAG,MAAM;AACT,IAAI,MAAM,CAAC,GAAG,IAAI,GAAE;AACpB,IAAI,MAAM,IAAI,GAAG,IAAI,KAAK,CAAC,GAAG,EAAE,CAAC,EAAC;AAClC,IAAIC,YAAY,CAAC,CAAC,EAAE,IAAI,EAAC;AACzB,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAC;AAC7B,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI;AAChB,MAAM,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE;AAC1B,QAAQ,IAAI,CAAC,GAAG,GAAG,EAAC;AACpB,OAAO;AACP,MAAM,IAAI,UAAU,IAAI,CAAC,IAAI,IAAI,EAAE;AACnC,QAAQ,MAAM,CAAC,KAAK,EAAE,GAAG,EAAC;AAC1B,OAAO;AACP,KAAK,EAAC;AACN,IAAI,OAAO,CAAC;AACZ,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,OAAO,IAAI,IAAI,KAAK,CAAC,OAAO;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/cache.d.ts b/nodejs/node_modules/lib0/dist/cache.d.ts new file mode 100644 index 00000000..afcd5643 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/cache.d.ts @@ -0,0 +1,52 @@ +/** + * @template K, V + */ +export class Cache { + /** + * @param {number} timeout + */ + constructor(timeout: number); + timeout: number; + /** + * @type list.List> + */ + _q: list.List>; + /** + * @type {Map>} + */ + _map: Map>; +} +export function removeStale(cache: Cache): number; +export function set(cache: Cache, key: K, value: V): void; +export function get(cache: Cache, key: K): V | undefined; +export function refreshTimeout(cache: Cache, key: K): void; +export function getAsync(cache: Cache, key: K): V | Promise | undefined; +export function remove(cache: Cache, key: K): NonNullable | undefined; +export function setIfUndefined(cache: Cache, key: K, init: () => Promise, removeNull?: boolean): V | Promise; +export function create(timeout: number): Cache; +import * as list from './list.js'; +/** + * @template K, V + * + * @implements {list.ListNode} + */ +declare class Entry implements list.ListNode { + /** + * @param {K} key + * @param {V | Promise} val + */ + constructor(key: K, val: V | Promise); + /** + * @type {this | null} + */ + prev: Entry | null; + /** + * @type {this | null} + */ + next: Entry | null; + created: number; + val: V | Promise; + key: K; +} +export {}; +//# sourceMappingURL=cache.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/cache.d.ts.map b/nodejs/node_modules/lib0/dist/cache.d.ts.map new file mode 100644 index 00000000..2fea9b77 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/cache.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../cache.js"],"names":[],"mappings":"AAqCA;;GAEG;AACH;IACE;;OAEG;IACH,qBAFW,MAAM,EAYhB;IATC,gBAAsB;IACtB;;OAEG;IACH,IAFS,KAAK,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAER;IACvB;;OAEG;IACH,MAFU,IAAI,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAEL;CAE3B;AAQM,uDAFK,MAAM,CAUjB;AASM,sEAcN;AAwBM,qEAGN;AAQM,uEASN;AAYM,uFAGN;AAQM,qFAON;AAWM,sGAHI,OAAO,kBAwBjB;AAKM,gCAFI,MAAM,mBAEkC;sBArM7B,WAAW;AAIjC;;;;GAIG;AACH,qCAFgB,IAAI,CAAC,QAAQ;IAG3B;;;OAGG;IACH,iBAHW,CAAC,OACD,CAAC,GAAG,QAAQ,CAAC,CAAC,EAcxB;IAXC;;OAEG;IACH,yBAAgB;IAChB;;OAEG;IACH,yBAAgB;IAChB,gBAAiC;IACjC,oBAAc;IACd,OAAc;CAEjB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/cache.test.d.ts b/nodejs/node_modules/lib0/dist/cache.test.d.ts new file mode 100644 index 00000000..693e0d4b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/cache.test.d.ts @@ -0,0 +1,3 @@ +export function testCache(tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=cache.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/cache.test.d.ts.map b/nodejs/node_modules/lib0/dist/cache.test.d.ts.map new file mode 100644 index 00000000..4bcfe191 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/cache.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.test.d.ts","sourceRoot":"","sources":["../cache.test.js"],"names":[],"mappings":"AAOO,8BAFI,EAAE,QAAQ,iBA6EpB;mBAlFkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/common.cjs b/nodejs/node_modules/lib0/dist/common.cjs new file mode 100644 index 00000000..cb930ef4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/common.cjs @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var webcrypto = require('lib0/webcrypto'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var webcrypto__namespace = /*#__PURE__*/_interopNamespace(webcrypto); + +/** + * @param {CryptoKey} key + */ +const exportKeyJwk = async key => { + const jwk = await webcrypto__namespace.subtle.exportKey('jwk', key); + jwk.key_ops = key.usages; + return jwk +}; + +/** + * Only suited for exporting public keys. + * + * @param {CryptoKey} key + * @return {Promise} + */ +const exportKeyRaw = key => + webcrypto__namespace.subtle.exportKey('raw', key).then(key => new Uint8Array(key)); + +exports.exportKeyJwk = exportKeyJwk; +exports.exportKeyRaw = exportKeyRaw; +//# sourceMappingURL=common.cjs.map diff --git a/nodejs/node_modules/lib0/dist/common.cjs.map b/nodejs/node_modules/lib0/dist/common.cjs.map new file mode 100644 index 00000000..9d8f2eb2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/common.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"common.cjs","sources":["../crypto/common.js"],"sourcesContent":["import * as webcrypto from 'lib0/webcrypto'\n\n/**\n * @param {CryptoKey} key\n */\nexport const exportKeyJwk = async key => {\n const jwk = await webcrypto.subtle.exportKey('jwk', key)\n jwk.key_ops = key.usages\n return jwk\n}\n\n/**\n * Only suited for exporting public keys.\n *\n * @param {CryptoKey} key\n * @return {Promise}\n */\nexport const exportKeyRaw = key =>\n webcrypto.subtle.exportKey('raw', key).then(key => new Uint8Array(key))\n"],"names":["webcrypto"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;AACA;AACA;AACY,MAAC,YAAY,GAAG,MAAM,GAAG,IAAI;AACzC,EAAE,MAAM,GAAG,GAAG,MAAMA,oBAAS,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAC;AAC1D,EAAE,GAAG,CAAC,OAAO,GAAG,GAAG,CAAC,OAAM;AAC1B,EAAE,OAAO,GAAG;AACZ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,YAAY,GAAG,GAAG;AAC/B,EAAEA,oBAAS,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,UAAU,CAAC,GAAG,CAAC;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/component.cjs b/nodejs/node_modules/lib0/dist/component.cjs new file mode 100644 index 00000000..6117053f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/component.cjs @@ -0,0 +1,427 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var dom = require('./dom-16daf1a0.cjs'); +var diff = require('./diff-fbaa426b.cjs'); +var object = require('./object-fecf6a7b.cjs'); +var json = require('./json-092190a1.cjs'); +var string = require('./string-6d104757.cjs'); +var array = require('./array-704ca50e.cjs'); +var number = require('./number-466d8922.cjs'); +var _function = require('./function-314fdc56.cjs'); +require('./pair-ab022bc3.cjs'); +require('./map-0dabcc55.cjs'); +require('./set-0f209abb.cjs'); +require('./math-08e068f9.cjs'); +require('./binary-ac8e39e2.cjs'); + +/* eslint-env browser */ + +/** + * @type {CustomElementRegistry} + */ +const registry = customElements; + +/** + * @param {string} name + * @param {any} constr + * @param {ElementDefinitionOptions} [opts] + */ +const define = (name, constr, opts) => registry.define(name, constr, opts); + +/** + * @param {string} name + * @return {Promise} + */ +const whenDefined = name => registry.whenDefined(name); + +const upgradedEventName = 'upgraded'; +const connectedEventName = 'connected'; +const disconnectedEventName = 'disconnected'; + +/** + * @template S + */ +class Lib0Component extends HTMLElement { + /** + * @param {S} [state] + */ + constructor (state) { + super(); + /** + * @type {S|null} + */ + this.state = /** @type {any} */ (state); + /** + * @type {any} + */ + this._internal = {}; + } + + /** + * @param {S} _state + * @param {boolean} [_forceStateUpdate] Force that the state is rerendered even if state didn't change + */ + setState (_state, _forceStateUpdate = true) {} + + /** + * @param {any} _stateUpdate + */ + updateState (_stateUpdate) { } +} + +/** + * @param {any} val + * @param {"json"|"string"|"number"} type + * @return {string} + */ +const encodeAttrVal = (val, type) => { + if (type === 'json') { + val = json.stringify(val); + } + return val + '' +}; + +/** + * @param {any} val + * @param {"json"|"string"|"number"|"bool"} type + * @return {any} + */ +const parseAttrVal = (val, type) => { + switch (type) { + case 'json': + return json.parse(val) + case 'number': + return Number.parseFloat(val) + case 'string': + return val + case 'bool': + return val != null + default: + return null + } +}; + +/** + * @typedef {Object} CONF + * @property {string?} [CONF.template] Template for the shadow dom. + * @property {string} [CONF.style] shadow dom style. Is only used when + * `CONF.template` is defined + * @property {S} [CONF.state] Initial component state. + * @property {function(S,S|null,Lib0Component):void} [CONF.onStateChange] Called when + * the state changes. + * @property {Object} [CONF.childStates] maps from + * CSS-selector to transformer function. The first element that matches the + * CSS-selector receives state updates via the transformer function. + * @property {Object} [CONF.attrs] + * attrs-keys and state-keys should be camelCase, but the DOM uses kebap-case. I.e. + * `attrs = { myAttr: 4 }` is represeted as `` in the DOM + * @property {Object):boolean|void>} [CONF.listeners] Maps from dom-event-name + * to event listener. + * @property {function(S, S, Lib0Component):Object} [CONF.slots] Fill slots + * automatically when state changes. Maps from slot-name to slot-html. + * @template S + */ + +/** + * @template T + * @param {string} name + * @param {CONF} cnf + * @return {typeof Lib0Component} + */ +const createComponent = (name, { template, style = '', state: defaultState, onStateChange = () => {}, childStates = { }, attrs = {}, listeners = {}, slots = () => ({}) }) => { + /** + * Maps from camelCase attribute name to kebap-case attribute name. + * @type {Object} + */ + const normalizedAttrs = {}; + for (const key in attrs) { + normalizedAttrs[string.fromCamelCase(key, '-')] = key; + } + const templateElement = template + ? /** @type {HTMLTemplateElement} */ (dom.parseElement(` + + `)) + : null; + + class _Lib0Component extends HTMLElement { + /** + * @param {T} [state] + */ + constructor (state) { + super(); + /** + * @type {Array<{d:Lib0Component, s:function(any, any):Object}>} + */ + this._childStates = []; + /** + * @type {Object} + */ + this._slots = {}; + this._init = false; + /** + * @type {any} + */ + this._internal = {}; + /** + * @type {any} + */ + this.state = state || null; + this.connected = false; + // init shadow dom + if (templateElement) { + const shadow = /** @type {ShadowRoot} */ (this.attachShadow({ mode: 'open' })); + shadow.appendChild(templateElement.content.cloneNode(true)); + // fill child states + for (const key in childStates) { + this._childStates.push({ + d: /** @type {Lib0Component} */ (dom.querySelector(/** @type {any} */ (shadow), key)), + s: childStates[key] + }); + } + } + dom.emitCustomEvent(this, upgradedEventName, { bubbles: true }); + } + + connectedCallback () { + this.connected = true; + if (!this._init) { + this._init = true; + const shadow = this.shadowRoot; + if (shadow) { + dom.addEventListener(shadow, upgradedEventName, event => { + this.setState(this.state, true); + event.stopPropagation(); + }); + } + /** + * @type {Object} + */ + const startState = this.state || object.assign({}, defaultState); + if (attrs) { + for (const key in attrs) { + const normalizedKey = string.fromCamelCase(key, '-'); + const val = parseAttrVal(this.getAttribute(normalizedKey), attrs[key]); + if (val) { + startState[key] = val; + } + } + } + // add event listeners + for (const key in listeners) { + dom.addEventListener(shadow || this, key, event => { + if (listeners[key](/** @type {CustomEvent} */ (event), this) !== false) { + event.stopPropagation(); + event.preventDefault(); + return false + } + }); + } + // first setState call + this.state = null; + this.setState(startState); + } + dom.emitCustomEvent(/** @type {any} */ (this.shadowRoot || this), connectedEventName, { bubbles: true }); + } + + disconnectedCallback () { + this.connected = false; + dom.emitCustomEvent(/** @type {any} */ (this.shadowRoot || this), disconnectedEventName, { bubbles: true }); + this.setState(null); + } + + static get observedAttributes () { + return object.keys(normalizedAttrs) + } + + /** + * @param {string} name + * @param {string} oldVal + * @param {string} newVal + * + * @private + */ + attributeChangedCallback (name, oldVal, newVal) { + const curState = /** @type {any} */ (this.state); + const camelAttrName = normalizedAttrs[name]; + const type = attrs[camelAttrName]; + const parsedVal = parseAttrVal(newVal, type); + if (curState && (type !== 'json' || json.stringify(curState[camelAttrName]) !== newVal) && curState[camelAttrName] !== parsedVal && !number.isNaN(parsedVal)) { + this.updateState({ [camelAttrName]: parsedVal }); + } + } + + /** + * @param {any} stateUpdate + */ + updateState (stateUpdate) { + this.setState(object.assign({}, this.state, stateUpdate)); + } + + /** + * @param {any} state + */ + setState (state, forceStateUpdates = false) { + const prevState = this.state; + this.state = state; + if (this._init && (!_function.equalityFlat(state, prevState) || forceStateUpdates)) { + // fill slots + if (state) { + const slotElems = slots(state, prevState, this); + for (const key in slotElems) { + const slotContent = slotElems[key]; + if (this._slots[key] !== slotContent) { + this._slots[key] = slotContent; + const currentSlots = /** @type {Array} */ (key !== 'default' ? array.from(dom.querySelectorAll(this, `[slot="${key}"]`)) : array.from(this.childNodes).filter(/** @param {any} child */ child => !dom.checkNodeType(child, dom.ELEMENT_NODE) || !child.hasAttribute('slot'))); + currentSlots.slice(1).map(dom.remove); + const nextSlot = dom.parseFragment(slotContent); + if (key !== 'default') { + array.from(nextSlot.children).forEach(c => c.setAttribute('slot', key)); + } + if (currentSlots.length > 0) { + dom.replaceWith(currentSlots[0], nextSlot); + } else { + dom.appendChild(this, nextSlot); + } + } + } + } + onStateChange(state, prevState, this); + if (state != null) { + this._childStates.forEach(cnf => { + const d = cnf.d; + if (d.updateState) { + d.updateState(cnf.s(state, this)); + } + }); + } + for (const key in attrs) { + const normalizedKey = string.fromCamelCase(key, '-'); + if (state == null) { + this.removeAttribute(normalizedKey); + } else { + const stateVal = state[key]; + const attrsType = attrs[key]; + if (!prevState || prevState[key] !== stateVal) { + if (attrsType === 'bool') { + if (stateVal) { + this.setAttribute(normalizedKey, ''); + } else { + this.removeAttribute(normalizedKey); + } + } else if (stateVal == null && (attrsType === 'string' || attrsType === 'number')) { + this.removeAttribute(normalizedKey); + } else { + this.setAttribute(normalizedKey, encodeAttrVal(stateVal, attrsType)); + } + } + } + } + } + } + } + define(name, _Lib0Component); + // @ts-ignore + return _Lib0Component +}; + +/** + * @param {function} definer function that defines a component when executed + */ +const createComponentDefiner = definer => { + /** + * @type {any} + */ + let defined = null; + return () => { + if (!defined) { + defined = definer(); + } + return defined + } +}; + +const defineListComponent = createComponentDefiner(() => { + const ListItem = createComponent('lib0-list-item', { + template: '', + slots: state => ({ + content: `
${state}
` + }) + }); + return createComponent('lib0-list', { + state: { list: /** @type {Array} */ ([]), Item: ListItem }, + onStateChange: (state, prevState, component) => { + if (state == null) { + return + } + const { list = /** @type {Array} */ ([]), Item = ListItem } = state; + // @todo deep compare here by providing another parameter to simpleDiffArray + let { index, remove, insert } = diff.simpleDiffArray(prevState ? prevState.list : [], list, _function.equalityFlat); + if (remove === 0 && insert.length === 0) { + return + } + let child = /** @type {Lib0Component} */ (component.firstChild); + while (index-- > 0) { + child = /** @type {Lib0Component} */ (child.nextElementSibling); + } + let insertStart = 0; + while (insertStart < insert.length && remove-- > 0) { + // update existing state + child.setState(insert[insertStart++]); + child = /** @type {Lib0Component} */ (child.nextElementSibling); + } + while (remove-- > 0) { + // remove remaining + const prevChild = child; + child = /** @type {Lib0Component} */ (child.nextElementSibling); + component.removeChild(prevChild); + } + // insert remaining + component.insertBefore(dom.fragment(insert.slice(insertStart).map(/** @param {any} insState */ insState => { + const el = new Item(); + el.setState(insState); + return el + })), child); + } + }) +}); + +const defineLazyLoadingComponent = createComponentDefiner(() => createComponent('lib0-lazy', { + state: /** @type {{component:null|String,import:null|function():Promise,state:null|object}} */ ({ + component: null, import: null, state: null + }), + attrs: { + component: 'string' + }, + onStateChange: ({ component, state, import: getImport }, prevState, componentEl) => { + if (component !== null) { + if (getImport) { + getImport(); + } + if (!prevState || component !== prevState.component) { + const el = /** @type {any} */ (dom.createElement(component)); + componentEl.innerHTML = ''; + componentEl.insertBefore(el, null); + } + const el = /** @type {any} */ (componentEl.firstElementChild); + // @todo generalize setting state and check if setState is defined + if (el.setState) { + el.setState(state); + } + } + } +})); + +exports.Lib0Component = Lib0Component; +exports.createComponent = createComponent; +exports.createComponentDefiner = createComponentDefiner; +exports.define = define; +exports.defineLazyLoadingComponent = defineLazyLoadingComponent; +exports.defineListComponent = defineListComponent; +exports.registry = registry; +exports.whenDefined = whenDefined; +//# sourceMappingURL=component.cjs.map diff --git a/nodejs/node_modules/lib0/dist/component.cjs.map b/nodejs/node_modules/lib0/dist/component.cjs.map new file mode 100644 index 00000000..ac7d0df9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/component.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"component.cjs","sources":["../component.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Web components.\n *\n * @module component\n */\n\nimport * as dom from './dom.js'\nimport * as diff from './diff.js'\nimport * as object from './object.js'\nimport * as json from './json.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\nimport * as number from './number.js'\nimport * as func from './function.js'\n\n/**\n * @type {CustomElementRegistry}\n */\nexport const registry = customElements\n\n/**\n * @param {string} name\n * @param {any} constr\n * @param {ElementDefinitionOptions} [opts]\n */\nexport const define = (name, constr, opts) => registry.define(name, constr, opts)\n\n/**\n * @param {string} name\n * @return {Promise}\n */\nexport const whenDefined = name => registry.whenDefined(name)\n\nconst upgradedEventName = 'upgraded'\nconst connectedEventName = 'connected'\nconst disconnectedEventName = 'disconnected'\n\n/**\n * @template S\n */\nexport class Lib0Component extends HTMLElement {\n /**\n * @param {S} [state]\n */\n constructor (state) {\n super()\n /**\n * @type {S|null}\n */\n this.state = /** @type {any} */ (state)\n /**\n * @type {any}\n */\n this._internal = {}\n }\n\n /**\n * @param {S} _state\n * @param {boolean} [_forceStateUpdate] Force that the state is rerendered even if state didn't change\n */\n setState (_state, _forceStateUpdate = true) {}\n\n /**\n * @param {any} _stateUpdate\n */\n updateState (_stateUpdate) { }\n}\n\n/**\n * @param {any} val\n * @param {\"json\"|\"string\"|\"number\"} type\n * @return {string}\n */\nconst encodeAttrVal = (val, type) => {\n if (type === 'json') {\n val = json.stringify(val)\n }\n return val + ''\n}\n\n/**\n * @param {any} val\n * @param {\"json\"|\"string\"|\"number\"|\"bool\"} type\n * @return {any}\n */\nconst parseAttrVal = (val, type) => {\n switch (type) {\n case 'json':\n return json.parse(val)\n case 'number':\n return Number.parseFloat(val)\n case 'string':\n return val\n case 'bool':\n return val != null\n default:\n return null\n }\n}\n\n/**\n * @typedef {Object} CONF\n * @property {string?} [CONF.template] Template for the shadow dom.\n * @property {string} [CONF.style] shadow dom style. Is only used when\n * `CONF.template` is defined\n * @property {S} [CONF.state] Initial component state.\n * @property {function(S,S|null,Lib0Component):void} [CONF.onStateChange] Called when\n * the state changes.\n * @property {Object} [CONF.childStates] maps from\n * CSS-selector to transformer function. The first element that matches the\n * CSS-selector receives state updates via the transformer function.\n * @property {Object} [CONF.attrs]\n * attrs-keys and state-keys should be camelCase, but the DOM uses kebap-case. I.e.\n * `attrs = { myAttr: 4 }` is represeted as `` in the DOM\n * @property {Object):boolean|void>} [CONF.listeners] Maps from dom-event-name\n * to event listener.\n * @property {function(S, S, Lib0Component):Object} [CONF.slots] Fill slots\n * automatically when state changes. Maps from slot-name to slot-html.\n * @template S\n */\n\n/**\n * @template T\n * @param {string} name\n * @param {CONF} cnf\n * @return {typeof Lib0Component}\n */\nexport const createComponent = (name, { template, style = '', state: defaultState, onStateChange = () => {}, childStates = { }, attrs = {}, listeners = {}, slots = () => ({}) }) => {\n /**\n * Maps from camelCase attribute name to kebap-case attribute name.\n * @type {Object}\n */\n const normalizedAttrs = {}\n for (const key in attrs) {\n normalizedAttrs[string.fromCamelCase(key, '-')] = key\n }\n const templateElement = template\n ? /** @type {HTMLTemplateElement} */ (dom.parseElement(`\n \n `))\n : null\n\n class _Lib0Component extends HTMLElement {\n /**\n * @param {T} [state]\n */\n constructor (state) {\n super()\n /**\n * @type {Array<{d:Lib0Component, s:function(any, any):Object}>}\n */\n this._childStates = []\n /**\n * @type {Object}\n */\n this._slots = {}\n this._init = false\n /**\n * @type {any}\n */\n this._internal = {}\n /**\n * @type {any}\n */\n this.state = state || null\n this.connected = false\n // init shadow dom\n if (templateElement) {\n const shadow = /** @type {ShadowRoot} */ (this.attachShadow({ mode: 'open' }))\n shadow.appendChild(templateElement.content.cloneNode(true))\n // fill child states\n for (const key in childStates) {\n this._childStates.push({\n d: /** @type {Lib0Component} */ (dom.querySelector(/** @type {any} */ (shadow), key)),\n s: childStates[key]\n })\n }\n }\n dom.emitCustomEvent(this, upgradedEventName, { bubbles: true })\n }\n\n connectedCallback () {\n this.connected = true\n if (!this._init) {\n this._init = true\n const shadow = this.shadowRoot\n if (shadow) {\n dom.addEventListener(shadow, upgradedEventName, event => {\n this.setState(this.state, true)\n event.stopPropagation()\n })\n }\n /**\n * @type {Object}\n */\n const startState = this.state || object.assign({}, defaultState)\n if (attrs) {\n for (const key in attrs) {\n const normalizedKey = string.fromCamelCase(key, '-')\n const val = parseAttrVal(this.getAttribute(normalizedKey), attrs[key])\n if (val) {\n startState[key] = val\n }\n }\n }\n // add event listeners\n for (const key in listeners) {\n dom.addEventListener(shadow || this, key, event => {\n if (listeners[key](/** @type {CustomEvent} */ (event), this) !== false) {\n event.stopPropagation()\n event.preventDefault()\n return false\n }\n })\n }\n // first setState call\n this.state = null\n this.setState(startState)\n }\n dom.emitCustomEvent(/** @type {any} */ (this.shadowRoot || this), connectedEventName, { bubbles: true })\n }\n\n disconnectedCallback () {\n this.connected = false\n dom.emitCustomEvent(/** @type {any} */ (this.shadowRoot || this), disconnectedEventName, { bubbles: true })\n this.setState(null)\n }\n\n static get observedAttributes () {\n return object.keys(normalizedAttrs)\n }\n\n /**\n * @param {string} name\n * @param {string} oldVal\n * @param {string} newVal\n *\n * @private\n */\n attributeChangedCallback (name, oldVal, newVal) {\n const curState = /** @type {any} */ (this.state)\n const camelAttrName = normalizedAttrs[name]\n const type = attrs[camelAttrName]\n const parsedVal = parseAttrVal(newVal, type)\n if (curState && (type !== 'json' || json.stringify(curState[camelAttrName]) !== newVal) && curState[camelAttrName] !== parsedVal && !number.isNaN(parsedVal)) {\n this.updateState({ [camelAttrName]: parsedVal })\n }\n }\n\n /**\n * @param {any} stateUpdate\n */\n updateState (stateUpdate) {\n this.setState(object.assign({}, this.state, stateUpdate))\n }\n\n /**\n * @param {any} state\n */\n setState (state, forceStateUpdates = false) {\n const prevState = this.state\n this.state = state\n if (this._init && (!func.equalityFlat(state, prevState) || forceStateUpdates)) {\n // fill slots\n if (state) {\n const slotElems = slots(state, prevState, this)\n for (const key in slotElems) {\n const slotContent = slotElems[key]\n if (this._slots[key] !== slotContent) {\n this._slots[key] = slotContent\n const currentSlots = /** @type {Array} */ (key !== 'default' ? array.from(dom.querySelectorAll(this, `[slot=\"${key}\"]`)) : array.from(this.childNodes).filter(/** @param {any} child */ child => !dom.checkNodeType(child, dom.ELEMENT_NODE) || !child.hasAttribute('slot')))\n currentSlots.slice(1).map(dom.remove)\n const nextSlot = dom.parseFragment(slotContent)\n if (key !== 'default') {\n array.from(nextSlot.children).forEach(c => c.setAttribute('slot', key))\n }\n if (currentSlots.length > 0) {\n dom.replaceWith(currentSlots[0], nextSlot)\n } else {\n dom.appendChild(this, nextSlot)\n }\n }\n }\n }\n onStateChange(state, prevState, this)\n if (state != null) {\n this._childStates.forEach(cnf => {\n const d = cnf.d\n if (d.updateState) {\n d.updateState(cnf.s(state, this))\n }\n })\n }\n for (const key in attrs) {\n const normalizedKey = string.fromCamelCase(key, '-')\n if (state == null) {\n this.removeAttribute(normalizedKey)\n } else {\n const stateVal = state[key]\n const attrsType = attrs[key]\n if (!prevState || prevState[key] !== stateVal) {\n if (attrsType === 'bool') {\n if (stateVal) {\n this.setAttribute(normalizedKey, '')\n } else {\n this.removeAttribute(normalizedKey)\n }\n } else if (stateVal == null && (attrsType === 'string' || attrsType === 'number')) {\n this.removeAttribute(normalizedKey)\n } else {\n this.setAttribute(normalizedKey, encodeAttrVal(stateVal, attrsType))\n }\n }\n }\n }\n }\n }\n }\n define(name, _Lib0Component)\n // @ts-ignore\n return _Lib0Component\n}\n\n/**\n * @param {function} definer function that defines a component when executed\n */\nexport const createComponentDefiner = definer => {\n /**\n * @type {any}\n */\n let defined = null\n return () => {\n if (!defined) {\n defined = definer()\n }\n return defined\n }\n}\n\nexport const defineListComponent = createComponentDefiner(() => {\n const ListItem = createComponent('lib0-list-item', {\n template: '',\n slots: state => ({\n content: `
${state}
`\n })\n })\n return createComponent('lib0-list', {\n state: { list: /** @type {Array} */ ([]), Item: ListItem },\n onStateChange: (state, prevState, component) => {\n if (state == null) {\n return\n }\n const { list = /** @type {Array} */ ([]), Item = ListItem } = state\n // @todo deep compare here by providing another parameter to simpleDiffArray\n let { index, remove, insert } = diff.simpleDiffArray(prevState ? prevState.list : [], list, func.equalityFlat)\n if (remove === 0 && insert.length === 0) {\n return\n }\n let child = /** @type {Lib0Component} */ (component.firstChild)\n while (index-- > 0) {\n child = /** @type {Lib0Component} */ (child.nextElementSibling)\n }\n let insertStart = 0\n while (insertStart < insert.length && remove-- > 0) {\n // update existing state\n child.setState(insert[insertStart++])\n child = /** @type {Lib0Component} */ (child.nextElementSibling)\n }\n while (remove-- > 0) {\n // remove remaining\n const prevChild = child\n child = /** @type {Lib0Component} */ (child.nextElementSibling)\n component.removeChild(prevChild)\n }\n // insert remaining\n component.insertBefore(dom.fragment(insert.slice(insertStart).map(/** @param {any} insState */ insState => {\n const el = new Item()\n el.setState(insState)\n return el\n })), child)\n }\n })\n})\n\nexport const defineLazyLoadingComponent = createComponentDefiner(() => createComponent('lib0-lazy', {\n state: /** @type {{component:null|String,import:null|function():Promise,state:null|object}} */ ({\n component: null, import: null, state: null\n }),\n attrs: {\n component: 'string'\n },\n onStateChange: ({ component, state, import: getImport }, prevState, componentEl) => {\n if (component !== null) {\n if (getImport) {\n getImport()\n }\n if (!prevState || component !== prevState.component) {\n const el = /** @type {any} */ (dom.createElement(component))\n componentEl.innerHTML = ''\n componentEl.insertBefore(el, null)\n }\n const el = /** @type {any} */ (componentEl.firstElementChild)\n // @todo generalize setting state and check if setState is defined\n if (el.setState) {\n el.setState(state)\n }\n }\n }\n}))\n"],"names":["json.stringify","json.parse","string.fromCamelCase","dom.parseElement","dom.querySelector","dom.emitCustomEvent","dom.addEventListener","object.assign","object.keys","number.isNaN","func.equalityFlat","array.from","dom.querySelectorAll","dom.checkNodeType","dom.ELEMENT_NODE","dom.remove","dom.parseFragment","dom.replaceWith","dom.appendChild","diff.simpleDiffArray","dom.fragment","dom.createElement"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAgBA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AAQ,CAAC,QAAQ,EAAC;AAC7B,QAAQ,OAAO,EAAE;AACjB,OAAO,CAAC,CAAC,EAAE,KAAK,EAAC;AACjB,KAAK;AACL,GAAG,CAAC;AACJ,CAAC,EAAC;AACF;AACY,MAAC,0BAA0B,GAAG,sBAAsB,CAAC,MAAM,eAAe,CAAC,WAAW,EAAE;AACpG,EAAE,KAAK,gGAAgG;AACvG,IAAI,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI;AAC9C,GAAG,CAAC;AACJ,EAAE,KAAK,EAAE;AACT,IAAI,SAAS,EAAE,QAAQ;AACvB,GAAG;AACH,EAAE,aAAa,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,EAAE,WAAW,KAAK;AACtF,IAAI,IAAI,SAAS,KAAK,IAAI,EAAE;AAC5B,MAAM,IAAI,SAAS,EAAE;AACrB,QAAQ,SAAS,GAAE;AACnB,OAAO;AACP,MAAM,IAAI,CAAC,SAAS,IAAI,SAAS,KAAK,SAAS,CAAC,SAAS,EAAE;AAC3D,QAAQ,MAAM,EAAE,uBAAuBC,iBAAiB,CAAC,SAAS,CAAC,EAAC;AACpE,QAAQ,WAAW,CAAC,SAAS,GAAG,GAAE;AAClC,QAAQ,WAAW,CAAC,YAAY,CAAC,EAAE,EAAE,IAAI,EAAC;AAC1C,OAAO;AACP,MAAM,MAAM,EAAE,uBAAuB,WAAW,CAAC,iBAAiB,EAAC;AACnE;AACA,MAAM,IAAI,EAAE,CAAC,QAAQ,EAAE;AACvB,QAAQ,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAC;AAC1B,OAAO;AACP,KAAK;AACL,GAAG;AACH,CAAC,CAAC;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/component.d.ts b/nodejs/node_modules/lib0/dist/component.d.ts new file mode 100644 index 00000000..2f0e2b98 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/component.d.ts @@ -0,0 +1,86 @@ +/** + * @type {CustomElementRegistry} + */ +export const registry: CustomElementRegistry; +export function define(name: string, constr: any, opts?: ElementDefinitionOptions | undefined): void; +export function whenDefined(name: string): Promise; +/** + * @template S + */ +export class Lib0Component extends HTMLElement { + /** + * @param {S} [state] + */ + constructor(state?: S | undefined); + /** + * @type {S|null} + */ + state: S | null; + /** + * @type {any} + */ + _internal: any; + /** + * @param {S} _state + * @param {boolean} [_forceStateUpdate] Force that the state is rerendered even if state didn't change + */ + setState(_state: S, _forceStateUpdate?: boolean | undefined): void; + /** + * @param {any} _stateUpdate + */ + updateState(_stateUpdate: any): void; +} +export function createComponent(name: string, { template, style, state: defaultState, onStateChange, childStates, attrs, listeners, slots }: CONF): typeof Lib0Component; +export function createComponentDefiner(definer: Function): () => any; +export function defineListComponent(): any; +export function defineLazyLoadingComponent(): any; +export type CONF = { + /** + * Template for the shadow dom. + */ + template?: string | null | undefined; + /** + * shadow dom style. Is only used when + * `CONF.template` is defined + */ + style?: string | undefined; + /** + * Initial component state. + */ + state?: S | undefined; + /** + * Called when + * the state changes. + */ + onStateChange?: ((arg0: S, arg1: S | null, arg2: Lib0Component) => void) | undefined; + /** + * maps from + * CSS-selector to transformer function. The first element that matches the + * CSS-selector receives state updates via the transformer function. + */ + childStates?: { + [x: string]: (arg0: any, arg1: any) => Object; + } | undefined; + /** + * attrs-keys and state-keys should be camelCase, but the DOM uses kebap-case. I.e. + * `attrs = { myAttr: 4 }` is represeted as `` in the DOM + */ + attrs?: { + [x: string]: "string" | "number" | "json" | "bool"; + } | undefined; + /** + * Maps from dom-event-name + * to event listener. + */ + listeners?: { + [x: string]: (arg0: CustomEvent, arg1: Lib0Component) => boolean | void; + } | undefined; + /** + * Fill slots + * automatically when state changes. Maps from slot-name to slot-html. + */ + slots?: ((arg0: S, arg1: S, arg2: Lib0Component) => { + [x: string]: string; + }) | undefined; +}; +//# sourceMappingURL=component.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/component.d.ts.map b/nodejs/node_modules/lib0/dist/component.d.ts.map new file mode 100644 index 00000000..9bf3600e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/component.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"component.d.ts","sourceRoot":"","sources":["../component.js"],"names":[],"mappings":"AAiBA;;GAEG;AACH,uBAFU,qBAAqB,CAEO;AAO/B,6BAJI,MAAM,UACN,GAAG,qDAGmE;AAM1E,kCAHI,MAAM,GACL,QAAQ,wBAAwB,CAAC,CAEgB;AAM7D;;GAEG;AACH;IACE;;OAEG;IACH,mCAUC;IARC;;OAEG;IACH,OAFU,CAAC,GAAC,IAAI,CAEuB;IACvC;;OAEG;IACH,WAFU,GAAG,CAEM;IAGrB;;;OAGG;IACH,iBAHW,CAAC,iDAGkC;IAE9C;;QAEI;IACJ,0BAFY,GAAG,QAEe;CAC/B;AA6DM,yCAJI,MAAM,2GAEL,oBAAoB,CAuM/B;AAKM,qEAWN;AANQ,2CAKN;AALM,kDAKN;;;;;;;;;;;;;;;;;;;4BAzOoB,CAAC,QAAC,CAAC,GAAC,IAAI,QAAC,cAAc,CAAC,CAAC,KAAE,IAAI;;;;;;;4BAEjB,GAAG,QAAE,GAAG,KAAE,MAAM;;;;;;;;;;;;;;4BAMf,WAAW,QAAE,cAAc,GAAG,CAAC,KAAE,OAAO,GAAC,IAAI;;;;;;oBAE5D,CAAC,QAAE,CAAC,QAAE,cAAc,CAAC,CAAC;YAAS,MAAM,GAAC,MAAM"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/conditions-f5c0c102.cjs b/nodejs/node_modules/lib0/dist/conditions-f5c0c102.cjs new file mode 100644 index 00000000..262c8ccb --- /dev/null +++ b/nodejs/node_modules/lib0/dist/conditions-f5c0c102.cjs @@ -0,0 +1,24 @@ +'use strict'; + +/** + * Often used conditions. + * + * @module conditions + */ + +/** + * @template T + * @param {T|null|undefined} v + * @return {T|null} + */ +/* c8 ignore next */ +const undefinedToNull = v => v === undefined ? null : v; + +var conditions = /*#__PURE__*/Object.freeze({ + __proto__: null, + undefinedToNull: undefinedToNull +}); + +exports.conditions = conditions; +exports.undefinedToNull = undefinedToNull; +//# sourceMappingURL=conditions-f5c0c102.cjs.map diff --git a/nodejs/node_modules/lib0/dist/conditions-f5c0c102.cjs.map b/nodejs/node_modules/lib0/dist/conditions-f5c0c102.cjs.map new file mode 100644 index 00000000..fea384d9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/conditions-f5c0c102.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"conditions-f5c0c102.cjs","sources":["../conditions.js"],"sourcesContent":["/**\n * Often used conditions.\n *\n * @module conditions\n */\n\n/**\n * @template T\n * @param {T|null|undefined} v\n * @return {T|null}\n */\n/* c8 ignore next */\nexport const undefinedToNull = v => v === undefined ? null : v\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,eAAe,GAAG,CAAC,IAAI,CAAC,KAAK,SAAS,GAAG,IAAI,GAAG;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/conditions.cjs b/nodejs/node_modules/lib0/dist/conditions.cjs new file mode 100644 index 00000000..789d383c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/conditions.cjs @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var conditions = require('./conditions-f5c0c102.cjs'); + + + +exports.undefinedToNull = conditions.undefinedToNull; +//# sourceMappingURL=conditions.cjs.map diff --git a/nodejs/node_modules/lib0/dist/conditions.cjs.map b/nodejs/node_modules/lib0/dist/conditions.cjs.map new file mode 100644 index 00000000..1f545ee5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/conditions.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"conditions.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/conditions.d.ts b/nodejs/node_modules/lib0/dist/conditions.d.ts new file mode 100644 index 00000000..0ed4306a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/conditions.d.ts @@ -0,0 +1,2 @@ +export function undefinedToNull(v: T | null | undefined): T | null; +//# sourceMappingURL=conditions.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/conditions.d.ts.map b/nodejs/node_modules/lib0/dist/conditions.d.ts.map new file mode 100644 index 00000000..5f94287b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/conditions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"conditions.d.ts","sourceRoot":"","sources":["../conditions.js"],"names":[],"mappings":"AAYO,sEAAuD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto.test.d.ts b/nodejs/node_modules/lib0/dist/crypto.test.d.ts new file mode 100644 index 00000000..050692d3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto.test.d.ts @@ -0,0 +1,9 @@ +export function testJwt(_tc: t.TestCase): Promise; +export function testEncryption(tc: t.TestCase): Promise; +export function testReapeatEncryption(tc: t.TestCase): Promise; +export function testImportExport(tc: t.TestCase): Promise; +export function testEncryptionPerformance(tc: t.TestCase): Promise; +export function testConsistentKeyGeneration(_tc: t.TestCase): Promise; +export function testSigning(tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=crypto.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto.test.d.ts.map b/nodejs/node_modules/lib0/dist/crypto.test.d.ts.map new file mode 100644 index 00000000..738ec004 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto.test.d.ts","sourceRoot":"","sources":["../crypto.test.js"],"names":[],"mappings":"AAYO,6BAFI,EAAE,QAAQ,iBA8BpB;AAKM,mCAFI,EAAE,QAAQ,iBAoCpB;AAKM,0CAFI,EAAE,QAAQ,iBA8BpB;AAKM,qCAFI,EAAE,QAAQ,iBAgDpB;AAKM,8CAFI,EAAE,QAAQ,iBAwCpB;AAKM,iDAFI,EAAE,QAAQ,iBA2EpB;AAKM,gCAFI,EAAE,QAAQ,iBAapB;mBAvSkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/aes-gcm.d.ts b/nodejs/node_modules/lib0/dist/crypto/aes-gcm.d.ts new file mode 100644 index 00000000..11509cb1 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/aes-gcm.d.ts @@ -0,0 +1,17 @@ +export function encrypt(key: CryptoKey, data: Uint8Array): Promise; +export function decrypt(key: CryptoKey, data: Uint8Array): PromiseLike; +export function importKeyJwk(jwk: any, { usages, extractable }?: { + usages?: Usages | undefined; + extractable?: boolean | undefined; +}): Promise; +export function importKeyRaw(raw: Uint8Array, { usages, extractable }?: { + usages?: Usages | undefined; + extractable?: boolean | undefined; +}): Promise; +export function deriveKey(secret: Uint8Array | string, salt: Uint8Array | string, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export type Usages = Array<'encrypt' | 'decrypt'>; +export { exportKeyJwk, exportKeyRaw } from "./common.js"; +//# sourceMappingURL=aes-gcm.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/aes-gcm.d.ts.map b/nodejs/node_modules/lib0/dist/crypto/aes-gcm.d.ts.map new file mode 100644 index 00000000..e4c959c3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/aes-gcm.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"aes-gcm.d.ts","sourceRoot":"","sources":["../../crypto/aes-gcm.js"],"names":[],"mappings":"AAuBO,6BAHI,SAAS,QACT,UAAU,uBAkBpB;AAWM,6BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CAclC;AAaM,kCALI,GAAG;IAEW,MAAM;IACL,WAAW;uBAQpC;AAUM,kCALI,UAAU;IAEI,MAAM;IACL,WAAW;uBAG2D;AAmBzF,kCANI,UAAU,GAAC,MAAM,QACjB,UAAU,GAAC,MAAM;IAEF,WAAW;IACZ,MAAM;uBAsB5B;qBAxHU,MAAM,SAAS,GAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/common.d.ts b/nodejs/node_modules/lib0/dist/crypto/common.d.ts new file mode 100644 index 00000000..8ab27bbf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/common.d.ts @@ -0,0 +1,3 @@ +export function exportKeyJwk(key: CryptoKey): Promise; +export function exportKeyRaw(key: CryptoKey): Promise; +//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/common.d.ts.map b/nodejs/node_modules/lib0/dist/crypto/common.d.ts.map new file mode 100644 index 00000000..bb0579dd --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../crypto/common.js"],"names":[],"mappings":"AAKO,kCAFI,SAAS,uBAMnB;AAQM,kCAHI,SAAS,GACR,QAAQ,UAAU,CAAC,CAG0C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/ecdsa.d.ts b/nodejs/node_modules/lib0/dist/crypto/ecdsa.d.ts new file mode 100644 index 00000000..d4dbcd5d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/ecdsa.d.ts @@ -0,0 +1,17 @@ +export function sign(key: CryptoKey, data: Uint8Array): PromiseLike; +export function verify(key: CryptoKey, signature: Uint8Array, data: Uint8Array): PromiseLike; +export function generateKeyPair({ extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export function importKeyJwk(jwk: any, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export function importKeyRaw(raw: any, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export type Usages = Array<'sign' | 'verify'>; +export { exportKeyJwk, exportKeyRaw } from "./common.js"; +//# sourceMappingURL=ecdsa.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/ecdsa.d.ts.map b/nodejs/node_modules/lib0/dist/crypto/ecdsa.d.ts.map new file mode 100644 index 00000000..80a34c0d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/ecdsa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ecdsa.d.ts","sourceRoot":"","sources":["../../crypto/ecdsa.js"],"names":[],"mappings":"AA8BO,0BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CAOa;AAYzC,4BALI,SAAS,aACT,UAAU,QACV,UAAU,GACT,YAAY,OAAO,CAAC,CAQ7B;AAaI;IAHmB,WAAW;IACZ,MAAM;2BAO5B;AAQI,kCALI,GAAG;IAEY,WAAW;IACZ,MAAM;uBAQ9B;AAUM,kCALI,GAAG;IAEY,WAAW;IACZ,MAAM;uBAGmD;qBAxFrE,MAAM,MAAM,GAAC,QAAQ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/jwt.d.ts b/nodejs/node_modules/lib0/dist/crypto/jwt.d.ts new file mode 100644 index 00000000..0447def9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/jwt.d.ts @@ -0,0 +1,10 @@ +export function encodeJwt(privateKey: CryptoKey, payload: Object): PromiseLike; +export function verifyJwt(publicKey: CryptoKey, jwt: string): Promise<{ + header: any; + payload: any; +}>; +export function unsafeDecode(jwt: string): { + header: any; + payload: any; +}; +//# sourceMappingURL=jwt.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/jwt.d.ts.map b/nodejs/node_modules/lib0/dist/crypto/jwt.d.ts.map new file mode 100644 index 00000000..1ac8dfdc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/jwt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../crypto/jwt.js"],"names":[],"mappings":"AAqBO,sCAHI,SAAS,WACT,MAAM,uBAgBhB;AAMM,qCAHI,SAAS,OACT,MAAM;;;GAiBhB;AAOM,kCAFI,MAAM;;;EAQhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/rsa-oaep.d.ts b/nodejs/node_modules/lib0/dist/crypto/rsa-oaep.d.ts new file mode 100644 index 00000000..0a9bde0c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/rsa-oaep.d.ts @@ -0,0 +1,13 @@ +export { exportKeyJwk } from "./common.js"; +export function encrypt(key: CryptoKey, data: Uint8Array): PromiseLike; +export function decrypt(key: CryptoKey, data: Uint8Array): PromiseLike; +export function generateKeyPair({ extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export function importKeyJwk(jwk: any, { extractable, usages }?: { + extractable?: boolean | undefined; + usages?: Usages | undefined; +}): Promise; +export type Usages = Array<'encrypt' | 'decrypt'>; +//# sourceMappingURL=rsa-oaep.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/crypto/rsa-oaep.d.ts.map b/nodejs/node_modules/lib0/dist/crypto/rsa-oaep.d.ts.map new file mode 100644 index 00000000..95be8382 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/crypto/rsa-oaep.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rsa-oaep.d.ts","sourceRoot":"","sources":["../../crypto/rsa-oaep.js"],"names":[],"mappings":";AAuBO,6BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CASC;AAW7B,6BAJI,SAAS,QACT,UAAU,GACT,YAAY,UAAU,CAAC,CASG;AAQ/B;IAJmB,WAAW;IACZ,MAAM;IACnB,QAAQ,aAAa,CAAC,CAY/B;AAQI,kCALI,GAAG;IAEY,WAAW;IACZ,MAAM;uBAQ9B;qBAxEY,MAAM,SAAS,GAAC,SAAS,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/decoding-000d097f.cjs b/nodejs/node_modules/lib0/dist/decoding-000d097f.cjs new file mode 100644 index 00000000..46adb53f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/decoding-000d097f.cjs @@ -0,0 +1,791 @@ +'use strict'; + +var binary = require('./binary-ac8e39e2.cjs'); +var math = require('./math-08e068f9.cjs'); +var number = require('./number-466d8922.cjs'); +var string = require('./string-6d104757.cjs'); +var error = require('./error-8582d695.cjs'); +var encoding = require('./encoding-882cb136.cjs'); + +/** + * Efficient schema-less binary decoding with support for variable length encoding. + * + * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module decoding + */ + +const errorUnexpectedEndOfArray = error.create('Unexpected end of array'); +const errorIntegerOutOfRange = error.create('Integer out of Range'); + +/** + * A Decoder handles the decoding of an Uint8Array. + */ +class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor (uint8Array) { + /** + * Decoding target. + * + * @type {Uint8Array} + */ + this.arr = uint8Array; + /** + * Current decoding position. + * + * @type {number} + */ + this.pos = 0; + } +} + +/** + * @function + * @param {Uint8Array} uint8Array + * @return {Decoder} + */ +const createDecoder = uint8Array => new Decoder(uint8Array); + +/** + * @function + * @param {Decoder} decoder + * @return {boolean} + */ +const hasContent = decoder => decoder.pos !== decoder.arr.length; + +/** + * Clone a decoder instance. + * Optionally set a new position parameter. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} [newPos] Defaults to current position + * @return {Decoder} A clone of `decoder` + */ +const clone = (decoder, newPos = decoder.pos) => { + const _decoder = createDecoder(decoder.arr); + _decoder.pos = newPos; + return _decoder +}; + +/** + * Create an Uint8Array view of the next `len` bytes and advance the position by `len`. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} len The length of bytes to read + * @return {Uint8Array} + */ +const readUint8Array = (decoder, len) => { + const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); + decoder.pos += len; + return view +}; + +/** + * Read variable length Uint8Array. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ +const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder)); + +/** + * Read the rest of the content as an ArrayBuffer + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ +const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos); + +/** + * Skip one byte, jump to the next position. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} The next position + */ +const skip8 = decoder => decoder.pos++; + +/** + * Read one byte as unsigned integer. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} Unsigned 8-bit integer + */ +const readUint8 = decoder => decoder.arr[decoder.pos++]; + +/** + * Read 2 bytes as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +const readUint16 = decoder => { + const uint = + decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8); + decoder.pos += 2; + return uint +}; + +/** + * Read 4 bytes as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +const readUint32 = decoder => { + const uint = + (decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8) + + (decoder.arr[decoder.pos + 2] << 16) + + (decoder.arr[decoder.pos + 3] << 24)) >>> 0; + decoder.pos += 4; + return uint +}; + +/** + * Read 4 bytes as unsigned integer in big endian order. + * (most significant byte first) + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +const readUint32BigEndian = decoder => { + const uint = + (decoder.arr[decoder.pos + 3] + + (decoder.arr[decoder.pos + 2] << 8) + + (decoder.arr[decoder.pos + 1] << 16) + + (decoder.arr[decoder.pos] << 24)) >>> 0; + decoder.pos += 4; + return uint +}; + +/** + * Look ahead without incrementing the position + * to the next byte and read it as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +const peekUint8 = decoder => decoder.arr[decoder.pos]; + +/** + * Look ahead without incrementing the position + * to the next byte and read it as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +const peekUint16 = decoder => + decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8); + +/** + * Look ahead without incrementing the position + * to the next byte and read it as unsigned integer. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer. + */ +const peekUint32 = decoder => ( + decoder.arr[decoder.pos] + + (decoder.arr[decoder.pos + 1] << 8) + + (decoder.arr[decoder.pos + 2] << 16) + + (decoder.arr[decoder.pos + 3] << 24) +) >>> 0; + +/** + * Read unsigned integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ +const readVarUint = decoder => { + let num = 0; + let mult = 1; + const len = decoder.arr.length; + while (decoder.pos < len) { + const r = decoder.arr[decoder.pos++]; + // num = num | ((r & binary.BITS7) << len) + num = num + (r & binary.BITS7) * mult; // shift $r << (7*#iterations) and add it to num + mult *= 128; // next iteration, shift 7 "more" to the left + if (r < binary.BIT8) { + return num + } + /* c8 ignore start */ + if (num > number.MAX_SAFE_INTEGER) { + throw errorIntegerOutOfRange + } + /* c8 ignore stop */ + } + throw errorUnexpectedEndOfArray +}; + +/** + * Read signed integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ +const readVarInt = decoder => { + let r = decoder.arr[decoder.pos++]; + let num = r & binary.BITS6; + let mult = 64; + const sign = (r & binary.BIT7) > 0 ? -1 : 1; + if ((r & binary.BIT8) === 0) { + // don't continue reading + return sign * num + } + const len = decoder.arr.length; + while (decoder.pos < len) { + r = decoder.arr[decoder.pos++]; + // num = num | ((r & binary.BITS7) << len) + num = num + (r & binary.BITS7) * mult; + mult *= 128; + if (r < binary.BIT8) { + return sign * num + } + /* c8 ignore start */ + if (num > number.MAX_SAFE_INTEGER) { + throw errorIntegerOutOfRange + } + /* c8 ignore stop */ + } + throw errorUnexpectedEndOfArray +}; + +/** + * Look ahead and read varUint without incrementing position + * + * @function + * @param {Decoder} decoder + * @return {number} + */ +const peekVarUint = decoder => { + const pos = decoder.pos; + const s = readVarUint(decoder); + decoder.pos = pos; + return s +}; + +/** + * Look ahead and read varUint without incrementing position + * + * @function + * @param {Decoder} decoder + * @return {number} + */ +const peekVarInt = decoder => { + const pos = decoder.pos; + const s = readVarInt(decoder); + decoder.pos = pos; + return s +}; + +/** + * We don't test this function anymore as we use native decoding/encoding by default now. + * Better not modify this anymore.. + * + * Transforming utf8 to a string is pretty expensive. The code performs 10x better + * when String.fromCodePoint is fed with all characters as arguments. + * But most environments have a maximum number of arguments per functions. + * For effiency reasons we apply a maximum of 10000 characters at once. + * + * @function + * @param {Decoder} decoder + * @return {String} The read String. + */ +/* c8 ignore start */ +const _readVarStringPolyfill = decoder => { + let remainingLen = readVarUint(decoder); + if (remainingLen === 0) { + return '' + } else { + let encodedString = String.fromCodePoint(readUint8(decoder)); // remember to decrease remainingLen + if (--remainingLen < 100) { // do not create a Uint8Array for small strings + while (remainingLen--) { + encodedString += String.fromCodePoint(readUint8(decoder)); + } + } else { + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000; + // this is dangerous, we create a fresh array view from the existing buffer + const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); + decoder.pos += nextLen; + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)); + remainingLen -= nextLen; + } + } + return decodeURIComponent(escape(encodedString)) + } +}; +/* c8 ignore stop */ + +/** + * @function + * @param {Decoder} decoder + * @return {String} The read String + */ +const _readVarStringNative = decoder => + /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder)); + +/** + * Read string of variable length + * * varUint is used to store the length of the string + * + * @function + * @param {Decoder} decoder + * @return {String} The read String + * + */ +/* c8 ignore next */ +const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; + +/** + * @param {Decoder} decoder + * @return {Uint8Array} + */ +const readTerminatedUint8Array = decoder => { + const encoder = encoding.createEncoder(); + let b; + while (true) { + b = readUint8(decoder); + if (b === 0) { + return encoding.toUint8Array(encoder) + } + if (b === 1) { + b = readUint8(decoder); + } + encoding.write(encoder, b); + } +}; + +/** + * @param {Decoder} decoder + * @return {string} + */ +const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder)); + +/** + * Look ahead and read varString without incrementing position + * + * @function + * @param {Decoder} decoder + * @return {string} + */ +const peekVarString = decoder => { + const pos = decoder.pos; + const s = readVarString(decoder); + decoder.pos = pos; + return s +}; + +/** + * @param {Decoder} decoder + * @param {number} len + * @return {DataView} + */ +const readFromDataView = (decoder, len) => { + const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); + decoder.pos += len; + return dv +}; + +/** + * @param {Decoder} decoder + */ +const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false); + +/** + * @param {Decoder} decoder + */ +const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false); + +/** + * @param {Decoder} decoder + */ +const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false); + +/** + * @param {Decoder} decoder + */ +const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false); + +/** + * @type {Array} + */ +const readAnyLookupTable = [ + decoder => undefined, // CASE 127: undefined + decoder => null, // CASE 126: null + readVarInt, // CASE 125: integer + readFloat32, // CASE 124: float32 + readFloat64, // CASE 123: float64 + readBigInt64, // CASE 122: bigint + decoder => false, // CASE 121: boolean (false) + decoder => true, // CASE 120: boolean (true) + readVarString, // CASE 119: string + decoder => { // CASE 118: object + const len = readVarUint(decoder); + /** + * @type {Object} + */ + const obj = {}; + for (let i = 0; i < len; i++) { + const key = readVarString(decoder); + obj[key] = readAny(decoder); + } + return obj + }, + decoder => { // CASE 117: array + const len = readVarUint(decoder); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(readAny(decoder)); + } + return arr + }, + readVarUint8Array // CASE 116: Uint8Array +]; + +/** + * @param {Decoder} decoder + */ +const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder); + +/** + * T must not be null. + * + * @template T + */ +class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor (uint8Array, reader) { + super(uint8Array); + /** + * The reader + */ + this.reader = reader; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = this.reader(this); + if (hasContent(this)) { + this.count = readVarUint(this) + 1; // see encoder implementation for the reason why this is incremented + } else { + this.count = -1; // read the current value forever + } + } + this.count--; + return /** @type {T} */ (this.s) + } +} + +class IntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor (uint8Array, start) { + super(uint8Array); + /** + * Current state + * @type {number} + */ + this.s = start; + } + + /** + * @return {number} + */ + read () { + this.s += readVarInt(this); + return this.s + } +} + +class RleIntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor (uint8Array, start) { + super(uint8Array); + /** + * Current state + * @type {number} + */ + this.s = start; + this.count = 0; + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + this.s += readVarInt(this); + if (hasContent(this)) { + this.count = readVarUint(this) + 1; // see encoder implementation for the reason why this is incremented + } else { + this.count = -1; // read the current value forever + } + } + this.count--; + return /** @type {number} */ (this.s) + } +} + +class UintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this); + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = math.isNegativeZero(this.s); + this.count = 1; + if (isNegative) { + this.s = -this.s; + this.count = readVarUint(this) + 2; + } + } + this.count--; + return /** @type {number} */ (this.s) + } +} + +class IncUintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this); + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = math.isNegativeZero(this.s); + this.count = 1; + if (isNegative) { + this.s = -this.s; + this.count = readVarUint(this) + 2; + } + } + this.count--; + return /** @type {number} */ (this.s++) + } +} + +class IntDiffOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + const diff = readVarInt(this); + // if the first bit is set, we read more data + const hasCount = diff & 1; + this.diff = math.floor(diff / 2); // shift >> 1 + this.count = 1; + if (hasCount) { + this.count = readVarUint(this) + 2; + } + } + this.s += this.diff; + this.count--; + return this.s + } +} + +class StringDecoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + this.decoder = new UintOptRleDecoder(uint8Array); + this.str = readVarString(this.decoder); + /** + * @type {number} + */ + this.spos = 0; + } + + /** + * @return {string} + */ + read () { + const end = this.spos + this.decoder.read(); + const res = this.str.slice(this.spos, end); + this.spos = end; + return res + } +} + +var decoding = /*#__PURE__*/Object.freeze({ + __proto__: null, + Decoder: Decoder, + createDecoder: createDecoder, + hasContent: hasContent, + clone: clone, + readUint8Array: readUint8Array, + readVarUint8Array: readVarUint8Array, + readTailAsUint8Array: readTailAsUint8Array, + skip8: skip8, + readUint8: readUint8, + readUint16: readUint16, + readUint32: readUint32, + readUint32BigEndian: readUint32BigEndian, + peekUint8: peekUint8, + peekUint16: peekUint16, + peekUint32: peekUint32, + readVarUint: readVarUint, + readVarInt: readVarInt, + peekVarUint: peekVarUint, + peekVarInt: peekVarInt, + _readVarStringPolyfill: _readVarStringPolyfill, + _readVarStringNative: _readVarStringNative, + readVarString: readVarString, + readTerminatedUint8Array: readTerminatedUint8Array, + readTerminatedString: readTerminatedString, + peekVarString: peekVarString, + readFromDataView: readFromDataView, + readFloat32: readFloat32, + readFloat64: readFloat64, + readBigInt64: readBigInt64, + readBigUint64: readBigUint64, + readAny: readAny, + RleDecoder: RleDecoder, + IntDiffDecoder: IntDiffDecoder, + RleIntDiffDecoder: RleIntDiffDecoder, + UintOptRleDecoder: UintOptRleDecoder, + IncUintOptRleDecoder: IncUintOptRleDecoder, + IntDiffOptRleDecoder: IntDiffOptRleDecoder, + StringDecoder: StringDecoder +}); + +exports.Decoder = Decoder; +exports.IncUintOptRleDecoder = IncUintOptRleDecoder; +exports.IntDiffDecoder = IntDiffDecoder; +exports.IntDiffOptRleDecoder = IntDiffOptRleDecoder; +exports.RleDecoder = RleDecoder; +exports.RleIntDiffDecoder = RleIntDiffDecoder; +exports.StringDecoder = StringDecoder; +exports.UintOptRleDecoder = UintOptRleDecoder; +exports._readVarStringNative = _readVarStringNative; +exports._readVarStringPolyfill = _readVarStringPolyfill; +exports.clone = clone; +exports.createDecoder = createDecoder; +exports.decoding = decoding; +exports.hasContent = hasContent; +exports.peekUint16 = peekUint16; +exports.peekUint32 = peekUint32; +exports.peekUint8 = peekUint8; +exports.peekVarInt = peekVarInt; +exports.peekVarString = peekVarString; +exports.peekVarUint = peekVarUint; +exports.readAny = readAny; +exports.readBigInt64 = readBigInt64; +exports.readBigUint64 = readBigUint64; +exports.readFloat32 = readFloat32; +exports.readFloat64 = readFloat64; +exports.readFromDataView = readFromDataView; +exports.readTailAsUint8Array = readTailAsUint8Array; +exports.readTerminatedString = readTerminatedString; +exports.readTerminatedUint8Array = readTerminatedUint8Array; +exports.readUint16 = readUint16; +exports.readUint32 = readUint32; +exports.readUint32BigEndian = readUint32BigEndian; +exports.readUint8 = readUint8; +exports.readUint8Array = readUint8Array; +exports.readVarInt = readVarInt; +exports.readVarString = readVarString; +exports.readVarUint = readVarUint; +exports.readVarUint8Array = readVarUint8Array; +exports.skip8 = skip8; +//# sourceMappingURL=decoding-000d097f.cjs.map diff --git a/nodejs/node_modules/lib0/dist/decoding-000d097f.cjs.map b/nodejs/node_modules/lib0/dist/decoding-000d097f.cjs.map new file mode 100644 index 00000000..906aa9d2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/decoding-000d097f.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding-000d097f.cjs","sources":["../decoding.js"],"sourcesContent":["/**\n * Efficient schema-less binary decoding with support for variable length encoding.\n *\n * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module decoding\n */\n\nimport * as binary from './binary.js'\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as string from './string.js'\nimport * as error from './error.js'\nimport * as encoding from './encoding.js'\n\nconst errorUnexpectedEndOfArray = error.create('Unexpected end of array')\nconst errorIntegerOutOfRange = error.create('Integer out of Range')\n\n/**\n * A Decoder handles the decoding of an Uint8Array.\n */\nexport class Decoder {\n /**\n * @param {Uint8Array} uint8Array Binary data to decode\n */\n constructor (uint8Array) {\n /**\n * Decoding target.\n *\n * @type {Uint8Array}\n */\n this.arr = uint8Array\n /**\n * Current decoding position.\n *\n * @type {number}\n */\n this.pos = 0\n }\n}\n\n/**\n * @function\n * @param {Uint8Array} uint8Array\n * @return {Decoder}\n */\nexport const createDecoder = uint8Array => new Decoder(uint8Array)\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {boolean}\n */\nexport const hasContent = decoder => decoder.pos !== decoder.arr.length\n\n/**\n * Clone a decoder instance.\n * Optionally set a new position parameter.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} [newPos] Defaults to current position\n * @return {Decoder} A clone of `decoder`\n */\nexport const clone = (decoder, newPos = decoder.pos) => {\n const _decoder = createDecoder(decoder.arr)\n _decoder.pos = newPos\n return _decoder\n}\n\n/**\n * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder The decoder instance\n * @param {number} len The length of bytes to read\n * @return {Uint8Array}\n */\nexport const readUint8Array = (decoder, len) => {\n const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len)\n decoder.pos += len\n return view\n}\n\n/**\n * Read variable length Uint8Array.\n *\n * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.\n * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.\n *\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder))\n\n/**\n * Read the rest of the content as an ArrayBuffer\n * @function\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTailAsUint8Array = decoder => readUint8Array(decoder, decoder.arr.length - decoder.pos)\n\n/**\n * Skip one byte, jump to the next position.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} The next position\n */\nexport const skip8 = decoder => decoder.pos++\n\n/**\n * Read one byte as unsigned integer.\n * @function\n * @param {Decoder} decoder The decoder instance\n * @return {number} Unsigned 8-bit integer\n */\nexport const readUint8 = decoder => decoder.arr[decoder.pos++]\n\n/**\n * Read 2 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint16 = decoder => {\n const uint =\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n decoder.pos += 2\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32 = decoder => {\n const uint =\n (decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint8 = decoder => decoder.arr[decoder.pos]\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint16 = decoder =>\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8)\n\n/**\n * Look ahead without incrementing the position\n * to the next byte and read it as unsigned integer.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const peekUint32 = decoder => (\n decoder.arr[decoder.pos] +\n (decoder.arr[decoder.pos + 1] << 8) +\n (decoder.arr[decoder.pos + 2] << 16) +\n (decoder.arr[decoder.pos + 3] << 24)\n) >>> 0\n\n/**\n * Read unsigned integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarUint = decoder => {\n let num = 0\n let mult = 1\n const len = decoder.arr.length\n while (decoder.pos < len) {\n const r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult // shift $r << (7*#iterations) and add it to num\n mult *= 128 // next iteration, shift 7 \"more\" to the left\n if (r < binary.BIT8) {\n return num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Read signed integer (32bit) with variable length.\n * 1/8th of the storage is used as encoding overhead.\n * * numbers < 2^7 is stored in one bytlength\n * * numbers < 2^14 is stored in two bylength\n * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.\n *\n * @function\n * @param {Decoder} decoder\n * @return {number} An unsigned integer.length\n */\nexport const readVarInt = decoder => {\n let r = decoder.arr[decoder.pos++]\n let num = r & binary.BITS6\n let mult = 64\n const sign = (r & binary.BIT7) > 0 ? -1 : 1\n if ((r & binary.BIT8) === 0) {\n // don't continue reading\n return sign * num\n }\n const len = decoder.arr.length\n while (decoder.pos < len) {\n r = decoder.arr[decoder.pos++]\n // num = num | ((r & binary.BITS7) << len)\n num = num + (r & binary.BITS7) * mult\n mult *= 128\n if (r < binary.BIT8) {\n return sign * num\n }\n /* c8 ignore start */\n if (num > number.MAX_SAFE_INTEGER) {\n throw errorIntegerOutOfRange\n }\n /* c8 ignore stop */\n }\n throw errorUnexpectedEndOfArray\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarUint = decoder => {\n const pos = decoder.pos\n const s = readVarUint(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * Look ahead and read varUint without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {number}\n */\nexport const peekVarInt = decoder => {\n const pos = decoder.pos\n const s = readVarInt(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * We don't test this function anymore as we use native decoding/encoding by default now.\n * Better not modify this anymore..\n *\n * Transforming utf8 to a string is pretty expensive. The code performs 10x better\n * when String.fromCodePoint is fed with all characters as arguments.\n * But most environments have a maximum number of arguments per functions.\n * For effiency reasons we apply a maximum of 10000 characters at once.\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String.\n */\n/* c8 ignore start */\nexport const _readVarStringPolyfill = decoder => {\n let remainingLen = readVarUint(decoder)\n if (remainingLen === 0) {\n return ''\n } else {\n let encodedString = String.fromCodePoint(readUint8(decoder)) // remember to decrease remainingLen\n if (--remainingLen < 100) { // do not create a Uint8Array for small strings\n while (remainingLen--) {\n encodedString += String.fromCodePoint(readUint8(decoder))\n }\n } else {\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n // this is dangerous, we create a fresh array view from the existing buffer\n const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen)\n decoder.pos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n }\n return decodeURIComponent(escape(encodedString))\n }\n}\n/* c8 ignore stop */\n\n/**\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n */\nexport const _readVarStringNative = decoder =>\n /** @type any */ (string.utf8TextDecoder).decode(readVarUint8Array(decoder))\n\n/**\n * Read string of variable length\n * * varUint is used to store the length of the string\n *\n * @function\n * @param {Decoder} decoder\n * @return {String} The read String\n *\n */\n/* c8 ignore next */\nexport const readVarString = string.utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill\n\n/**\n * @param {Decoder} decoder\n * @return {Uint8Array}\n */\nexport const readTerminatedUint8Array = decoder => {\n const encoder = encoding.createEncoder()\n let b\n while (true) {\n b = readUint8(decoder)\n if (b === 0) {\n return encoding.toUint8Array(encoder)\n }\n if (b === 1) {\n b = readUint8(decoder)\n }\n encoding.write(encoder, b)\n }\n}\n\n/**\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const readTerminatedString = decoder => string.decodeUtf8(readTerminatedUint8Array(decoder))\n\n/**\n * Look ahead and read varString without incrementing position\n *\n * @function\n * @param {Decoder} decoder\n * @return {string}\n */\nexport const peekVarString = decoder => {\n const pos = decoder.pos\n const s = readVarString(decoder)\n decoder.pos = pos\n return s\n}\n\n/**\n * @param {Decoder} decoder\n * @param {number} len\n * @return {DataView}\n */\nexport const readFromDataView = (decoder, len) => {\n const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len)\n decoder.pos += len\n return dv\n}\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false)\n\n/**\n * @param {Decoder} decoder\n */\nexport const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false)\n\n/**\n * @type {Array}\n */\nconst readAnyLookupTable = [\n decoder => undefined, // CASE 127: undefined\n decoder => null, // CASE 126: null\n readVarInt, // CASE 125: integer\n readFloat32, // CASE 124: float32\n readFloat64, // CASE 123: float64\n readBigInt64, // CASE 122: bigint\n decoder => false, // CASE 121: boolean (false)\n decoder => true, // CASE 120: boolean (true)\n readVarString, // CASE 119: string\n decoder => { // CASE 118: object\n const len = readVarUint(decoder)\n /**\n * @type {Object}\n */\n const obj = {}\n for (let i = 0; i < len; i++) {\n const key = readVarString(decoder)\n obj[key] = readAny(decoder)\n }\n return obj\n },\n decoder => { // CASE 117: array\n const len = readVarUint(decoder)\n const arr = []\n for (let i = 0; i < len; i++) {\n arr.push(readAny(decoder))\n }\n return arr\n },\n readVarUint8Array // CASE 116: Uint8Array\n]\n\n/**\n * @param {Decoder} decoder\n */\nexport const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder)\n\n/**\n * T must not be null.\n *\n * @template T\n */\nexport class RleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {function(Decoder):T} reader\n */\n constructor (uint8Array, reader) {\n super(uint8Array)\n /**\n * The reader\n */\n this.reader = reader\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = this.reader(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {T} */ (this.s)\n }\n}\n\nexport class IntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @return {number}\n */\n read () {\n this.s += readVarInt(this)\n return this.s\n }\n}\n\nexport class RleIntDiffDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n * @param {number} start\n */\n constructor (uint8Array, start) {\n super(uint8Array)\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n this.s += readVarInt(this)\n if (hasContent(this)) {\n this.count = readVarUint(this) + 1 // see encoder implementation for the reason why this is incremented\n } else {\n this.count = -1 // read the current value forever\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class UintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s)\n }\n}\n\nexport class IncUintOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n read () {\n if (this.count === 0) {\n this.s = readVarInt(this)\n // if the sign is negative, we read the count too, otherwise count is 1\n const isNegative = math.isNegativeZero(this.s)\n this.count = 1\n if (isNegative) {\n this.s = -this.s\n this.count = readVarUint(this) + 2\n }\n }\n this.count--\n return /** @type {number} */ (this.s++)\n }\n}\n\nexport class IntDiffOptRleDecoder extends Decoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n super(uint8Array)\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @return {number}\n */\n read () {\n if (this.count === 0) {\n const diff = readVarInt(this)\n // if the first bit is set, we read more data\n const hasCount = diff & 1\n this.diff = math.floor(diff / 2) // shift >> 1\n this.count = 1\n if (hasCount) {\n this.count = readVarUint(this) + 2\n }\n }\n this.s += this.diff\n this.count--\n return this.s\n }\n}\n\nexport class StringDecoder {\n /**\n * @param {Uint8Array} uint8Array\n */\n constructor (uint8Array) {\n this.decoder = new UintOptRleDecoder(uint8Array)\n this.str = readVarString(this.decoder)\n /**\n * @type {number}\n */\n this.spos = 0\n }\n\n /**\n * @return {string}\n */\n read () {\n const end = this.spos + this.decoder.read()\n const res = this.str.slice(this.spos, end)\n this.spos = end\n return res\n }\n}\n"],"names":["error.create","binary.BITS7","binary.BIT8","number.MAX_SAFE_INTEGER","binary.BITS6","binary.BIT7","string.utf8TextDecoder","encoding.createEncoder","encoding.toUint8Array","encoding.write","string.decodeUtf8","math.isNegativeZero","math.floor"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAQA;AACA,MAAM,yBAAyB,GAAGA,YAAY,CAAC,yBAAyB,EAAC;AACzE,MAAM,sBAAsB,GAAGA,YAAY,CAAC,sBAAsB,EAAC;AACnE;AACA;AACA;AACA;AACO,MAAM,OAAO,CAAC;AACrB;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,UAAU,EAAE;AAC3B;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,CAAC,GAAG,GAAG,WAAU;AACzB;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,CAAC,GAAG,GAAG,EAAC;AAChB,GAAG;AACH,CAAC;AACD;AACA;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GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAC;AAC9C,IAAI,IAAI,CAAC,IAAI,GAAG,IAAG;AACnB,IAAI,OAAO,GAAG;AACd,GAAG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/decoding.cjs b/nodejs/node_modules/lib0/dist/decoding.cjs new file mode 100644 index 00000000..496d39b7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/decoding.cjs @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./binary-ac8e39e2.cjs'); +require('./math-08e068f9.cjs'); +require('./number-466d8922.cjs'); +require('./string-6d104757.cjs'); +require('./error-8582d695.cjs'); +require('./encoding-882cb136.cjs'); +var decoding = require('./decoding-000d097f.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); + + + +exports.Decoder = decoding.Decoder; +exports.IncUintOptRleDecoder = decoding.IncUintOptRleDecoder; +exports.IntDiffDecoder = decoding.IntDiffDecoder; +exports.IntDiffOptRleDecoder = decoding.IntDiffOptRleDecoder; +exports.RleDecoder = decoding.RleDecoder; +exports.RleIntDiffDecoder = decoding.RleIntDiffDecoder; +exports.StringDecoder = decoding.StringDecoder; +exports.UintOptRleDecoder = decoding.UintOptRleDecoder; +exports._readVarStringNative = decoding._readVarStringNative; +exports._readVarStringPolyfill = decoding._readVarStringPolyfill; +exports.clone = decoding.clone; +exports.createDecoder = decoding.createDecoder; +exports.hasContent = decoding.hasContent; +exports.peekUint16 = decoding.peekUint16; +exports.peekUint32 = decoding.peekUint32; +exports.peekUint8 = decoding.peekUint8; +exports.peekVarInt = decoding.peekVarInt; +exports.peekVarString = decoding.peekVarString; +exports.peekVarUint = decoding.peekVarUint; +exports.readAny = decoding.readAny; +exports.readBigInt64 = decoding.readBigInt64; +exports.readBigUint64 = decoding.readBigUint64; +exports.readFloat32 = decoding.readFloat32; +exports.readFloat64 = decoding.readFloat64; +exports.readFromDataView = decoding.readFromDataView; +exports.readTailAsUint8Array = decoding.readTailAsUint8Array; +exports.readTerminatedString = decoding.readTerminatedString; +exports.readTerminatedUint8Array = decoding.readTerminatedUint8Array; +exports.readUint16 = decoding.readUint16; +exports.readUint32 = decoding.readUint32; +exports.readUint32BigEndian = decoding.readUint32BigEndian; +exports.readUint8 = decoding.readUint8; +exports.readUint8Array = decoding.readUint8Array; +exports.readVarInt = decoding.readVarInt; +exports.readVarString = decoding.readVarString; +exports.readVarUint = decoding.readVarUint; +exports.readVarUint8Array = decoding.readVarUint8Array; +exports.skip8 = decoding.skip8; +//# sourceMappingURL=decoding.cjs.map diff --git a/nodejs/node_modules/lib0/dist/decoding.cjs.map b/nodejs/node_modules/lib0/dist/decoding.cjs.map new file mode 100644 index 00000000..85f4368c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/decoding.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/decoding.d.ts b/nodejs/node_modules/lib0/dist/decoding.d.ts new file mode 100644 index 00000000..848d8a3f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/decoding.d.ts @@ -0,0 +1,152 @@ +/** + * A Decoder handles the decoding of an Uint8Array. + */ +export class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor(uint8Array: Uint8Array); + /** + * Decoding target. + * + * @type {Uint8Array} + */ + arr: Uint8Array; + /** + * Current decoding position. + * + * @type {number} + */ + pos: number; +} +export function createDecoder(uint8Array: Uint8Array): Decoder; +export function hasContent(decoder: Decoder): boolean; +export function clone(decoder: Decoder, newPos?: number | undefined): Decoder; +export function readUint8Array(decoder: Decoder, len: number): Uint8Array; +export function readVarUint8Array(decoder: Decoder): Uint8Array; +export function readTailAsUint8Array(decoder: Decoder): Uint8Array; +export function skip8(decoder: Decoder): number; +export function readUint8(decoder: Decoder): number; +export function readUint16(decoder: Decoder): number; +export function readUint32(decoder: Decoder): number; +export function readUint32BigEndian(decoder: Decoder): number; +export function peekUint8(decoder: Decoder): number; +export function peekUint16(decoder: Decoder): number; +export function peekUint32(decoder: Decoder): number; +export function readVarUint(decoder: Decoder): number; +export function readVarInt(decoder: Decoder): number; +export function peekVarUint(decoder: Decoder): number; +export function peekVarInt(decoder: Decoder): number; +export function _readVarStringPolyfill(decoder: Decoder): string; +export function _readVarStringNative(decoder: Decoder): string; +export function readVarString(decoder: Decoder): string; +export function readTerminatedUint8Array(decoder: Decoder): Uint8Array; +export function readTerminatedString(decoder: Decoder): string; +export function peekVarString(decoder: Decoder): string; +export function readFromDataView(decoder: Decoder, len: number): DataView; +export function readFloat32(decoder: Decoder): number; +export function readFloat64(decoder: Decoder): number; +export function readBigInt64(decoder: Decoder): any; +export function readBigUint64(decoder: Decoder): any; +export function readAny(decoder: Decoder): any; +/** + * T must not be null. + * + * @template T + */ +export class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor(uint8Array: Uint8Array, reader: (arg0: Decoder) => T); + /** + * The reader + */ + reader: (arg0: Decoder) => T; + /** + * Current state + * @type {T|null} + */ + s: T | null; + count: number; + read(): T; +} +export class IntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor(uint8Array: Uint8Array, start: number); + /** + * Current state + * @type {number} + */ + s: number; + /** + * @return {number} + */ + read(): number; +} +export class RleIntDiffDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {number} start + */ + constructor(uint8Array: Uint8Array, start: number); + /** + * Current state + * @type {number} + */ + s: number; + count: number; + /** + * @return {number} + */ + read(): number; +} +export class UintOptRleDecoder extends Decoder { + /** + * @type {number} + */ + s: number; + count: number; + read(): number; +} +export class IncUintOptRleDecoder extends Decoder { + /** + * @type {number} + */ + s: number; + count: number; + read(): number; +} +export class IntDiffOptRleDecoder extends Decoder { + /** + * @type {number} + */ + s: number; + count: number; + diff: number; + /** + * @return {number} + */ + read(): number; +} +export class StringDecoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor(uint8Array: Uint8Array); + decoder: UintOptRleDecoder; + str: string; + /** + * @type {number} + */ + spos: number; + /** + * @return {string} + */ + read(): string; +} +//# sourceMappingURL=decoding.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/decoding.d.ts.map b/nodejs/node_modules/lib0/dist/decoding.d.ts.map new file mode 100644 index 00000000..84d38670 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/decoding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decoding.d.ts","sourceRoot":"","sources":["../decoding.js"],"names":[],"mappings":"AAsCA;;GAEG;AACH;IACE;;OAEG;IACH,wBAFW,UAAU,EAepB;IAZC;;;;OAIG;IACH,KAFU,UAAU,CAEC;IACrB;;;;OAIG;IACH,KAFU,MAAM,CAEJ;CAEf;AAOM,0CAHI,UAAU,GACT,OAAO,CAE+C;AAO3D,oCAHI,OAAO,GACN,OAAO,CAEoD;AAWhE,+BAJI,OAAO,gCAEN,OAAO,CAMlB;AAaM,wCAJI,OAAO,OACP,MAAM,GACL,UAAU,CAMrB;AAYM,2CAHI,OAAO,GACN,UAAU,CAEmE;AAQlF,8CAHI,OAAO,GACN,UAAU,CAEkF;AAQjG,+BAHI,OAAO,GACN,MAAM,CAE2B;AAQtC,mCAHI,OAAO,GACN,MAAM,CAE4C;AASvD,oCAHI,OAAO,GACN,MAAM,CAQjB;AASM,oCAHI,OAAO,GACN,MAAM,CAUjB;AAUM,6CAHI,OAAO,GACN,MAAM,CAUjB;AAUM,mCAHI,OAAO,GACN,MAAM,CAE0C;AAUrD,oCAHI,OAA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AEG;IACH,GAFU,MAAM,CAEN;IACV,cAAc;IACd,aAAa;IAGf;;OAEG;IACH,QAFY,MAAM,CAgBjB;CACF;AAED;IACE;;OAEG;IACH,wBAFW,UAAU,EASpB;IANC,2BAAgD;IAChD,YAAsC;IACtC;;OAEG;IACH,MAFU,MAAM,CAEH;IAGf;;OAEG;IACH,QAFY,MAAM,CAOjB;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/diff-fbaa426b.cjs b/nodejs/node_modules/lib0/dist/diff-fbaa426b.cjs new file mode 100644 index 00000000..06093c74 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff-fbaa426b.cjs @@ -0,0 +1,164 @@ +'use strict'; + +var _function = require('./function-314fdc56.cjs'); + +/** + * Efficient diffs. + * + * @module diff + */ + +/** + * A SimpleDiff describes a change on a String. + * + * ```js + * console.log(a) // the old value + * console.log(b) // the updated value + * // Apply changes of diff (pseudocode) + * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters + * a.insert(diff.index, diff.insert) // Insert `diff.insert` + * a === b // values match + * ``` + * + * @typedef {Object} SimpleDiff + * @property {Number} index The index where changes were applied + * @property {Number} remove The number of characters to delete starting + * at `index`. + * @property {T} insert The new text to insert at `index` after applying + * `delete` + * + * @template T + */ + +const highSurrogateRegex = /[\uD800-\uDBFF]/; +const lowSurrogateRegex = /[\uDC00-\uDFFF]/; + +/** + * Create a diff between two strings. This diff implementation is highly + * efficient, but not very sophisticated. + * + * @function + * + * @param {string} a The old version of the string + * @param {string} b The updated version of the string + * @return {SimpleDiff} The diff description. + */ +const simpleDiffString = (a, b) => { + let left = 0; // number of same characters counting from left + let right = 0; // number of same characters counting from right + while (left < a.length && left < b.length && a[left] === b[left]) { + left++; + } + // If the last same character is a high surrogate, we need to rollback to the previous character + if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--; + while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) { + right++; + } + // If the last same character is a low surrogate, we need to rollback to the previous character + if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--; + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } +}; + +/** + * @todo Remove in favor of simpleDiffString + * @deprecated + */ +const simpleDiff = simpleDiffString; + +/** + * Create a diff between two arrays. This diff implementation is highly + * efficient, but not very sophisticated. + * + * Note: This is basically the same function as above. Another function was created so that the runtime + * can better optimize these function calls. + * + * @function + * @template T + * + * @param {Array} a The old version of the array + * @param {Array} b The updated version of the array + * @param {function(T, T):boolean} [compare] + * @return {SimpleDiff>} The diff description. + */ +const simpleDiffArray = (a, b, compare = _function.equalityStrict) => { + let left = 0; // number of same characters counting from left + let right = 0; // number of same characters counting from right + while (left < a.length && left < b.length && compare(a[left], b[left])) { + left++; + } + while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) { + right++; + } + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } +}; + +/** + * Diff text and try to diff at the current cursor position. + * + * @param {string} a + * @param {string} b + * @param {number} cursor This should refer to the current left cursor-range position + */ +const simpleDiffStringWithCursor = (a, b, cursor) => { + let left = 0; // number of same characters counting from left + let right = 0; // number of same characters counting from right + // Iterate left to the right until we find a changed character + // First iteration considers the current cursor position + while ( + left < a.length && + left < b.length && + a[left] === b[left] && + left < cursor + ) { + left++; + } + // If the last same character is a high surrogate, we need to rollback to the previous character + if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--; + // Iterate right to the left until we find a changed character + while ( + right + left < a.length && + right + left < b.length && + a[a.length - right - 1] === b[b.length - right - 1] + ) { + right++; + } + // If the last same character is a low surrogate, we need to rollback to the previous character + if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--; + // Try to iterate left further to the right without caring about the current cursor position + while ( + right + left < a.length && + right + left < b.length && + a[left] === b[left] + ) { + left++; + } + if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--; + return { + index: left, + remove: a.length - left - right, + insert: b.slice(left, b.length - right) + } +}; + +var diff = /*#__PURE__*/Object.freeze({ + __proto__: null, + simpleDiffString: simpleDiffString, + simpleDiff: simpleDiff, + simpleDiffArray: simpleDiffArray, + simpleDiffStringWithCursor: simpleDiffStringWithCursor +}); + +exports.diff = diff; +exports.simpleDiff = simpleDiff; +exports.simpleDiffArray = simpleDiffArray; +exports.simpleDiffString = simpleDiffString; +exports.simpleDiffStringWithCursor = simpleDiffStringWithCursor; +//# sourceMappingURL=diff-fbaa426b.cjs.map diff --git a/nodejs/node_modules/lib0/dist/diff-fbaa426b.cjs.map b/nodejs/node_modules/lib0/dist/diff-fbaa426b.cjs.map new file mode 100644 index 00000000..cc9c0124 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff-fbaa426b.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"diff-fbaa426b.cjs","sources":["../diff.js"],"sourcesContent":["/**\n * Efficient diffs.\n *\n * @module diff\n */\n\nimport { equalityStrict } from './function.js'\n\n/**\n * A SimpleDiff describes a change on a String.\n *\n * ```js\n * console.log(a) // the old value\n * console.log(b) // the updated value\n * // Apply changes of diff (pseudocode)\n * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters\n * a.insert(diff.index, diff.insert) // Insert `diff.insert`\n * a === b // values match\n * ```\n *\n * @typedef {Object} SimpleDiff\n * @property {Number} index The index where changes were applied\n * @property {Number} remove The number of characters to delete starting\n * at `index`.\n * @property {T} insert The new text to insert at `index` after applying\n * `delete`\n *\n * @template T\n */\n\nconst highSurrogateRegex = /[\\uD800-\\uDBFF]/\nconst lowSurrogateRegex = /[\\uDC00-\\uDFFF]/\n\n/**\n * Create a diff between two strings. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * @function\n *\n * @param {string} a The old version of the string\n * @param {string} b The updated version of the string\n * @return {SimpleDiff} The diff description.\n */\nexport const simpleDiffString = (a, b) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && a[left] === b[left]) {\n left++\n }\n // If the last same character is a high surrogate, we need to rollback to the previous character\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n while (right + left < a.length && right + left < b.length && a[a.length - right - 1] === b[b.length - right - 1]) {\n right++\n }\n // If the last same character is a low surrogate, we need to rollback to the previous character\n if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n\n/**\n * @todo Remove in favor of simpleDiffString\n * @deprecated\n */\nexport const simpleDiff = simpleDiffString\n\n/**\n * Create a diff between two arrays. This diff implementation is highly\n * efficient, but not very sophisticated.\n *\n * Note: This is basically the same function as above. Another function was created so that the runtime\n * can better optimize these function calls.\n *\n * @function\n * @template T\n *\n * @param {Array} a The old version of the array\n * @param {Array} b The updated version of the array\n * @param {function(T, T):boolean} [compare]\n * @return {SimpleDiff>} The diff description.\n */\nexport const simpleDiffArray = (a, b, compare = equalityStrict) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n while (left < a.length && left < b.length && compare(a[left], b[left])) {\n left++\n }\n while (right + left < a.length && right + left < b.length && compare(a[a.length - right - 1], b[b.length - right - 1])) {\n right++\n }\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n\n/**\n * Diff text and try to diff at the current cursor position.\n *\n * @param {string} a\n * @param {string} b\n * @param {number} cursor This should refer to the current left cursor-range position\n */\nexport const simpleDiffStringWithCursor = (a, b, cursor) => {\n let left = 0 // number of same characters counting from left\n let right = 0 // number of same characters counting from right\n // Iterate left to the right until we find a changed character\n // First iteration considers the current cursor position\n while (\n left < a.length &&\n left < b.length &&\n a[left] === b[left] &&\n left < cursor\n ) {\n left++\n }\n // If the last same character is a high surrogate, we need to rollback to the previous character\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n // Iterate right to the left until we find a changed character\n while (\n right + left < a.length &&\n right + left < b.length &&\n a[a.length - right - 1] === b[b.length - right - 1]\n ) {\n right++\n }\n // If the last same character is a low surrogate, we need to rollback to the previous character\n if (right > 0 && lowSurrogateRegex.test(a[a.length - right])) right--\n // Try to iterate left further to the right without caring about the current cursor position\n while (\n right + left < a.length &&\n right + left < b.length &&\n a[left] === b[left]\n ) {\n left++\n }\n if (left > 0 && highSurrogateRegex.test(a[left - 1])) left--\n return {\n index: left,\n remove: a.length - left - right,\n insert: b.slice(left, b.length - right)\n }\n}\n"],"names":["equalityStrict"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,kBAAkB,GAAG,kBAAiB;AAC5C,MAAM,iBAAiB,GAAG,kBAAiB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,gBAAgB,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK;AAC1C,EAAE,IAAI,IAAI,GAAG,EAAC;AACd,EAAE,IAAI,KAAK,GAAG,EAAC;AACf,EAAE,OAAO,IAAI,GAAG,CAAC,CAAC,MAAM,IAAI,IAAI,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE;AACpE,IAAI,IAAI,GAAE;AACV,GAAG;AACH;AACA,EAAE,IAAI,IAAI,GAAG,CAAC,IAAI,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,GAAE;AAC9D,EAAE,OAAO,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,IAAI,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,GAAG,CAAC,CAAC,EAA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AACF,IAAI,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM;AAC3B,IAAI,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM;AAC3B,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC;AACvB,IAAI;AACJ,IAAI,IAAI,GAAE;AACV,GAAG;AACH,EAAE,IAAI,IAAI,GAAG,CAAC,IAAI,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,GAAE;AAC9D,EAAE,OAAO;AACT,IAAI,KAAK,EAAE,IAAI;AACf,IAAI,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,IAAI,GAAG,KAAK;AACnC,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC;AAC3C,GAAG;AACH;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/diff.cjs b/nodejs/node_modules/lib0/dist/diff.cjs new file mode 100644 index 00000000..b0df40c6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff.cjs @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./function-314fdc56.cjs'); +var diff = require('./diff-fbaa426b.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./object-fecf6a7b.cjs'); + + + +exports.simpleDiff = diff.simpleDiff; +exports.simpleDiffArray = diff.simpleDiffArray; +exports.simpleDiffString = diff.simpleDiffString; +exports.simpleDiffStringWithCursor = diff.simpleDiffStringWithCursor; +//# sourceMappingURL=diff.cjs.map diff --git a/nodejs/node_modules/lib0/dist/diff.cjs.map b/nodejs/node_modules/lib0/dist/diff.cjs.map new file mode 100644 index 00000000..74a12d39 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/diff.d.ts b/nodejs/node_modules/lib0/dist/diff.d.ts new file mode 100644 index 00000000..7f9023c4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff.d.ts @@ -0,0 +1,37 @@ +export function simpleDiffString(a: string, b: string): SimpleDiff; +export function simpleDiff(a: string, b: string): SimpleDiff; +export function simpleDiffArray(a: T[], b: T[], compare?: ((arg0: T, arg1: T) => boolean) | undefined): SimpleDiff; +export function simpleDiffStringWithCursor(a: string, b: string, cursor: number): { + index: number; + remove: number; + insert: string; +}; +/** + * A SimpleDiff describes a change on a String. + * + * ```js + * console.log(a) // the old value + * console.log(b) // the updated value + * // Apply changes of diff (pseudocode) + * a.remove(diff.index, diff.remove) // Remove `diff.remove` characters + * a.insert(diff.index, diff.insert) // Insert `diff.insert` + * a === b // values match + * ``` + */ +export type SimpleDiff = { + /** + * The index where changes were applied + */ + index: number; + /** + * The number of characters to delete starting + * at `index`. + */ + remove: number; + /** + * The new text to insert at `index` after applying + * `delete` + */ + insert: T; +}; +//# sourceMappingURL=diff.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/diff.d.ts.map b/nodejs/node_modules/lib0/dist/diff.d.ts.map new file mode 100644 index 00000000..dfcb1cb6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.d.ts","sourceRoot":"","sources":["../diff.js"],"names":[],"mappings":"AA2CO,oCAJI,MAAM,KACN,MAAM,GACL,WAAW,MAAM,CAAC,CAoB7B;AAlBM,8BAJI,MAAM,KACN,MAAM,GACL,WAAW,MAAM,CAAC,CAoB7B;AAuBM,oFAHmB,OAAO,gCAiBhC;AASM,8CAJI,MAAM,KACN,MAAM,UACN,MAAM;;;;EAyChB;;;;;;;;;;;;;;;;;;;;;;;;;;;YA1Ha,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/diff.test.d.ts b/nodejs/node_modules/lib0/dist/diff.test.d.ts new file mode 100644 index 00000000..5df670c3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff.test.d.ts @@ -0,0 +1,6 @@ +export function testDiffing(tc: t.TestCase): void; +export function testRepeatDiffing(tc: t.TestCase): void; +export function testSimpleDiffWithCursor(tc: t.TestCase): void; +export function testArrayDiffing(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=diff.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/diff.test.d.ts.map b/nodejs/node_modules/lib0/dist/diff.test.d.ts.map new file mode 100644 index 00000000..5dadf868 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/diff.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.test.d.ts","sourceRoot":"","sources":["../diff.test.js"],"names":[],"mappings":"AA0BO,gCAFI,EAAE,QAAQ,QAmBpB;AAKM,sCAFI,EAAE,QAAQ,QAQpB;AAKM,6CAFI,EAAE,QAAQ,QA4CpB;AAKM,qCAFI,EAAE,QAAQ,QAQpB;mBA7GkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/dom-16daf1a0.cjs b/nodejs/node_modules/lib0/dist/dom-16daf1a0.cjs new file mode 100644 index 00000000..ec093177 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/dom-16daf1a0.cjs @@ -0,0 +1,342 @@ +'use strict'; + +var pair = require('./pair-ab022bc3.cjs'); +var map = require('./map-0dabcc55.cjs'); + +/* eslint-env browser */ + +/* c8 ignore start */ +/** + * @type {Document} + */ +const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {}); + +/** + * @param {string} name + * @return {HTMLElement} + */ +const createElement = name => doc.createElement(name); + +/** + * @return {DocumentFragment} + */ +const createDocumentFragment = () => doc.createDocumentFragment(); + +/** + * @param {string} text + * @return {Text} + */ +const createTextNode = text => doc.createTextNode(text); + +const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null); + +/** + * @param {HTMLElement} el + * @param {string} name + * @param {Object} opts + */ +const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts)); + +/** + * @param {Element} el + * @param {Array>} attrs Array of key-value pairs + * @return {Element} + */ +const setAttributes = (el, attrs) => { + pair.forEach(attrs, (key, value) => { + if (value === false) { + el.removeAttribute(key); + } else if (value === true) { + el.setAttribute(key, ''); + } else { + // @ts-ignore + el.setAttribute(key, value); + } + }); + return el +}; + +/** + * @param {Element} el + * @param {Map} attrs Array of key-value pairs + * @return {Element} + */ +const setAttributesMap = (el, attrs) => { + attrs.forEach((value, key) => { el.setAttribute(key, value); }); + return el +}; + +/** + * @param {Array|HTMLCollection} children + * @return {DocumentFragment} + */ +const fragment = children => { + const fragment = createDocumentFragment(); + for (let i = 0; i < children.length; i++) { + appendChild(fragment, children[i]); + } + return fragment +}; + +/** + * @param {Element} parent + * @param {Array} nodes + * @return {Element} + */ +const append = (parent, nodes) => { + appendChild(parent, fragment(nodes)); + return parent +}; + +/** + * @param {HTMLElement} el + */ +const remove = el => el.remove(); + +/** + * @param {EventTarget} el + * @param {string} name + * @param {EventListener} f + */ +const addEventListener = (el, name, f) => el.addEventListener(name, f); + +/** + * @param {EventTarget} el + * @param {string} name + * @param {EventListener} f + */ +const removeEventListener = (el, name, f) => el.removeEventListener(name, f); + +/** + * @param {Node} node + * @param {Array>} listeners + * @return {Node} + */ +const addEventListeners = (node, listeners) => { + pair.forEach(listeners, (name, f) => addEventListener(node, name, f)); + return node +}; + +/** + * @param {Node} node + * @param {Array>} listeners + * @return {Node} + */ +const removeEventListeners = (node, listeners) => { + pair.forEach(listeners, (name, f) => removeEventListener(node, name, f)); + return node +}; + +/** + * @param {string} name + * @param {Array|pair.Pair>} attrs Array of key-value pairs + * @param {Array} children + * @return {Element} + */ +const element = (name, attrs = [], children = []) => + append(setAttributes(createElement(name), attrs), children); + +/** + * @param {number} width + * @param {number} height + */ +const canvas = (width, height) => { + const c = /** @type {HTMLCanvasElement} */ (createElement('canvas')); + c.height = height; + c.width = width; + return c +}; + +/** + * @param {string} t + * @return {Text} + */ +const text = createTextNode; + +/** + * @param {pair.Pair} pair + */ +const pairToStyleString = pair => `${pair.left}:${pair.right};`; + +/** + * @param {Array>} pairs + * @return {string} + */ +const pairsToStyleString = pairs => pairs.map(pairToStyleString).join(''); + +/** + * @param {Map} m + * @return {string} + */ +const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join(''); + +/** + * @todo should always query on a dom element + * + * @param {HTMLElement|ShadowRoot} el + * @param {string} query + * @return {HTMLElement | null} + */ +const querySelector = (el, query) => el.querySelector(query); + +/** + * @param {HTMLElement|ShadowRoot} el + * @param {string} query + * @return {NodeListOf} + */ +const querySelectorAll = (el, query) => el.querySelectorAll(query); + +/** + * @param {string} id + * @return {HTMLElement} + */ +const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id)); + +/** + * @param {string} html + * @return {HTMLElement} + */ +const _parse = html => domParser.parseFromString(`${html}`, 'text/html').body; + +/** + * @param {string} html + * @return {DocumentFragment} + */ +const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes)); + +/** + * @param {string} html + * @return {HTMLElement} + */ +const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild); + +/** + * @param {HTMLElement} oldEl + * @param {HTMLElement|DocumentFragment} newEl + */ +const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl); + +/** + * @param {HTMLElement} parent + * @param {HTMLElement} el + * @param {Node|null} ref + * @return {HTMLElement} + */ +const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref); + +/** + * @param {Node} parent + * @param {Node} child + * @return {Node} + */ +const appendChild = (parent, child) => parent.appendChild(child); + +const ELEMENT_NODE = doc.ELEMENT_NODE; +const TEXT_NODE = doc.TEXT_NODE; +const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE; +const COMMENT_NODE = doc.COMMENT_NODE; +const DOCUMENT_NODE = doc.DOCUMENT_NODE; +const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE; +const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE; + +/** + * @param {any} node + * @param {number} type + */ +const checkNodeType = (node, type) => node.nodeType === type; + +/** + * @param {Node} parent + * @param {HTMLElement} child + */ +const isParentOf = (parent, child) => { + let p = child.parentNode; + while (p && p !== parent) { + p = p.parentNode; + } + return p === parent +}; +/* c8 ignore stop */ + +var dom = /*#__PURE__*/Object.freeze({ + __proto__: null, + doc: doc, + createElement: createElement, + createDocumentFragment: createDocumentFragment, + createTextNode: createTextNode, + domParser: domParser, + emitCustomEvent: emitCustomEvent, + setAttributes: setAttributes, + setAttributesMap: setAttributesMap, + fragment: fragment, + append: append, + remove: remove, + addEventListener: addEventListener, + removeEventListener: removeEventListener, + addEventListeners: addEventListeners, + removeEventListeners: removeEventListeners, + element: element, + canvas: canvas, + text: text, + pairToStyleString: pairToStyleString, + pairsToStyleString: pairsToStyleString, + mapToStyleString: mapToStyleString, + querySelector: querySelector, + querySelectorAll: querySelectorAll, + getElementById: getElementById, + parseFragment: parseFragment, + parseElement: parseElement, + replaceWith: replaceWith, + insertBefore: insertBefore, + appendChild: appendChild, + ELEMENT_NODE: ELEMENT_NODE, + TEXT_NODE: TEXT_NODE, + CDATA_SECTION_NODE: CDATA_SECTION_NODE, + COMMENT_NODE: COMMENT_NODE, + DOCUMENT_NODE: DOCUMENT_NODE, + DOCUMENT_TYPE_NODE: DOCUMENT_TYPE_NODE, + DOCUMENT_FRAGMENT_NODE: DOCUMENT_FRAGMENT_NODE, + checkNodeType: checkNodeType, + isParentOf: isParentOf +}); + +exports.CDATA_SECTION_NODE = CDATA_SECTION_NODE; +exports.COMMENT_NODE = COMMENT_NODE; +exports.DOCUMENT_FRAGMENT_NODE = DOCUMENT_FRAGMENT_NODE; +exports.DOCUMENT_NODE = DOCUMENT_NODE; +exports.DOCUMENT_TYPE_NODE = DOCUMENT_TYPE_NODE; +exports.ELEMENT_NODE = ELEMENT_NODE; +exports.TEXT_NODE = TEXT_NODE; +exports.addEventListener = addEventListener; +exports.addEventListeners = addEventListeners; +exports.append = append; +exports.appendChild = appendChild; +exports.canvas = canvas; +exports.checkNodeType = checkNodeType; +exports.createDocumentFragment = createDocumentFragment; +exports.createElement = createElement; +exports.createTextNode = createTextNode; +exports.doc = doc; +exports.dom = dom; +exports.domParser = domParser; +exports.element = element; +exports.emitCustomEvent = emitCustomEvent; +exports.fragment = fragment; +exports.getElementById = getElementById; +exports.insertBefore = insertBefore; +exports.isParentOf = isParentOf; +exports.mapToStyleString = mapToStyleString; +exports.pairToStyleString = pairToStyleString; +exports.pairsToStyleString = pairsToStyleString; +exports.parseElement = parseElement; +exports.parseFragment = parseFragment; +exports.querySelector = querySelector; +exports.querySelectorAll = querySelectorAll; +exports.remove = remove; +exports.removeEventListener = removeEventListener; +exports.removeEventListeners = removeEventListeners; +exports.replaceWith = replaceWith; +exports.setAttributes = setAttributes; +exports.setAttributesMap = setAttributesMap; +exports.text = text; +//# sourceMappingURL=dom-16daf1a0.cjs.map diff --git a/nodejs/node_modules/lib0/dist/dom-16daf1a0.cjs.map b/nodejs/node_modules/lib0/dist/dom-16daf1a0.cjs.map new file mode 100644 index 00000000..14715f8b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/dom-16daf1a0.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dom-16daf1a0.cjs","sources":["../dom.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\nimport * as pair from './pair.js'\nimport * as map from './map.js'\n\n/* c8 ignore start */\n/**\n * @type {Document}\n */\nexport const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\nexport const createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\nexport const createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\nexport const createTextNode = text => doc.createTextNode(text)\n\nexport const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\nexport const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array>} attrs Array of key-value pairs\n * @return {Element}\n */\nexport const setAttributes = (el, attrs) => {\n pair.forEach(attrs, (key, value) => {\n if (value === false) {\n el.removeAttribute(key)\n } else if (value === true) {\n el.setAttribute(key, '')\n } else {\n // @ts-ignore\n el.setAttribute(key, value)\n }\n })\n return el\n}\n\n/**\n * @param {Element} el\n * @param {Map} attrs Array of key-value pairs\n * @return {Element}\n */\nexport const setAttributesMap = (el, attrs) => {\n attrs.forEach((value, key) => { el.setAttribute(key, value) })\n return el\n}\n\n/**\n * @param {Array|HTMLCollection} children\n * @return {DocumentFragment}\n */\nexport const fragment = children => {\n const fragment = createDocumentFragment()\n for (let i = 0; i < children.length; i++) {\n appendChild(fragment, children[i])\n }\n return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array} nodes\n * @return {Element}\n */\nexport const append = (parent, nodes) => {\n appendChild(parent, fragment(nodes))\n return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\nexport const remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nexport const addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nexport const removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\nexport const addEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => addEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {Node} node\n * @param {Array>} listeners\n * @return {Node}\n */\nexport const removeEventListeners = (node, listeners) => {\n pair.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n return node\n}\n\n/**\n * @param {string} name\n * @param {Array|pair.Pair>} attrs Array of key-value pairs\n * @param {Array} children\n * @return {Element}\n */\nexport const element = (name, attrs = [], children = []) =>\n append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\nexport const canvas = (width, height) => {\n const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n c.height = height\n c.width = width\n return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\nexport const text = createTextNode\n\n/**\n * @param {pair.Pair} pair\n */\nexport const pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array>} pairs\n * @return {string}\n */\nexport const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map} m\n * @return {string}\n */\nexport const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\nexport const querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf}\n */\nexport const querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\nexport const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nconst _parse = html => domParser.parseFromString(`${html}`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\nexport const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nexport const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\nexport const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\nexport const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\nexport const appendChild = (parent, child) => parent.appendChild(child)\n\nexport const ELEMENT_NODE = doc.ELEMENT_NODE\nexport const TEXT_NODE = doc.TEXT_NODE\nexport const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nexport const COMMENT_NODE = doc.COMMENT_NODE\nexport const DOCUMENT_NODE = doc.DOCUMENT_NODE\nexport const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nexport const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nexport const checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nexport const isParentOf = (parent, child) => {\n let p = child.parentNode\n while (p && p !== parent) {\n p = p.parentNode\n }\n return p === parent\n}\n/* c8 ignore stop */\n"],"names":["pair.forEach","map.map"],"mappings":";;;;;AAAA;AAUA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,4BAA4B,OAAO,QAAQ,KAAK,WAAW,GAAG,QAAQ,GAAG,EAAE,EAAC;AAC5F;AACA;AACA;AACA;AACA;AACY,MAAC,aAAa,GAAG,IAAI,IAAI,GAAG,CAAC,aAAa,CAAC,IAAI,EAAC;AAC5D;AACA;AACA;AACA;AACY,MAAC,sBAAsB,GAAG,MAAM,GAAG,CAAC,sBAAsB,GAAE;AACxE;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,IAAI,IAAI,GAAG,CAAC,cAAc,CAAC,IAAI,EAAC;AAC9D;AACY,MAAC,SAAS,6BAA6B,OAAO,SAAS,KAAK,WAAW,GAAG,IAAI,SAAS,EAAE,GAAG,IAAI,EAAC;AAC7G;AACA;AACA;AACA;AAC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,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,WAAU;AAC1B,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,MAAM,EAAE;AAC5B,IAAI,CAAC,GAAG,CAAC,CAAC,WAAU;AACpB,GAAG;AACH,EAAE,OAAO,CAAC,KAAK,MAAM;AACrB,EAAC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/dom.cjs b/nodejs/node_modules/lib0/dist/dom.cjs new file mode 100644 index 00000000..a6465ff0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/dom.cjs @@ -0,0 +1,49 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./pair-ab022bc3.cjs'); +require('./map-0dabcc55.cjs'); +var dom = require('./dom-16daf1a0.cjs'); + + + +exports.CDATA_SECTION_NODE = dom.CDATA_SECTION_NODE; +exports.COMMENT_NODE = dom.COMMENT_NODE; +exports.DOCUMENT_FRAGMENT_NODE = dom.DOCUMENT_FRAGMENT_NODE; +exports.DOCUMENT_NODE = dom.DOCUMENT_NODE; +exports.DOCUMENT_TYPE_NODE = dom.DOCUMENT_TYPE_NODE; +exports.ELEMENT_NODE = dom.ELEMENT_NODE; +exports.TEXT_NODE = dom.TEXT_NODE; +exports.addEventListener = dom.addEventListener; +exports.addEventListeners = dom.addEventListeners; +exports.append = dom.append; +exports.appendChild = dom.appendChild; +exports.canvas = dom.canvas; +exports.checkNodeType = dom.checkNodeType; +exports.createDocumentFragment = dom.createDocumentFragment; +exports.createElement = dom.createElement; +exports.createTextNode = dom.createTextNode; +exports.doc = dom.doc; +exports.domParser = dom.domParser; +exports.element = dom.element; +exports.emitCustomEvent = dom.emitCustomEvent; +exports.fragment = dom.fragment; +exports.getElementById = dom.getElementById; +exports.insertBefore = dom.insertBefore; +exports.isParentOf = dom.isParentOf; +exports.mapToStyleString = dom.mapToStyleString; +exports.pairToStyleString = dom.pairToStyleString; +exports.pairsToStyleString = dom.pairsToStyleString; +exports.parseElement = dom.parseElement; +exports.parseFragment = dom.parseFragment; +exports.querySelector = dom.querySelector; +exports.querySelectorAll = dom.querySelectorAll; +exports.remove = dom.remove; +exports.removeEventListener = dom.removeEventListener; +exports.removeEventListeners = dom.removeEventListeners; +exports.replaceWith = dom.replaceWith; +exports.setAttributes = dom.setAttributes; +exports.setAttributesMap = dom.setAttributesMap; +exports.text = dom.text; +//# sourceMappingURL=dom.cjs.map diff --git a/nodejs/node_modules/lib0/dist/dom.cjs.map b/nodejs/node_modules/lib0/dist/dom.cjs.map new file mode 100644 index 00000000..555160cd --- /dev/null +++ b/nodejs/node_modules/lib0/dist/dom.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dom.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/dom.d.ts b/nodejs/node_modules/lib0/dist/dom.d.ts new file mode 100644 index 00000000..91701491 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/dom.d.ts @@ -0,0 +1,43 @@ +/** + * @type {Document} + */ +export const doc: Document; +export function createElement(name: string): HTMLElement; +export function createDocumentFragment(): DocumentFragment; +export function createTextNode(text: string): Text; +export const domParser: DOMParser; +export function emitCustomEvent(el: HTMLElement, name: string, opts: Object): boolean; +export function setAttributes(el: Element, attrs: Array>): Element; +export function setAttributesMap(el: Element, attrs: Map): Element; +export function fragment(children: Array | HTMLCollection): DocumentFragment; +export function append(parent: Element, nodes: Array): Element; +export function remove(el: HTMLElement): void; +export function addEventListener(el: EventTarget, name: string, f: EventListener): void; +export function removeEventListener(el: EventTarget, name: string, f: EventListener): void; +export function addEventListeners(node: Node, listeners: Array>): Node; +export function removeEventListeners(node: Node, listeners: Array>): Node; +export function element(name: string, attrs?: Array | pair.Pair>, children?: Array): Element; +export function canvas(width: number, height: number): HTMLCanvasElement; +export function text(text: string): Text; +export function pairToStyleString(pair: pair.Pair): string; +export function pairsToStyleString(pairs: Array>): string; +export function mapToStyleString(m: Map): string; +export function querySelector(el: HTMLElement | ShadowRoot, query: string): HTMLElement | null; +export function querySelectorAll(el: HTMLElement | ShadowRoot, query: string): NodeListOf; +export function getElementById(id: string): HTMLElement; +export function parseFragment(html: string): DocumentFragment; +export function parseElement(html: string): HTMLElement; +export function replaceWith(oldEl: HTMLElement, newEl: HTMLElement | DocumentFragment): void; +export function insertBefore(parent: HTMLElement, el: HTMLElement, ref: Node | null): HTMLElement; +export function appendChild(parent: Node, child: Node): Node; +export const ELEMENT_NODE: 1; +export const TEXT_NODE: 3; +export const CDATA_SECTION_NODE: 4; +export const COMMENT_NODE: 8; +export const DOCUMENT_NODE: 9; +export const DOCUMENT_TYPE_NODE: 10; +export const DOCUMENT_FRAGMENT_NODE: 11; +export function checkNodeType(node: any, type: number): boolean; +export function isParentOf(parent: Node, child: HTMLElement): boolean; +import * as pair from './pair.js'; +//# sourceMappingURL=dom.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/dom.d.ts.map b/nodejs/node_modules/lib0/dist/dom.d.ts.map new file mode 100644 index 00000000..dd62bcde --- /dev/null +++ b/nodejs/node_modules/lib0/dist/dom.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["../dom.js"],"names":[],"mappings":"AAYA;;GAEG;AACH,kBAFU,QAAQ,CAE0E;AAMrF,oCAHI,MAAM,GACL,WAAW,CAEqC;AAKrD,0CAFK,gBAAgB,CAE4C;AAMjE,qCAHI,MAAM,GACL,IAAI,CAE8C;AAE9D,kCAA6G;AAOtG,oCAJI,WAAW,QACX,MAAM,QACN,MAAM,WAE+E;AAOzF,kCAJI,OAAO,SACP,MAAM,KAAK,IAAI,CAAC,MAAM,EAAC,MAAM,GAAC,OAAO,CAAC,CAAC,GACtC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mCAHI,MAAM,GACL,WAAW,CAEsE;AAMtF,mCAHI,WAAW,SACX,WAAW,GAAC,gBAAgB,QAE8B;AAQ9D,qCALI,WAAW,MACX,WAAW,OACX,IAAI,GAAC,IAAI,GACR,WAAW,CAEsD;AAOtE,oCAJI,IAAI,SACJ,IAAI,GACH,IAAI,CAEuD;AAEvE,6BAA4C;AAC5C,0BAAsC;AACtC,mCAAwD;AACxD,6BAA4C;AAC5C,8BAA8C;AAC9C,oCAAwD;AACxD,wCAAgE;AAMzD,oCAHI,GAAG,QACH,MAAM,WAEkD;AAM5D,mCAHI,IAAI,SACJ,WAAW,WAQrB;sBA7PqB,WAAW"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/ecdsa.cjs b/nodejs/node_modules/lib0/dist/ecdsa.cjs new file mode 100644 index 00000000..64013cc3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/ecdsa.cjs @@ -0,0 +1,130 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var webcrypto = require('lib0/webcrypto'); +var common = require('./common.cjs'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var webcrypto__namespace = /*#__PURE__*/_interopNamespace(webcrypto); + +/** + * ECDSA is an asymmetric key for signing + */ + +/** + * @typedef {Array<'sign'|'verify'>} Usages + */ + +/** + * @type {Usages} + */ +const defaultUsages = ['sign', 'verify']; + +const defaultSignAlgorithm = { + name: 'ECDSA', + hash: 'SHA-384' +}; + +/** + * @experimental The API is not final! + * + * Sign a message + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} signature + */ +const sign = (key, data) => + webcrypto__namespace.subtle.sign( + defaultSignAlgorithm, + key, + data + ).then(signature => new Uint8Array(signature)); + +/** + * @experimental The API is not final! + * + * Sign a message + * + * @param {CryptoKey} key + * @param {Uint8Array} signature + * @param {Uint8Array} data + * @return {PromiseLike} signature + */ +const verify = (key, signature, data) => + webcrypto__namespace.subtle.verify( + defaultSignAlgorithm, + key, + signature, + data + ); + +const defaultKeyAlgorithm = { + name: 'ECDSA', + namedCurve: 'P-384' +}; + +/* c8 ignore next */ +/** + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) => + webcrypto__namespace.subtle.generateKey( + defaultKeyAlgorithm, + extractable, + usages + ); + +/** + * @param {any} jwk + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +const importKeyJwk = (jwk, { extractable = false, usages } = {}) => { + if (usages == null) { + /* c8 ignore next 2 */ + usages = jwk.key_ops || defaultUsages; + } + return webcrypto__namespace.subtle.importKey('jwk', jwk, defaultKeyAlgorithm, extractable, /** @type {Usages} */ (usages)) +}; + +/** + * Only suited for importing public keys. + * + * @param {any} raw + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +const importKeyRaw = (raw, { extractable = false, usages = defaultUsages } = {}) => + webcrypto__namespace.subtle.importKey('raw', raw, defaultKeyAlgorithm, extractable, usages); + +exports.exportKeyJwk = common.exportKeyJwk; +exports.exportKeyRaw = common.exportKeyRaw; +exports.generateKeyPair = generateKeyPair; +exports.importKeyJwk = importKeyJwk; +exports.importKeyRaw = importKeyRaw; +exports.sign = sign; +exports.verify = verify; +//# sourceMappingURL=ecdsa.cjs.map diff --git a/nodejs/node_modules/lib0/dist/ecdsa.cjs.map b/nodejs/node_modules/lib0/dist/ecdsa.cjs.map new file mode 100644 index 00000000..fdf2fc14 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/ecdsa.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ecdsa.cjs","sources":["../crypto/ecdsa.js"],"sourcesContent":["/**\n * ECDSA is an asymmetric key for signing\n */\n\nimport * as webcrypto from 'lib0/webcrypto'\nexport { exportKeyJwk, exportKeyRaw } from './common.js'\n\n/**\n * @typedef {Array<'sign'|'verify'>} Usages\n */\n\n/**\n * @type {Usages}\n */\nconst defaultUsages = ['sign', 'verify']\n\nconst defaultSignAlgorithm = {\n name: 'ECDSA',\n hash: 'SHA-384'\n}\n\n/**\n * @experimental The API is not final!\n *\n * Sign a message\n *\n * @param {CryptoKey} key\n * @param {Uint8Array} data\n * @return {PromiseLike} signature\n */\nexport const sign = (key, data) =>\n webcrypto.subtle.sign(\n defaultSignAlgorithm,\n key,\n data\n ).then(signature => new Uint8Array(signature))\n\n/**\n * @experimental The API is not final!\n *\n * Sign a message\n *\n * @param {CryptoKey} key\n * @param {Uint8Array} signature\n * @param {Uint8Array} data\n * @return {PromiseLike} signature\n */\nexport const verify = (key, signature, data) =>\n webcrypto.subtle.verify(\n defaultSignAlgorithm,\n key,\n signature,\n data\n )\n\nconst defaultKeyAlgorithm = {\n name: 'ECDSA',\n namedCurve: 'P-384'\n}\n\n/* c8 ignore next */\n/**\n * @param {Object} opts\n * @param {boolean} [opts.extractable]\n * @param {Usages} [opts.usages]\n */\nexport const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) =>\n webcrypto.subtle.generateKey(\n defaultKeyAlgorithm,\n extractable,\n usages\n )\n\n/**\n * @param {any} jwk\n * @param {Object} opts\n * @param {boolean} [opts.extractable]\n * @param {Usages} [opts.usages]\n */\nexport const importKeyJwk = (jwk, { extractable = false, usages } = {}) => {\n if (usages == null) {\n /* c8 ignore next 2 */\n usages = jwk.key_ops || defaultUsages\n }\n return webcrypto.subtle.importKey('jwk', jwk, defaultKeyAlgorithm, extractable, /** @type {Usages} */ (usages))\n}\n\n/**\n * Only suited for importing public keys.\n *\n * @param {any} raw\n * @param {Object} opts\n * @param {boolean} [opts.extractable]\n * @param {Usages} [opts.usages]\n */\nexport const importKeyRaw = (raw, { extractable = false, usages = defaultUsages } = {}) =>\n webcrypto.subtle.importKey('raw', raw, defaultKeyAlgorithm, extractable, usages)\n"],"names":["webcrypto"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAC;AACxC;AACA,MAAM,oBAAoB,GAAG;AAC7B,EAAE,IAAI,EAAE,OAAO;AACf,EAAE,IAAI,EAAE,SAAS;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,CAAC,GAAG,EAAE,IAAI;AAC9B,EAAEA,oBAAS,CAAC,MAAM,CAAC,IAAI;AACvB,IAAI,oBAAoB;AACxB,IAAI,GAAG;AACP,IAAI,IAAI;AACR,GAAG,CAAC,IAAI,CAAC,SAAS,IAAI,IAAI,UAAU,CAAC,SAAS,CAAC,EAAC;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI;AAC3C,EAAEA,oBAAS,CAAC,MAAM,CAAC,MAAM;AACzB,IAAI,oBAAoB;AACxB,IAAI,GAAG;AACP,IAAI,SAAS;AACb,IAAI,IAAI;AACR,IAAG;AACH;AACA,MAAM,mBAAmB,GAAG;AAC5B,EAAE,IAAI,EAAE,OAAO;AACf,EAAE,UAAU,EAAE,OAAO;AACrB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,eAAe,GAAG,CAAC,EAAE,WAAW,GAAG,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,GAAG,EAAE;AACpF,EAAEA,oBAAS,CAAC,MAAM,CAAC,WAAW;AAC9B,IAAI,mBAAmB;AACvB,IAAI,WAAW;AACf,IAAI,MAAM;AACV,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,YAAY,GAAG,CAAC,GAAG,EAAE,EAAE,WAAW,GAAG,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK;AAC3E,EAAE,IAAI,MAAM,IAAI,IAAI,EAAE;AACtB;AACA,IAAI,MAAM,GAAG,GAAG,CAAC,OAAO,IAAI,cAAa;AACzC,GAAG;AACH,EAAE,OAAOA,oBAAS,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,mBAAmB,EAAE,WAAW,yBAAyB,MAAM,EAAE;AACjH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,YAAY,GAAG,CAAC,GAAG,EAAE,EAAE,WAAW,GAAG,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,GAAG,EAAE;AACtF,EAAEA,oBAAS,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/encoding-882cb136.cjs b/nodejs/node_modules/lib0/dist/encoding-882cb136.cjs new file mode 100644 index 00000000..2f75f3c4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding-882cb136.cjs @@ -0,0 +1,1017 @@ +'use strict'; + +var math = require('./math-08e068f9.cjs'); +var number = require('./number-466d8922.cjs'); +var binary = require('./binary-ac8e39e2.cjs'); +var string = require('./string-6d104757.cjs'); +var array = require('./array-704ca50e.cjs'); + +/** + * Efficient schema-less binary encoding with support for variable length encoding. + * + * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module encoding + */ + +/** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ +class Encoder { + constructor () { + this.cpos = 0; + this.cbuf = new Uint8Array(100); + /** + * @type {Array} + */ + this.bufs = []; + } +} + +/** + * @function + * @return {Encoder} + */ +const createEncoder = () => new Encoder(); + +/** + * @param {function(Encoder):void} f + */ +const encode = (f) => { + const encoder = createEncoder(); + f(encoder); + return toUint8Array(encoder) +}; + +/** + * The current length of the encoded data. + * + * @function + * @param {Encoder} encoder + * @return {number} + */ +const length = encoder => { + let len = encoder.cpos; + for (let i = 0; i < encoder.bufs.length; i++) { + len += encoder.bufs[i].length; + } + return len +}; + +/** + * Check whether encoder is empty. + * + * @function + * @param {Encoder} encoder + * @return {boolean} + */ +const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0; + +/** + * Transform to Uint8Array. + * + * @function + * @param {Encoder} encoder + * @return {Uint8Array} The created ArrayBuffer. + */ +const toUint8Array = encoder => { + const uint8arr = new Uint8Array(length(encoder)); + let curPos = 0; + for (let i = 0; i < encoder.bufs.length; i++) { + const d = encoder.bufs[i]; + uint8arr.set(d, curPos); + curPos += d.length; + } + uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos); + return uint8arr +}; + +/** + * Verify that it is possible to write `len` bytes wtihout checking. If + * necessary, a new Buffer with the required length is attached. + * + * @param {Encoder} encoder + * @param {number} len + */ +const verifyLen = (encoder, len) => { + const bufferLen = encoder.cbuf.length; + if (bufferLen - encoder.cpos < len) { + encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos)); + encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2); + encoder.cpos = 0; + } +}; + +/** + * Write one byte to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {number} num The byte that is to be encoded. + */ +const write = (encoder, num) => { + const bufferLen = encoder.cbuf.length; + if (encoder.cpos === bufferLen) { + encoder.bufs.push(encoder.cbuf); + encoder.cbuf = new Uint8Array(bufferLen * 2); + encoder.cpos = 0; + } + encoder.cbuf[encoder.cpos++] = num; +}; + +/** + * Write one byte at a specific position. + * Position must already be written (i.e. encoder.length > pos) + * + * @function + * @param {Encoder} encoder + * @param {number} pos Position to which to write data + * @param {number} num Unsigned 8-bit integer + */ +const set = (encoder, pos, num) => { + let buffer = null; + // iterate all buffers and adjust position + for (let i = 0; i < encoder.bufs.length && buffer === null; i++) { + const b = encoder.bufs[i]; + if (pos < b.length) { + buffer = b; // found buffer + } else { + pos -= b.length; + } + } + if (buffer === null) { + // use current buffer + buffer = encoder.cbuf; + } + buffer[pos] = num; +}; + +/** + * Write one byte as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeUint8 = write; + +/** + * Write one byte as an unsigned Integer at a specific location. + * + * @function + * @param {Encoder} encoder + * @param {number} pos The location where the data will be written. + * @param {number} num The number that is to be encoded. + */ +const setUint8 = set; + +/** + * Write two bytes as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeUint16 = (encoder, num) => { + write(encoder, num & binary.BITS8); + write(encoder, (num >>> 8) & binary.BITS8); +}; +/** + * Write two bytes as an unsigned integer at a specific location. + * + * @function + * @param {Encoder} encoder + * @param {number} pos The location where the data will be written. + * @param {number} num The number that is to be encoded. + */ +const setUint16 = (encoder, pos, num) => { + set(encoder, pos, num & binary.BITS8); + set(encoder, pos + 1, (num >>> 8) & binary.BITS8); +}; + +/** + * Write two bytes as an unsigned integer + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeUint32 = (encoder, num) => { + for (let i = 0; i < 4; i++) { + write(encoder, num & binary.BITS8); + num >>>= 8; + } +}; + +/** + * Write two bytes as an unsigned integer in big endian order. + * (most significant byte first) + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeUint32BigEndian = (encoder, num) => { + for (let i = 3; i >= 0; i--) { + write(encoder, (num >>> (8 * i)) & binary.BITS8); + } +}; + +/** + * Write two bytes as an unsigned integer at a specific location. + * + * @function + * @param {Encoder} encoder + * @param {number} pos The location where the data will be written. + * @param {number} num The number that is to be encoded. + */ +const setUint32 = (encoder, pos, num) => { + for (let i = 0; i < 4; i++) { + set(encoder, pos + i, num & binary.BITS8); + num >>>= 8; + } +}; + +/** + * Write a variable length unsigned integer. Max encodable integer is 2^53. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeVarUint = (encoder, num) => { + while (num > binary.BITS7) { + write(encoder, binary.BIT8 | (binary.BITS7 & num)); + num = math.floor(num / 128); // shift >>> 7 + } + write(encoder, binary.BITS7 & num); +}; + +/** + * Write a variable length integer. + * + * We use the 7th bit instead for signaling that this is a negative number. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeVarInt = (encoder, num) => { + const isNegative = math.isNegativeZero(num); + if (isNegative) { + num = -num; + } + // |- whether to continue reading |- whether is negative |- number + write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num)); + num = math.floor(num / 64); // shift >>> 6 + // We don't need to consider the case of num === 0 so we can use a different + // pattern here than above. + while (num > 0) { + write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num)); + num = math.floor(num / 128); // shift >>> 7 + } +}; + +/** + * A cache to store strings temporarily + */ +const _strBuffer = new Uint8Array(30000); +const _maxStrBSize = _strBuffer.length / 3; + +/** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +const _writeVarStringNative = (encoder, str) => { + if (str.length < _maxStrBSize) { + // We can encode the string into the existing buffer + /* c8 ignore next */ + const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; + writeVarUint(encoder, written); + for (let i = 0; i < written; i++) { + write(encoder, _strBuffer[i]); + } + } else { + writeVarUint8Array(encoder, string.encodeUtf8(str)); + } +}; + +/** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +const _writeVarStringPolyfill = (encoder, str) => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + writeVarUint(encoder, len); + for (let i = 0; i < len; i++) { + write(encoder, /** @type {number} */ (encodedString.codePointAt(i))); + } +}; + +/** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +/* c8 ignore next */ +const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill; + +/** + * Write a string terminated by a special byte sequence. This is not very performant and is + * generally discouraged. However, the resulting byte arrays are lexiographically ordered which + * makes this a nice feature for databases. + * + * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +const writeTerminatedString = (encoder, str) => + writeTerminatedUint8Array(encoder, string.encodeUtf8(str)); + +/** + * Write a terminating Uint8Array. Note that this is not performant and is generally + * discouraged. There are few situations when this is needed. + * + * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1. + * + * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then + * the result is terminated using the 0x0 character. + * + * This is basically how many systems implement null terminated strings. However, we use an escape + * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key + * encoder for NoSql databases). + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} buf The string that is to be encoded. + */ +const writeTerminatedUint8Array = (encoder, buf) => { + for (let i = 0; i < buf.length; i++) { + const b = buf[i]; + if (b === 0 || b === 1) { + write(encoder, 1); + } + write(encoder, buf[i]); + } + write(encoder, 0); +}; + +/** + * Write the content of another Encoder. + * + * @TODO: can be improved! + * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure. + * Encoders start with a rather big initial buffer. + * + * @function + * @param {Encoder} encoder The enUint8Arr + * @param {Encoder} append The BinaryEncoder to be written. + */ +const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append)); + +/** + * Append fixed-length Uint8Array to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ +const writeUint8Array = (encoder, uint8Array) => { + const bufferLen = encoder.cbuf.length; + const cpos = encoder.cpos; + const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length); + const rightCopyLen = uint8Array.length - leftCopyLen; + encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); + encoder.cpos += leftCopyLen; + if (rightCopyLen > 0) { + // Still something to write, write right half.. + // Append new buffer + encoder.bufs.push(encoder.cbuf); + // must have at least size of remaining buffer + encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen)); + // copy array + encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); + encoder.cpos = rightCopyLen; + } +}; + +/** + * Append an Uint8Array to Encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ +const writeVarUint8Array = (encoder, uint8Array) => { + writeVarUint(encoder, uint8Array.byteLength); + writeUint8Array(encoder, uint8Array); +}; + +/** + * Create an DataView of the next `len` bytes. Use it to write data after + * calling this function. + * + * ```js + * // write float32 using DataView + * const dv = writeOnDataView(encoder, 4) + * dv.setFloat32(0, 1.1) + * // read float32 using DataView + * const dv = readFromDataView(encoder, 4) + * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result) + * ``` + * + * @param {Encoder} encoder + * @param {number} len + * @return {DataView} + */ +const writeOnDataView = (encoder, len) => { + verifyLen(encoder, len); + const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); + encoder.cpos += len; + return dview +}; + +/** + * @param {Encoder} encoder + * @param {number} num + */ +const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); + +/** + * @param {Encoder} encoder + * @param {number} num + */ +const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); + +/** + * @param {Encoder} encoder + * @param {bigint} num + */ +const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false); + +/** + * @param {Encoder} encoder + * @param {bigint} num + */ +const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false); + +const floatTestBed = new DataView(new ArrayBuffer(4)); +/** + * Check if a number can be encoded as a 32 bit float. + * + * @param {number} num + * @return {boolean} + */ +const isFloat32 = num => { + floatTestBed.setFloat32(0, num); + return floatTestBed.getFloat32(0) === num +}; + +/** + * Encode data with efficient binary format. + * + * Differences to JSON: + * • Transforms data to a binary format (not to a string) + * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON) + * • Numbers are efficiently encoded either as a variable length integer, as a + * 32 bit float, as a 64 bit float, or as a 64 bit bigint. + * + * Encoding table: + * + * | Data Type | Prefix | Encoding Method | Comment | + * | ------------------- | -------- | ------------------ | ------- | + * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined | + * | null | 126 | | | + * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers | + * | float32 | 124 | writeFloat32 | | + * | float64 | 123 | writeFloat64 | | + * | bigint | 122 | writeBigInt64 | | + * | boolean (false) | 121 | | True and false are different data types so we save the following byte | + * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false | + * | string | 119 | writeVarString | | + * | object | 118 | custom | Writes {length} then {length} key-value pairs | + * | array | 117 | custom | Writes {length} then {length} json values | + * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data | + * + * Reasons for the decreasing prefix: + * We need the first bit for extendability (later we may want to encode the + * prefix with writeVarUint). The remaining 7 bits are divided as follows: + * [0-30] the beginning of the data range is used for custom purposes + * (defined by the function that uses this library) + * [31-127] the end of the data range is used for data encoding by + * lib0/encoding.js + * + * @param {Encoder} encoder + * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data + */ +const writeAny = (encoder, data) => { + switch (typeof data) { + case 'string': + // TYPE 119: STRING + write(encoder, 119); + writeVarString(encoder, data); + break + case 'number': + if (number.isInteger(data) && math.abs(data) <= binary.BITS31) { + // TYPE 125: INTEGER + write(encoder, 125); + writeVarInt(encoder, data); + } else if (isFloat32(data)) { + // TYPE 124: FLOAT32 + write(encoder, 124); + writeFloat32(encoder, data); + } else { + // TYPE 123: FLOAT64 + write(encoder, 123); + writeFloat64(encoder, data); + } + break + case 'bigint': + // TYPE 122: BigInt + write(encoder, 122); + writeBigInt64(encoder, data); + break + case 'object': + if (data === null) { + // TYPE 126: null + write(encoder, 126); + } else if (array.isArray(data)) { + // TYPE 117: Array + write(encoder, 117); + writeVarUint(encoder, data.length); + for (let i = 0; i < data.length; i++) { + writeAny(encoder, data[i]); + } + } else if (data instanceof Uint8Array) { + // TYPE 116: ArrayBuffer + write(encoder, 116); + writeVarUint8Array(encoder, data); + } else { + // TYPE 118: Object + write(encoder, 118); + const keys = Object.keys(data); + writeVarUint(encoder, keys.length); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + writeVarString(encoder, key); + writeAny(encoder, data[key]); + } + } + break + case 'boolean': + // TYPE 120/121: boolean (true/false) + write(encoder, data ? 120 : 121); + break + default: + // TYPE 127: undefined + write(encoder, 127); + } +}; + +/** + * Now come a few stateful encoder that have their own classes. + */ + +/** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ +class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor (writer) { + super(); + /** + * The writer + */ + this.w = writer; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + /** + * @param {T} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1); // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1; + // write first value + this.w(this, v); + this.s = v; + } + } +} + +/** + * Basic diff decoder using variable length encoding. + * + * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt. + */ +class IntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor (start) { + super(); + /** + * Current state + * @type {number} + */ + this.s = start; + } + + /** + * @param {number} v + */ + write (v) { + writeVarInt(this, v - this.s); + this.s = v; + } +} + +/** + * A combination of IntDiffEncoder and RleEncoder. + * + * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding. + * + * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5]) + */ +class RleIntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor (start) { + super(); + /** + * Current state + * @type {number} + */ + this.s = start; + this.count = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v && this.count > 0) { + this.count++; + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1); // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1; + // write first value + writeVarInt(this, v - this.s); + this.s = v; + } + } +} + +/** + * @param {UintOptRleEncoder} encoder + */ +const flushUintOptRleEncoder = encoder => { + if (encoder.count > 0) { + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set sign to positive + // case 2: write several values. set sign to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } +}; + +/** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ +class UintOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + flushUintOptRleEncoder(this); + this.count = 1; + this.s = v; + } + } + + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array () { + flushUintOptRleEncoder(this); + return toUint8Array(this.encoder) + } +} + +/** + * Increasing Uint Optimized RLE Encoder + * + * The RLE encoder counts the number of same occurences of the same value. + * The IncUintOptRle encoder counts if the value increases. + * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded + * as [1, 3, 5]. + */ +class IncUintOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.s + this.count === v) { + this.count++; + } else { + flushUintOptRleEncoder(this); + this.count = 1; + this.s = v; + } + } + + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array () { + flushUintOptRleEncoder(this); + return toUint8Array(this.encoder) + } +} + +/** + * @param {IntDiffOptRleEncoder} encoder + */ +const flushIntDiffOptRleEncoder = encoder => { + if (encoder.count > 0) { + // 31 bit making up the diff | wether to write the counter + // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1) + const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set first bit to positive + // case 2: write several values. set first bit to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encodedDiff); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } +}; + +/** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ +class IntDiffOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.diff === v - this.s) { + this.s = v; + this.count++; + } else { + flushIntDiffOptRleEncoder(this); + this.count = 1; + this.diff = v - this.s; + this.s = v; + } + } + + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array () { + flushIntDiffOptRleEncoder(this); + return toUint8Array(this.encoder) + } +} + +/** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ +class StringEncoder { + constructor () { + /** + * @type {Array} + */ + this.sarr = []; + this.s = ''; + this.lensE = new UintOptRleEncoder(); + } + + /** + * @param {string} string + */ + write (string) { + this.s += string; + if (this.s.length > 19) { + this.sarr.push(this.s); + this.s = ''; + } + this.lensE.write(string.length); + } + + toUint8Array () { + const encoder = new Encoder(); + this.sarr.push(this.s); + this.s = ''; + writeVarString(encoder, this.sarr.join('')); + writeUint8Array(encoder, this.lensE.toUint8Array()); + return toUint8Array(encoder) + } +} + +var encoding = /*#__PURE__*/Object.freeze({ + __proto__: null, + Encoder: Encoder, + createEncoder: createEncoder, + encode: encode, + length: length, + hasContent: hasContent, + toUint8Array: toUint8Array, + verifyLen: verifyLen, + write: write, + set: set, + writeUint8: writeUint8, + setUint8: setUint8, + writeUint16: writeUint16, + setUint16: setUint16, + writeUint32: writeUint32, + writeUint32BigEndian: writeUint32BigEndian, + setUint32: setUint32, + writeVarUint: writeVarUint, + writeVarInt: writeVarInt, + _writeVarStringNative: _writeVarStringNative, + _writeVarStringPolyfill: _writeVarStringPolyfill, + writeVarString: writeVarString, + writeTerminatedString: writeTerminatedString, + writeTerminatedUint8Array: writeTerminatedUint8Array, + writeBinaryEncoder: writeBinaryEncoder, + writeUint8Array: writeUint8Array, + writeVarUint8Array: writeVarUint8Array, + writeOnDataView: writeOnDataView, + writeFloat32: writeFloat32, + writeFloat64: writeFloat64, + writeBigInt64: writeBigInt64, + writeBigUint64: writeBigUint64, + writeAny: writeAny, + RleEncoder: RleEncoder, + IntDiffEncoder: IntDiffEncoder, + RleIntDiffEncoder: RleIntDiffEncoder, + UintOptRleEncoder: UintOptRleEncoder, + IncUintOptRleEncoder: IncUintOptRleEncoder, + IntDiffOptRleEncoder: IntDiffOptRleEncoder, + StringEncoder: StringEncoder +}); + +exports.Encoder = Encoder; +exports.IncUintOptRleEncoder = IncUintOptRleEncoder; +exports.IntDiffEncoder = IntDiffEncoder; +exports.IntDiffOptRleEncoder = IntDiffOptRleEncoder; +exports.RleEncoder = RleEncoder; +exports.RleIntDiffEncoder = RleIntDiffEncoder; +exports.StringEncoder = StringEncoder; +exports.UintOptRleEncoder = UintOptRleEncoder; +exports._writeVarStringNative = _writeVarStringNative; +exports._writeVarStringPolyfill = _writeVarStringPolyfill; +exports.createEncoder = createEncoder; +exports.encode = encode; +exports.encoding = encoding; +exports.hasContent = hasContent; +exports.length = length; +exports.set = set; +exports.setUint16 = setUint16; +exports.setUint32 = setUint32; +exports.setUint8 = setUint8; +exports.toUint8Array = toUint8Array; +exports.verifyLen = verifyLen; +exports.write = write; +exports.writeAny = writeAny; +exports.writeBigInt64 = writeBigInt64; +exports.writeBigUint64 = writeBigUint64; +exports.writeBinaryEncoder = writeBinaryEncoder; +exports.writeFloat32 = writeFloat32; +exports.writeFloat64 = writeFloat64; +exports.writeOnDataView = writeOnDataView; +exports.writeTerminatedString = writeTerminatedString; +exports.writeTerminatedUint8Array = writeTerminatedUint8Array; +exports.writeUint16 = writeUint16; +exports.writeUint32 = writeUint32; +exports.writeUint32BigEndian = writeUint32BigEndian; +exports.writeUint8 = writeUint8; +exports.writeUint8Array = writeUint8Array; +exports.writeVarInt = writeVarInt; +exports.writeVarString = writeVarString; +exports.writeVarUint = writeVarUint; +exports.writeVarUint8Array = writeVarUint8Array; +//# sourceMappingURL=encoding-882cb136.cjs.map diff --git a/nodejs/node_modules/lib0/dist/encoding-882cb136.cjs.map b/nodejs/node_modules/lib0/dist/encoding-882cb136.cjs.map new file mode 100644 index 00000000..0b1d5e5e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding-882cb136.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding-882cb136.cjs","sources":["../encoding.js"],"sourcesContent":["/**\n * Efficient schema-less binary encoding with support for variable length encoding.\n *\n * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.\n *\n * Encodes numbers in little-endian order (least to most significant byte order)\n * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)\n * which is also used in Protocol Buffers.\n *\n * ```js\n * // encoding step\n * const encoder = encoding.createEncoder()\n * encoding.writeVarUint(encoder, 256)\n * encoding.writeVarString(encoder, 'Hello world!')\n * const buf = encoding.toUint8Array(encoder)\n * ```\n *\n * ```js\n * // decoding step\n * const decoder = decoding.createDecoder(buf)\n * decoding.readVarUint(decoder) // => 256\n * decoding.readVarString(decoder) // => 'Hello world!'\n * decoding.hasContent(decoder) // => false - all data is read\n * ```\n *\n * @module encoding\n */\n\nimport * as math from './math.js'\nimport * as number from './number.js'\nimport * as binary from './binary.js'\nimport * as string from './string.js'\nimport * as array from './array.js'\n\n/**\n * A BinaryEncoder handles the encoding to an Uint8Array.\n */\nexport class Encoder {\n constructor () {\n this.cpos = 0\n this.cbuf = new Uint8Array(100)\n /**\n * @type {Array}\n */\n this.bufs = []\n }\n}\n\n/**\n * @function\n * @return {Encoder}\n */\nexport const createEncoder = () => new Encoder()\n\n/**\n * @param {function(Encoder):void} f\n */\nexport const encode = (f) => {\n const encoder = createEncoder()\n f(encoder)\n return toUint8Array(encoder)\n}\n\n/**\n * The current length of the encoded data.\n *\n * @function\n * @param {Encoder} encoder\n * @return {number}\n */\nexport const length = encoder => {\n let len = encoder.cpos\n for (let i = 0; i < encoder.bufs.length; i++) {\n len += encoder.bufs[i].length\n }\n return len\n}\n\n/**\n * Check whether encoder is empty.\n *\n * @function\n * @param {Encoder} encoder\n * @return {boolean}\n */\nexport const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0\n\n/**\n * Transform to Uint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @return {Uint8Array} The created ArrayBuffer.\n */\nexport const toUint8Array = encoder => {\n const uint8arr = new Uint8Array(length(encoder))\n let curPos = 0\n for (let i = 0; i < encoder.bufs.length; i++) {\n const d = encoder.bufs[i]\n uint8arr.set(d, curPos)\n curPos += d.length\n }\n uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos)\n return uint8arr\n}\n\n/**\n * Verify that it is possible to write `len` bytes wtihout checking. If\n * necessary, a new Buffer with the required length is attached.\n *\n * @param {Encoder} encoder\n * @param {number} len\n */\nexport const verifyLen = (encoder, len) => {\n const bufferLen = encoder.cbuf.length\n if (bufferLen - encoder.cpos < len) {\n encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos))\n encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2)\n encoder.cpos = 0\n }\n}\n\n/**\n * Write one byte to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The byte that is to be encoded.\n */\nexport const write = (encoder, num) => {\n const bufferLen = encoder.cbuf.length\n if (encoder.cpos === bufferLen) {\n encoder.bufs.push(encoder.cbuf)\n encoder.cbuf = new Uint8Array(bufferLen * 2)\n encoder.cpos = 0\n }\n encoder.cbuf[encoder.cpos++] = num\n}\n\n/**\n * Write one byte at a specific position.\n * Position must already be written (i.e. encoder.length > pos)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos Position to which to write data\n * @param {number} num Unsigned 8-bit integer\n */\nexport const set = (encoder, pos, num) => {\n let buffer = null\n // iterate all buffers and adjust position\n for (let i = 0; i < encoder.bufs.length && buffer === null; i++) {\n const b = encoder.bufs[i]\n if (pos < b.length) {\n buffer = b // found buffer\n } else {\n pos -= b.length\n }\n }\n if (buffer === null) {\n // use current buffer\n buffer = encoder.cbuf\n }\n buffer[pos] = num\n}\n\n/**\n * Write one byte as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint8 = write\n\n/**\n * Write one byte as an unsigned Integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint8 = set\n\n/**\n * Write two bytes as an unsigned integer.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint16 = (encoder, num) => {\n write(encoder, num & binary.BITS8)\n write(encoder, (num >>> 8) & binary.BITS8)\n}\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint16 = (encoder, pos, num) => {\n set(encoder, pos, num & binary.BITS8)\n set(encoder, pos + 1, (num >>> 8) & binary.BITS8)\n}\n\n/**\n * Write two bytes as an unsigned integer\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32 = (encoder, num) => {\n for (let i = 0; i < 4; i++) {\n write(encoder, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Write two bytes as an unsigned integer at a specific location.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} pos The location where the data will be written.\n * @param {number} num The number that is to be encoded.\n */\nexport const setUint32 = (encoder, pos, num) => {\n for (let i = 0; i < 4; i++) {\n set(encoder, pos + i, num & binary.BITS8)\n num >>>= 8\n }\n}\n\n/**\n * Write a variable length unsigned integer. Max encodable integer is 2^53.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarUint = (encoder, num) => {\n while (num > binary.BITS7) {\n write(encoder, binary.BIT8 | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n write(encoder, binary.BITS7 & num)\n}\n\n/**\n * Write a variable length integer.\n *\n * We use the 7th bit instead for signaling that this is a negative number.\n *\n * @function\n * @param {Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeVarInt = (encoder, num) => {\n const isNegative = math.isNegativeZero(num)\n if (isNegative) {\n num = -num\n }\n // |- whether to continue reading |- whether is negative |- number\n write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num))\n num = math.floor(num / 64) // shift >>> 6\n // We don't need to consider the case of num === 0 so we can use a different\n // pattern here than above.\n while (num > 0) {\n write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num))\n num = math.floor(num / 128) // shift >>> 7\n }\n}\n\n/**\n * A cache to store strings temporarily\n */\nconst _strBuffer = new Uint8Array(30000)\nconst _maxStrBSize = _strBuffer.length / 3\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringNative = (encoder, str) => {\n if (str.length < _maxStrBSize) {\n // We can encode the string into the existing buffer\n /* c8 ignore next */\n const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0\n writeVarUint(encoder, written)\n for (let i = 0; i < written; i++) {\n write(encoder, _strBuffer[i])\n }\n } else {\n writeVarUint8Array(encoder, string.encodeUtf8(str))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const _writeVarStringPolyfill = (encoder, str) => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n writeVarUint(encoder, len)\n for (let i = 0; i < len; i++) {\n write(encoder, /** @type {number} */ (encodedString.codePointAt(i)))\n }\n}\n\n/**\n * Write a variable length string.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\n/* c8 ignore next */\nexport const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill\n\n/**\n * Write a string terminated by a special byte sequence. This is not very performant and is\n * generally discouraged. However, the resulting byte arrays are lexiographically ordered which\n * makes this a nice feature for databases.\n *\n * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array.\n *\n * @function\n * @param {Encoder} encoder\n * @param {String} str The string that is to be encoded.\n */\nexport const writeTerminatedString = (encoder, str) =>\n writeTerminatedUint8Array(encoder, string.encodeUtf8(str))\n\n/**\n * Write a terminating Uint8Array. Note that this is not performant and is generally\n * discouraged. There are few situations when this is needed.\n *\n * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1.\n *\n * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then\n * the result is terminated using the 0x0 character.\n *\n * This is basically how many systems implement null terminated strings. However, we use an escape\n * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key\n * encoder for NoSql databases).\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} buf The string that is to be encoded.\n */\nexport const writeTerminatedUint8Array = (encoder, buf) => {\n for (let i = 0; i < buf.length; i++) {\n const b = buf[i]\n if (b === 0 || b === 1) {\n write(encoder, 1)\n }\n write(encoder, buf[i])\n }\n write(encoder, 0)\n}\n\n/**\n * Write the content of another Encoder.\n *\n * @TODO: can be improved!\n * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure.\n * Encoders start with a rather big initial buffer.\n *\n * @function\n * @param {Encoder} encoder The enUint8Arr\n * @param {Encoder} append The BinaryEncoder to be written.\n */\nexport const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append))\n\n/**\n * Append fixed-length Uint8Array to the encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeUint8Array = (encoder, uint8Array) => {\n const bufferLen = encoder.cbuf.length\n const cpos = encoder.cpos\n const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length)\n const rightCopyLen = uint8Array.length - leftCopyLen\n encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos)\n encoder.cpos += leftCopyLen\n if (rightCopyLen > 0) {\n // Still something to write, write right half..\n // Append new buffer\n encoder.bufs.push(encoder.cbuf)\n // must have at least size of remaining buffer\n encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen))\n // copy array\n encoder.cbuf.set(uint8Array.subarray(leftCopyLen))\n encoder.cpos = rightCopyLen\n }\n}\n\n/**\n * Append an Uint8Array to Encoder.\n *\n * @function\n * @param {Encoder} encoder\n * @param {Uint8Array} uint8Array\n */\nexport const writeVarUint8Array = (encoder, uint8Array) => {\n writeVarUint(encoder, uint8Array.byteLength)\n writeUint8Array(encoder, uint8Array)\n}\n\n/**\n * Create an DataView of the next `len` bytes. Use it to write data after\n * calling this function.\n *\n * ```js\n * // write float32 using DataView\n * const dv = writeOnDataView(encoder, 4)\n * dv.setFloat32(0, 1.1)\n * // read float32 using DataView\n * const dv = readFromDataView(encoder, 4)\n * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)\n * ```\n *\n * @param {Encoder} encoder\n * @param {number} len\n * @return {DataView}\n */\nexport const writeOnDataView = (encoder, len) => {\n verifyLen(encoder, len)\n const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len)\n encoder.cpos += len\n return dview\n}\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {number} num\n */\nexport const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false)\n\n/**\n * @param {Encoder} encoder\n * @param {bigint} num\n */\nexport const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false)\n\nconst floatTestBed = new DataView(new ArrayBuffer(4))\n/**\n * Check if a number can be encoded as a 32 bit float.\n *\n * @param {number} num\n * @return {boolean}\n */\nconst isFloat32 = num => {\n floatTestBed.setFloat32(0, num)\n return floatTestBed.getFloat32(0) === num\n}\n\n/**\n * Encode data with efficient binary format.\n *\n * Differences to JSON:\n * • Transforms data to a binary format (not to a string)\n * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)\n * • Numbers are efficiently encoded either as a variable length integer, as a\n * 32 bit float, as a 64 bit float, or as a 64 bit bigint.\n *\n * Encoding table:\n *\n * | Data Type | Prefix | Encoding Method | Comment |\n * | ------------------- | -------- | ------------------ | ------- |\n * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |\n * | null | 126 | | |\n * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |\n * | float32 | 124 | writeFloat32 | |\n * | float64 | 123 | writeFloat64 | |\n * | bigint | 122 | writeBigInt64 | |\n * | boolean (false) | 121 | | True and false are different data types so we save the following byte |\n * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |\n * | string | 119 | writeVarString | |\n * | object | 118 | custom | Writes {length} then {length} key-value pairs |\n * | array | 117 | custom | Writes {length} then {length} json values |\n * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |\n *\n * Reasons for the decreasing prefix:\n * We need the first bit for extendability (later we may want to encode the\n * prefix with writeVarUint). The remaining 7 bits are divided as follows:\n * [0-30] the beginning of the data range is used for custom purposes\n * (defined by the function that uses this library)\n * [31-127] the end of the data range is used for data encoding by\n * lib0/encoding.js\n *\n * @param {Encoder} encoder\n * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data\n */\nexport const writeAny = (encoder, data) => {\n switch (typeof data) {\n case 'string':\n // TYPE 119: STRING\n write(encoder, 119)\n writeVarString(encoder, data)\n break\n case 'number':\n if (number.isInteger(data) && math.abs(data) <= binary.BITS31) {\n // TYPE 125: INTEGER\n write(encoder, 125)\n writeVarInt(encoder, data)\n } else if (isFloat32(data)) {\n // TYPE 124: FLOAT32\n write(encoder, 124)\n writeFloat32(encoder, data)\n } else {\n // TYPE 123: FLOAT64\n write(encoder, 123)\n writeFloat64(encoder, data)\n }\n break\n case 'bigint':\n // TYPE 122: BigInt\n write(encoder, 122)\n writeBigInt64(encoder, data)\n break\n case 'object':\n if (data === null) {\n // TYPE 126: null\n write(encoder, 126)\n } else if (array.isArray(data)) {\n // TYPE 117: Array\n write(encoder, 117)\n writeVarUint(encoder, data.length)\n for (let i = 0; i < data.length; i++) {\n writeAny(encoder, data[i])\n }\n } else if (data instanceof Uint8Array) {\n // TYPE 116: ArrayBuffer\n write(encoder, 116)\n writeVarUint8Array(encoder, data)\n } else {\n // TYPE 118: Object\n write(encoder, 118)\n const keys = Object.keys(data)\n writeVarUint(encoder, keys.length)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n writeVarString(encoder, key)\n writeAny(encoder, data[key])\n }\n }\n break\n case 'boolean':\n // TYPE 120/121: boolean (true/false)\n write(encoder, data ? 120 : 121)\n break\n default:\n // TYPE 127: undefined\n write(encoder, 127)\n }\n}\n\n/**\n * Now come a few stateful encoder that have their own classes.\n */\n\n/**\n * Basic Run Length Encoder - a basic compression implementation.\n *\n * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated.\n *\n * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf\n *\n * @note T must not be null!\n *\n * @template T\n */\nexport class RleEncoder extends Encoder {\n /**\n * @param {function(Encoder, T):void} writer\n */\n constructor (writer) {\n super()\n /**\n * The writer\n */\n this.w = writer\n /**\n * Current state\n * @type {T|null}\n */\n this.s = null\n this.count = 0\n }\n\n /**\n * @param {T} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n this.w(this, v)\n this.s = v\n }\n }\n}\n\n/**\n * Basic diff decoder using variable length encoding.\n *\n * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt.\n */\nexport class IntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n writeVarInt(this, v - this.s)\n this.s = v\n }\n}\n\n/**\n * A combination of IntDiffEncoder and RleEncoder.\n *\n * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding.\n *\n * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5])\n */\nexport class RleIntDiffEncoder extends Encoder {\n /**\n * @param {number} start\n */\n constructor (start) {\n super()\n /**\n * Current state\n * @type {number}\n */\n this.s = start\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v && this.count > 0) {\n this.count++\n } else {\n if (this.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw\n }\n this.count = 1\n // write first value\n writeVarInt(this, v - this.s)\n this.s = v\n }\n }\n}\n\n/**\n * @param {UintOptRleEncoder} encoder\n */\nconst flushUintOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set sign to positive\n // case 2: write several values. set sign to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder.\n *\n * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write\n * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count.\n *\n * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3)\n */\nexport class UintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Increasing Uint Optimized RLE Encoder\n *\n * The RLE encoder counts the number of same occurences of the same value.\n * The IncUintOptRle encoder counts if the value increases.\n * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded\n * as [1, 3, 5].\n */\nexport class IncUintOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.s + this.count === v) {\n this.count++\n } else {\n flushUintOptRleEncoder(this)\n this.count = 1\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushUintOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * @param {IntDiffOptRleEncoder} encoder\n */\nconst flushIntDiffOptRleEncoder = encoder => {\n if (encoder.count > 0) {\n // 31 bit making up the diff | wether to write the counter\n // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1)\n const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1)\n // flush counter, unless this is the first value (count = 0)\n // case 1: just a single value. set first bit to positive\n // case 2: write several values. set first bit to negative to indicate that there is a length coming\n writeVarInt(encoder.encoder, encodedDiff)\n if (encoder.count > 1) {\n writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw\n }\n }\n}\n\n/**\n * A combination of the IntDiffEncoder and the UintOptRleEncoder.\n *\n * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes\n * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers!\n *\n * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1])\n *\n * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains:\n * * 1 bit that denotes whether the next value is a count (LSB)\n * * 1 bit that denotes whether this value is negative (MSB - 1)\n * * 1 bit that denotes whether to continue reading the variable length integer (MSB)\n *\n * Therefore, only five bits remain to encode diff ranges.\n *\n * Use this Encoder only when appropriate. In most cases, this is probably a bad idea.\n */\nexport class IntDiffOptRleEncoder {\n constructor () {\n this.encoder = new Encoder()\n /**\n * @type {number}\n */\n this.s = 0\n this.count = 0\n this.diff = 0\n }\n\n /**\n * @param {number} v\n */\n write (v) {\n if (this.diff === v - this.s) {\n this.s = v\n this.count++\n } else {\n flushIntDiffOptRleEncoder(this)\n this.count = 1\n this.diff = v - this.s\n this.s = v\n }\n }\n\n /**\n * Flush the encoded state and transform this to a Uint8Array.\n *\n * Note that this should only be called once.\n */\n toUint8Array () {\n flushIntDiffOptRleEncoder(this)\n return toUint8Array(this.encoder)\n }\n}\n\n/**\n * Optimized String Encoder.\n *\n * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted.\n * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?).\n *\n * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call.\n *\n * The lengths are encoded using a UintOptRleEncoder.\n */\nexport class StringEncoder {\n constructor () {\n /**\n * @type {Array}\n */\n this.sarr = []\n this.s = ''\n this.lensE = new UintOptRleEncoder()\n }\n\n /**\n * @param {string} string\n */\n write (string) {\n this.s += string\n if (this.s.length > 19) {\n this.sarr.push(this.s)\n this.s = ''\n }\n this.lensE.write(string.length)\n }\n\n toUint8Array () {\n const encoder = new Encoder()\n this.sarr.push(this.s)\n this.s = ''\n writeVarString(encoder, this.sarr.join(''))\n writeUint8Array(encoder, this.lensE.toUint8Array())\n return toUint8Array(encoder)\n }\n}\n"],"names":["math.max","binary.BITS8","binary.BITS7","binary.BIT8","math.floor","math.isNegativeZero","binary.BITS6","binary.BIT7","string.utf8TextEncoder","string.encodeUtf8","math.min","number.isInteger","math.abs","binary.BITS31","array.isArray"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA;AACA;AACA;AACA;AACO,MAAM,OAAO,CAAC;AACrB,EAAE,WAAW,CAAC,GAAG;AACjB,IAAI,IAAI,CAAC,IAAI,GAAG,EAAC;AACjB,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,UAAU,CAAC,GAAG,EAAC;AACnC;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,GAAE;AAClB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACY,MAAC,aAAa,GAAG,MAAM,IAAI,OAAO,GAAE;AAChD;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,CAAC,KAAK;AAC7B,EAAE,MAAM,OAAO,GAAG,aAAa,GAAE;AACjC,EAAE,CAAC,CAAC,OAAO,EAAC;AACZ,EAAE,OAAO,YAAY,CAAC,OAAO,CAAC;AAC9B,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,OAAO,IAAI;AACjC,EAAE,IAAI,GAAG,GAAG,OAAO,CAAC,KAAI;AACxB,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAChD,IAAI,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAM;AACjC,GAAG;AACH,EAAE,OAAO,GAAG;AACZ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,UAAU,GAAG,OAAO,IAAI,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,OAAO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M,CAAC,MAAM,EAAC;AACnC,GAAG;AACH;AACA,EAAE,YAAY,CAAC,GAAG;AAClB,IAAI,MAAM,OAAO,GAAG,IAAI,OAAO,GAAE;AACjC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAC;AAC1B,IAAI,IAAI,CAAC,CAAC,GAAG,GAAE;AACf,IAAI,cAAc,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,EAAC;AAC/C,IAAI,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,EAAC;AACvD,IAAI,OAAO,YAAY,CAAC,OAAO,CAAC;AAChC,GAAG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/encoding.cjs b/nodejs/node_modules/lib0/dist/encoding.cjs new file mode 100644 index 00000000..e547e785 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding.cjs @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./math-08e068f9.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +var encoding = require('./encoding-882cb136.cjs'); +require('./set-0f209abb.cjs'); + + + +exports.Encoder = encoding.Encoder; +exports.IncUintOptRleEncoder = encoding.IncUintOptRleEncoder; +exports.IntDiffEncoder = encoding.IntDiffEncoder; +exports.IntDiffOptRleEncoder = encoding.IntDiffOptRleEncoder; +exports.RleEncoder = encoding.RleEncoder; +exports.RleIntDiffEncoder = encoding.RleIntDiffEncoder; +exports.StringEncoder = encoding.StringEncoder; +exports.UintOptRleEncoder = encoding.UintOptRleEncoder; +exports._writeVarStringNative = encoding._writeVarStringNative; +exports._writeVarStringPolyfill = encoding._writeVarStringPolyfill; +exports.createEncoder = encoding.createEncoder; +exports.encode = encoding.encode; +exports.hasContent = encoding.hasContent; +exports.length = encoding.length; +exports.set = encoding.set; +exports.setUint16 = encoding.setUint16; +exports.setUint32 = encoding.setUint32; +exports.setUint8 = encoding.setUint8; +exports.toUint8Array = encoding.toUint8Array; +exports.verifyLen = encoding.verifyLen; +exports.write = encoding.write; +exports.writeAny = encoding.writeAny; +exports.writeBigInt64 = encoding.writeBigInt64; +exports.writeBigUint64 = encoding.writeBigUint64; +exports.writeBinaryEncoder = encoding.writeBinaryEncoder; +exports.writeFloat32 = encoding.writeFloat32; +exports.writeFloat64 = encoding.writeFloat64; +exports.writeOnDataView = encoding.writeOnDataView; +exports.writeTerminatedString = encoding.writeTerminatedString; +exports.writeTerminatedUint8Array = encoding.writeTerminatedUint8Array; +exports.writeUint16 = encoding.writeUint16; +exports.writeUint32 = encoding.writeUint32; +exports.writeUint32BigEndian = encoding.writeUint32BigEndian; +exports.writeUint8 = encoding.writeUint8; +exports.writeUint8Array = encoding.writeUint8Array; +exports.writeVarInt = encoding.writeVarInt; +exports.writeVarString = encoding.writeVarString; +exports.writeVarUint = encoding.writeVarUint; +exports.writeVarUint8Array = encoding.writeVarUint8Array; +//# sourceMappingURL=encoding.cjs.map diff --git a/nodejs/node_modules/lib0/dist/encoding.cjs.map b/nodejs/node_modules/lib0/dist/encoding.cjs.map new file mode 100644 index 00000000..4f4b002f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/encoding.d.ts b/nodejs/node_modules/lib0/dist/encoding.d.ts new file mode 100644 index 00000000..fe4568b8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding.d.ts @@ -0,0 +1,233 @@ +/** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ +export class Encoder { + cpos: number; + cbuf: Uint8Array; + /** + * @type {Array} + */ + bufs: Array; +} +export function createEncoder(): Encoder; +export function encode(f: (arg0: Encoder) => void): Uint8Array; +export function length(encoder: Encoder): number; +export function hasContent(encoder: Encoder): boolean; +export function toUint8Array(encoder: Encoder): Uint8Array; +export function verifyLen(encoder: Encoder, len: number): void; +export function write(encoder: Encoder, num: number): void; +export function set(encoder: Encoder, pos: number, num: number): void; +export function writeUint8(encoder: Encoder, num: number): void; +export function setUint8(encoder: Encoder, pos: number, num: number): void; +export function writeUint16(encoder: Encoder, num: number): void; +export function setUint16(encoder: Encoder, pos: number, num: number): void; +export function writeUint32(encoder: Encoder, num: number): void; +export function writeUint32BigEndian(encoder: Encoder, num: number): void; +export function setUint32(encoder: Encoder, pos: number, num: number): void; +export function writeVarUint(encoder: Encoder, num: number): void; +export function writeVarInt(encoder: Encoder, num: number): void; +export function _writeVarStringNative(encoder: Encoder, str: string): void; +export function _writeVarStringPolyfill(encoder: Encoder, str: string): void; +export function writeVarString(encoder: Encoder, str: string): void; +export function writeTerminatedString(encoder: Encoder, str: string): void; +export function writeTerminatedUint8Array(encoder: Encoder, buf: Uint8Array): void; +export function writeBinaryEncoder(encoder: Encoder, append: Encoder): void; +export function writeUint8Array(encoder: Encoder, uint8Array: Uint8Array): void; +export function writeVarUint8Array(encoder: Encoder, uint8Array: Uint8Array): void; +export function writeOnDataView(encoder: Encoder, len: number): DataView; +export function writeFloat32(encoder: Encoder, num: number): void; +export function writeFloat64(encoder: Encoder, num: number): void; +export function writeBigInt64(encoder: Encoder, num: bigint): any; +export function writeBigUint64(encoder: Encoder, num: bigint): any; +export function writeAny(encoder: Encoder, data: undefined | null | number | bigint | boolean | string | { + [x: string]: any; +} | Array | Uint8Array): void; +/** + * Now come a few stateful encoder that have their own classes. + */ +/** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ +export class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor(writer: (arg0: Encoder, arg1: T) => void); + /** + * The writer + */ + w: (arg0: Encoder, arg1: T) => void; + /** + * Current state + * @type {T|null} + */ + s: T | null; + count: number; + /** + * @param {T} v + */ + write(v: T): void; +} +/** + * Basic diff decoder using variable length encoding. + * + * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt. + */ +export class IntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor(start: number); + /** + * Current state + * @type {number} + */ + s: number; + /** + * @param {number} v + */ + write(v: number): void; +} +/** + * A combination of IntDiffEncoder and RleEncoder. + * + * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding. + * + * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5]) + */ +export class RleIntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor(start: number); + /** + * Current state + * @type {number} + */ + s: number; + count: number; + /** + * @param {number} v + */ + write(v: number): void; +} +/** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ +export class UintOptRleEncoder { + encoder: Encoder; + /** + * @type {number} + */ + s: number; + count: number; + /** + * @param {number} v + */ + write(v: number): void; + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array(): Uint8Array; +} +/** + * Increasing Uint Optimized RLE Encoder + * + * The RLE encoder counts the number of same occurences of the same value. + * The IncUintOptRle encoder counts if the value increases. + * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded + * as [1, 3, 5]. + */ +export class IncUintOptRleEncoder { + encoder: Encoder; + /** + * @type {number} + */ + s: number; + count: number; + /** + * @param {number} v + */ + write(v: number): void; + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array(): Uint8Array; +} +/** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ +export class IntDiffOptRleEncoder { + encoder: Encoder; + /** + * @type {number} + */ + s: number; + count: number; + diff: number; + /** + * @param {number} v + */ + write(v: number): void; + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array(): Uint8Array; +} +/** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ +export class StringEncoder { + /** + * @type {Array} + */ + sarr: Array; + s: string; + lensE: UintOptRleEncoder; + /** + * @param {string} string + */ + write(string: string): void; + toUint8Array(): Uint8Array; +} +//# sourceMappingURL=encoding.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/encoding.d.ts.map b/nodejs/node_modules/lib0/dist/encoding.d.ts.map new file mode 100644 index 00000000..4ea0c5be --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["../encoding.js"],"names":[],"mappings":"AAkCA;;GAEG;AACH;IAEI,aAAa;IACb,iBAA+B;IAC/B;;OAEG;IACH,MAFU,MAAM,UAAU,CAAC,CAEb;CAEjB;AAMM,iCAFK,OAAO,CAE6B;AAKzC,iCAFa,OAAO,KAAE,IAAI,cAMhC;AASM,gCAHI,OAAO,GACN,MAAM,CAQjB;AASM,oCAHI,OAAO,GACN,OAAO,CAE6D;AASzE,sCAHI,OAAO,GACN,UAAU,CAYrB;AASM,mCAHI,OAAO,OACP,MAAM,QAShB;AASM,+BAHI,OAAO,OACP,MAAM,QAUhB;AAWM,6BAJI,OAAO,OACP,MAAM,OACN,MAAM,QAkBhB;AAnCM,oCAHI,OAAO,OACP,MAAM,QAUhB;AAWM,kCAJI,OAAO,OACP,MAAM,OACN,MAAM,QAkBhB;AA4BM,qCAHI,OAAO,OACP,MAAM,QAKhB;AASM,mCAJI,OAAO,OACP,MAAM,OACN,MAAM,QAKhB;AASM,qCAHI,OAAO,OACP,MAAM,QAOhB;AAUM,8CAHI,OAAO,OACP,MAAM,QAMhB;AAUM,mCAJI,OAAO,OACP,MAAM,OACN,MAAM,QAOhB;AASM,sCAHI,OAAO,OACP,MAAM,QAQhB;AAWM,qCAHI,OAAO,OACP,MAAM,QAgBhB;AAeM,+CAHI,OAAO,qBAejB;AASM,iDAHI,OAAO,qBAUjB;AA5BM,wCAHI,OAAO,qBAejB;AAuCM,+CAHI,OAAO,qBAI0C;AAmBrD,mDAHI,OAAO,OACP,UAAU,QAWpB;AAaM,4CAHI,OAAO,UACP,OAAO,QAEmF;AAS9F,yCAHI,OAAO,cACP,UAAU,QA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AUhB;IAED;;;;OAIG;IACH,2BAGC;CACF;AAoBD;;;;;;;;;;;;;;;;GAgBG;AACH;IAEI,iBAA4B;IAC5B;;OAEG;IACH,GAFU,MAAM,CAEN;IACV,cAAc;IACd,aAAa;IAGf;;OAEG;IACH,SAFW,MAAM,QAYhB;IAED;;;;OAIG;IACH,2BAGC;CACF;AAED;;;;;;;;;GASG;AACH;IAEI;;OAEG;IACH,MAFU,MAAM,MAAM,CAAC,CAET;IACd,UAAW;IACX,yBAAoC;IAGtC;;OAEG;IACH,cAFW,MAAM,QAShB;IAED,2BAOC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/encoding.test.d.ts b/nodejs/node_modules/lib0/dist/encoding.test.d.ts new file mode 100644 index 00000000..83f548f4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding.test.d.ts @@ -0,0 +1,50 @@ +export function testGolangBinaryEncodingCompatibility(): void; +export function testVerifyLen(): void; +export function testStringEncodingPerformanceNativeVsPolyfill(): void; +export function testDecodingPerformanceNativeVsPolyfill(): void; +export function testStringDecodingPerformance(): void; +export function testAnyEncodeUnknowns(_tc: t.TestCase): void; +export function testAnyEncodeDate(_tc: t.TestCase): void; +export function testEncodeMax32bitUint(_tc: t.TestCase): void; +export function testVarUintEncoding(_tc: t.TestCase): void; +export function testVarIntEncoding(_tc: t.TestCase): void; +export function testRepeatVarUintEncoding(tc: t.TestCase): void; +export function testRepeatVarUintEncoding53bit(tc: t.TestCase): void; +export function testRepeatVarIntEncoding(tc: t.TestCase): void; +export function testRepeatVarIntEncoding53bit(tc: t.TestCase): void; +export function testRepeanntAnyEncoding(tc: t.TestCase): void; +export function testRepeatPeekVarUintEncoding(tc: t.TestCase): void; +export function testRepeatPeekVarIntEncoding(tc: t.TestCase): void; +export function testAnyVsJsonEncoding(tc: t.TestCase): void; +export function testStringEncoding(_tc: t.TestCase): void; +export function testRepeatStringEncoding(tc: t.TestCase): void; +export function testSetMethods(_tc: t.TestCase): void; +export function testRepeatRandomWrites(tc: t.TestCase): void; +export function testWriteUint8ArrayOverflow(_tc: t.TestCase): void; +export function testSetOnOverflow(_tc: t.TestCase): void; +export function testCloneDecoder(_tc: t.TestCase): void; +export function testWriteBinaryEncoder(_tc: t.TestCase): void; +export function testOverflowStringDecoding(tc: t.TestCase): void; +export function testRleEncoder(_tc: t.TestCase): void; +export function testRleIntDiffEncoder(_tc: t.TestCase): void; +export function testUintOptRleEncoder(_tc: t.TestCase): void; +export function testIncUintOptRleEncoder(_tc: t.TestCase): void; +export function testIntDiffRleEncoder(_tc: t.TestCase): void; +export function testIntEncoders(tc: t.TestCase): void; +export function testIntDiffEncoder(_tc: t.TestCase): void; +export function testStringDecoder(tc: t.TestCase): void; +export function testLargeNumberEncoding(tc: t.TestCase): void; +export function testInvalidVarIntEncoding(_tc: t.TestCase): void; +export function testTerminatedEncodering(_tc: t.TestCase): void; +export type EncodingPair = { + read: (arg0: decoding.Decoder) => any; + write: (arg0: encoding.Encoder, arg1: any) => void; + gen: (arg0: prng.PRNG) => any; + compare: (arg0: any, arg1: any) => boolean; + name: string; +}; +import * as t from './testing.js'; +import * as decoding from './decoding.js'; +import * as encoding from './encoding.js'; +import * as prng from './prng.js'; +//# sourceMappingURL=encoding.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/encoding.test.d.ts.map b/nodejs/node_modules/lib0/dist/encoding.test.d.ts.map new file mode 100644 index 00000000..a0fdcca9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/encoding.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.test.d.ts","sourceRoot":"","sources":["../encoding.test.js"],"names":[],"mappings":"AA6CO,8DAkCN;AAwCM,sCAQN;AAEM,sEA2CN;AAEM,gEAoDN;AAEM,sDAiDN;AAKM,2CAFI,EAAE,QAAQ,QAYpB;AAKM,uCAFI,EAAE,QAAQ,QAIpB;AAKM,4CAFI,EAAE,QAAQ,QAIpB;AAKM,yCAFI,EAAE,QAAQ,Q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nodejs/node_modules/lib0/dist/environment-f4d7c3e5.cjs b/nodejs/node_modules/lib0/dist/environment-f4d7c3e5.cjs new file mode 100644 index 00000000..dfeff1cb --- /dev/null +++ b/nodejs/node_modules/lib0/dist/environment-f4d7c3e5.cjs @@ -0,0 +1,169 @@ +'use strict'; + +var map = require('./map-0dabcc55.cjs'); +var string = require('./string-6d104757.cjs'); +var conditions = require('./conditions-f5c0c102.cjs'); +var storage = require('./storage.cjs'); +var _function = require('./function-314fdc56.cjs'); + +/** + * Isomorphic module to work access the environment (query params, env variables). + * + * @module map + */ + +/* c8 ignore next 2 */ +// @ts-ignore +const isNode = typeof process !== 'undefined' && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; + +/* c8 ignore next */ +const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode; +/* c8 ignore next 3 */ +const isMac = typeof navigator !== 'undefined' + ? /Mac/.test(navigator.platform) + : false; + +/** + * @type {Map} + */ +let params; + +/* c8 ignore start */ +const computeParams = () => { + if (params === undefined) { + if (isNode) { + params = map.create(); + const pargs = process.argv; + let currParamName = null; + for (let i = 0; i < pargs.length; i++) { + const parg = pargs[i]; + if (parg[0] === '-') { + if (currParamName !== null) { + params.set(currParamName, ''); + } + currParamName = parg; + } else { + if (currParamName !== null) { + params.set(currParamName, parg); + currParamName = null; + } + } + } + if (currParamName !== null) { + params.set(currParamName, ''); + } + // in ReactNative for example this would not be true (unless connected to the Remote Debugger) + } else if (typeof location === 'object') { + params = map.create(); // eslint-disable-next-line no-undef + (location.search || '?').slice(1).split('&').forEach((kv) => { + if (kv.length !== 0) { + const [key, value] = kv.split('='); + params.set(`--${string.fromCamelCase(key, '-')}`, value); + params.set(`-${string.fromCamelCase(key, '-')}`, value); + } + }); + } else { + params = map.create(); + } + } + return params +}; +/* c8 ignore stop */ + +/** + * @param {string} name + * @return {boolean} + */ +/* c8 ignore next */ +const hasParam = (name) => computeParams().has(name); + +/** + * @param {string} name + * @param {string} defaultVal + * @return {string} + */ +/* c8 ignore next 2 */ +const getParam = (name, defaultVal) => + computeParams().get(name) || defaultVal; + +/** + * @param {string} name + * @return {string|null} + */ +/* c8 ignore next 4 */ +const getVariable = (name) => + isNode + ? conditions.undefinedToNull(process.env[name.toUpperCase().replaceAll('-', '_')]) + : conditions.undefinedToNull(storage.varStorage.getItem(name)); + +/** + * @param {string} name + * @return {string|null} + */ +/* c8 ignore next 2 */ +const getConf = (name) => + computeParams().get('--' + name) || getVariable(name); + +/** + * @param {string} name + * @return {string} + */ +/* c8 ignore next 5 */ +const ensureConf = (name) => { + const c = getConf(name); + if (c == null) throw new Error(`Expected configuration "${name.toUpperCase().replaceAll('-', '_')}"`) + return c +}; + +/** + * @param {string} name + * @return {boolean} + */ +/* c8 ignore next 2 */ +const hasConf = (name) => + hasParam('--' + name) || getVariable(name) !== null; + +/* c8 ignore next */ +const production = hasConf('production'); + +/* c8 ignore next 2 */ +const forceColor = isNode && + _function.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2']); + +/* c8 ignore start */ +const supportsColor = !hasParam('no-colors') && + (!isNode || process.stdout.isTTY || forceColor) && ( + !isNode || hasParam('color') || forceColor || + getVariable('COLORTERM') !== null || + (getVariable('TERM') || '').includes('color') +); +/* c8 ignore stop */ + +var environment = /*#__PURE__*/Object.freeze({ + __proto__: null, + isNode: isNode, + isBrowser: isBrowser, + isMac: isMac, + hasParam: hasParam, + getParam: getParam, + getVariable: getVariable, + getConf: getConf, + ensureConf: ensureConf, + hasConf: hasConf, + production: production, + supportsColor: supportsColor +}); + +exports.ensureConf = ensureConf; +exports.environment = environment; +exports.getConf = getConf; +exports.getParam = getParam; +exports.getVariable = getVariable; +exports.hasConf = hasConf; +exports.hasParam = hasParam; +exports.isBrowser = isBrowser; +exports.isMac = isMac; +exports.isNode = isNode; +exports.production = production; +exports.supportsColor = supportsColor; +//# sourceMappingURL=environment-f4d7c3e5.cjs.map diff --git a/nodejs/node_modules/lib0/dist/environment-f4d7c3e5.cjs.map b/nodejs/node_modules/lib0/dist/environment-f4d7c3e5.cjs.map new file mode 100644 index 00000000..7ebb4254 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/environment-f4d7c3e5.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"environment-f4d7c3e5.cjs","sources":["../environment.js"],"sourcesContent":["/**\n * Isomorphic module to work access the environment (query params, env variables).\n *\n * @module map\n */\n\nimport * as map from './map.js'\nimport * as string from './string.js'\nimport * as conditions from './conditions.js'\nimport * as storage from './storage.js'\nimport * as f from './function.js'\n\n/* c8 ignore next 2 */\n// @ts-ignore\nexport const isNode = typeof process !== 'undefined' && process.release && /node|io\\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n\n/* c8 ignore next */\nexport const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode\n/* c8 ignore next 3 */\nexport const isMac = typeof navigator !== 'undefined'\n ? /Mac/.test(navigator.platform)\n : false\n\n/**\n * @type {Map}\n */\nlet params\nconst args = []\n\n/* c8 ignore start */\nconst computeParams = () => {\n if (params === undefined) {\n if (isNode) {\n params = map.create()\n const pargs = process.argv\n let currParamName = null\n for (let i = 0; i < pargs.length; i++) {\n const parg = pargs[i]\n if (parg[0] === '-') {\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n currParamName = parg\n } else {\n if (currParamName !== null) {\n params.set(currParamName, parg)\n currParamName = null\n } else {\n args.push(parg)\n }\n }\n }\n if (currParamName !== null) {\n params.set(currParamName, '')\n }\n // in ReactNative for example this would not be true (unless connected to the Remote Debugger)\n } else if (typeof location === 'object') {\n params = map.create(); // eslint-disable-next-line no-undef\n (location.search || '?').slice(1).split('&').forEach((kv) => {\n if (kv.length !== 0) {\n const [key, value] = kv.split('=')\n params.set(`--${string.fromCamelCase(key, '-')}`, value)\n params.set(`-${string.fromCamelCase(key, '-')}`, value)\n }\n })\n } else {\n params = map.create()\n }\n }\n return params\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next */\nexport const hasParam = (name) => computeParams().has(name)\n\n/**\n * @param {string} name\n * @param {string} defaultVal\n * @return {string}\n */\n/* c8 ignore next 2 */\nexport const getParam = (name, defaultVal) =>\n computeParams().get(name) || defaultVal\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 4 */\nexport const getVariable = (name) =>\n isNode\n ? conditions.undefinedToNull(process.env[name.toUpperCase().replaceAll('-', '_')])\n : conditions.undefinedToNull(storage.varStorage.getItem(name))\n\n/**\n * @param {string} name\n * @return {string|null}\n */\n/* c8 ignore next 2 */\nexport const getConf = (name) =>\n computeParams().get('--' + name) || getVariable(name)\n\n/**\n * @param {string} name\n * @return {string}\n */\n/* c8 ignore next 5 */\nexport const ensureConf = (name) => {\n const c = getConf(name)\n if (c == null) throw new Error(`Expected configuration \"${name.toUpperCase().replaceAll('-', '_')}\"`)\n return c\n}\n\n/**\n * @param {string} name\n * @return {boolean}\n */\n/* c8 ignore next 2 */\nexport const hasConf = (name) =>\n hasParam('--' + name) || getVariable(name) !== null\n\n/* c8 ignore next */\nexport const production = hasConf('production')\n\n/* c8 ignore next 2 */\nconst forceColor = isNode &&\n f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2'])\n\n/* c8 ignore start */\nexport const supportsColor = !hasParam('no-colors') &&\n (!isNode || process.stdout.isTTY || forceColor) && (\n !isNode || hasParam('color') || forceColor ||\n getVariable('COLORTERM') !== null ||\n (getVariable('TERM') || '').includes('color')\n)\n/* c8 ignore stop */\n"],"names":["map.create","string.fromCamelCase","conditions.undefinedToNull","storage.varStorage","f.isOneOf"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AAOA;AACA;AACA;AACY,MAAC,MAAM,GAAG,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,OAAO,IAAI,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,I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,CAAC,OAAO,CAAC,IAAI,UAAU;AAC5C,IAAI,WAAW,CAAC,WAAW,CAAC,KAAK,IAAI;AACrC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,OAAO,CAAC;AACjD,EAAC;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/environment.cjs b/nodejs/node_modules/lib0/dist/environment.cjs new file mode 100644 index 00000000..bc29a7ce --- /dev/null +++ b/nodejs/node_modules/lib0/dist/environment.cjs @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./map-0dabcc55.cjs'); +require('./string-6d104757.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +var environment = require('./environment-f4d7c3e5.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./object-fecf6a7b.cjs'); + + + +exports.ensureConf = environment.ensureConf; +exports.getConf = environment.getConf; +exports.getParam = environment.getParam; +exports.getVariable = environment.getVariable; +exports.hasConf = environment.hasConf; +exports.hasParam = environment.hasParam; +exports.isBrowser = environment.isBrowser; +exports.isMac = environment.isMac; +exports.isNode = environment.isNode; +exports.production = environment.production; +exports.supportsColor = environment.supportsColor; +//# sourceMappingURL=environment.cjs.map diff --git a/nodejs/node_modules/lib0/dist/environment.cjs.map b/nodejs/node_modules/lib0/dist/environment.cjs.map new file mode 100644 index 00000000..306ad5b0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/environment.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"environment.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/environment.d.ts b/nodejs/node_modules/lib0/dist/environment.d.ts new file mode 100644 index 00000000..d014c146 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/environment.d.ts @@ -0,0 +1,12 @@ +export const isNode: boolean; +export const isBrowser: boolean; +export const isMac: boolean; +export function hasParam(name: string): boolean; +export function getParam(name: string, defaultVal: string): string; +export function getVariable(name: string): string | null; +export function getConf(name: string): string | null; +export function ensureConf(name: string): string; +export function hasConf(name: string): boolean; +export const production: boolean; +export const supportsColor: boolean; +//# sourceMappingURL=environment.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/environment.d.ts.map b/nodejs/node_modules/lib0/dist/environment.d.ts.map new file mode 100644 index 00000000..a4fcb1c0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/environment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../environment.js"],"names":[],"mappings":"AAcA,6BAA0N;AAG1N,gCAAoG;AAEpG,4BAES;AAyDF,+BAJI,MAAM,GACL,OAAO,CAGwC;AAQpD,+BALI,MAAM,cACN,MAAM,GACL,MAAM,CAIuB;AAOlC,kCAJI,MAAM,GACL,MAAM,GAAC,IAAI,CAM2C;AAO3D,8BAJI,MAAM,GACL,MAAM,GAAC,IAAI,CAIgC;AAOhD,iCAJI,MAAM,GACL,MAAM,CAOjB;AAOM,8BAJI,MAAM,GACL,OAAO,CAIkC;AAGrD,iCAA+C;AAO/C,oCAKC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/error-8582d695.cjs b/nodejs/node_modules/lib0/dist/error-8582d695.cjs new file mode 100644 index 00000000..5f71e005 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/error-8582d695.cjs @@ -0,0 +1,45 @@ +'use strict'; + +/** + * Error helpers. + * + * @module error + */ + +/** + * @param {string} s + * @return {Error} + */ +/* c8 ignore next */ +const create = s => new Error(s); + +/** + * @throws {Error} + * @return {never} + */ +/* c8 ignore next 3 */ +const methodUnimplemented = () => { + throw create('Method unimplemented') +}; + +/** + * @throws {Error} + * @return {never} + */ +/* c8 ignore next 3 */ +const unexpectedCase = () => { + throw create('Unexpected case') +}; + +var error = /*#__PURE__*/Object.freeze({ + __proto__: null, + create: create, + methodUnimplemented: methodUnimplemented, + unexpectedCase: unexpectedCase +}); + +exports.create = create; +exports.error = error; +exports.methodUnimplemented = methodUnimplemented; +exports.unexpectedCase = unexpectedCase; +//# sourceMappingURL=error-8582d695.cjs.map diff --git a/nodejs/node_modules/lib0/dist/error-8582d695.cjs.map b/nodejs/node_modules/lib0/dist/error-8582d695.cjs.map new file mode 100644 index 00000000..6a5142fc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/error-8582d695.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"error-8582d695.cjs","sources":["../error.js"],"sourcesContent":["/**\n * Error helpers.\n *\n * @module error\n */\n\n/**\n * @param {string} s\n * @return {Error}\n */\n/* c8 ignore next */\nexport const create = s => new Error(s)\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const methodUnimplemented = () => {\n throw create('Method unimplemented')\n}\n\n/**\n * @throws {Error}\n * @return {never}\n */\n/* c8 ignore next 3 */\nexport const unexpectedCase = () => {\n throw create('Unexpected case')\n}\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,EAAC;AACvC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,mBAAmB,GAAG,MAAM;AACzC,EAAE,MAAM,MAAM,CAAC,sBAAsB,CAAC;AACtC,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,MAAM;AACpC,EAAE,MAAM,MAAM,CAAC,iBAAiB,CAAC;AACjC;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/error.cjs b/nodejs/node_modules/lib0/dist/error.cjs new file mode 100644 index 00000000..d738ebd4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/error.cjs @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var error = require('./error-8582d695.cjs'); + + + +exports.create = error.create; +exports.methodUnimplemented = error.methodUnimplemented; +exports.unexpectedCase = error.unexpectedCase; +//# sourceMappingURL=error.cjs.map diff --git a/nodejs/node_modules/lib0/dist/error.cjs.map b/nodejs/node_modules/lib0/dist/error.cjs.map new file mode 100644 index 00000000..9cec587e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/error.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"error.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/error.d.ts b/nodejs/node_modules/lib0/dist/error.d.ts new file mode 100644 index 00000000..9580d419 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/error.d.ts @@ -0,0 +1,4 @@ +export function create(s: string): Error; +export function methodUnimplemented(): never; +export function unexpectedCase(): never; +//# sourceMappingURL=error.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/error.d.ts.map b/nodejs/node_modules/lib0/dist/error.d.ts.map new file mode 100644 index 00000000..fedd819f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../error.js"],"names":[],"mappings":"AAWO,0BAJI,MAAM,GACL,KAAK,CAGsB;AAOhC,uCAHK,KAAK,CAKhB;AAOM,kCAHK,KAAK,CAKhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/eventloop-d0571621.cjs b/nodejs/node_modules/lib0/dist/eventloop-d0571621.cjs new file mode 100644 index 00000000..2a77acec --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop-d0571621.cjs @@ -0,0 +1,129 @@ +'use strict'; + +/* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */ + +/** + * Utility module to work with EcmaScript's event loop. + * + * @module eventloop + */ + +/** + * @type {Array} + */ +let queue = []; + +const _runQueue = () => { + for (let i = 0; i < queue.length; i++) { + queue[i](); + } + queue = []; +}; + +/** + * @param {function():void} f + */ +const enqueue = f => { + queue.push(f); + if (queue.length === 1) { + setTimeout(_runQueue, 0); + } +}; + +/** + * @typedef {Object} TimeoutObject + * @property {function} TimeoutObject.destroy + */ + +/** + * @param {function(number):void} clearFunction + */ +const createTimeoutClass = clearFunction => class TT { + /** + * @param {number} timeoutId + */ + constructor (timeoutId) { + this._ = timeoutId; + } + + destroy () { + clearFunction(this._); + } +}; + +const Timeout = createTimeoutClass(clearTimeout); + +/** + * @param {number} timeout + * @param {function} callback + * @return {TimeoutObject} + */ +const timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout)); + +const Interval = createTimeoutClass(clearInterval); + +/** + * @param {number} timeout + * @param {function} callback + * @return {TimeoutObject} + */ +const interval = (timeout, callback) => new Interval(setInterval(callback, timeout)); + +/* c8 ignore next */ +const Animation = createTimeoutClass(arg => typeof requestAnimationFrame !== 'undefined' && cancelAnimationFrame(arg)); + +/** + * @param {function(number):void} cb + * @return {TimeoutObject} + */ +/* c8 ignore next */ +const animationFrame = cb => typeof requestAnimationFrame === 'undefined' ? timeout(0, cb) : new Animation(requestAnimationFrame(cb)); + +/* c8 ignore next */ +// @ts-ignore +const Idle = createTimeoutClass(arg => typeof cancelIdleCallback !== 'undefined' && cancelIdleCallback(arg)); + +/** + * Note: this is experimental and is probably only useful in browsers. + * + * @param {function} cb + * @return {TimeoutObject} + */ +/* c8 ignore next 2 */ +// @ts-ignore +const idleCallback = cb => typeof requestIdleCallback !== 'undefined' ? new Idle(requestIdleCallback(cb)) : timeout(1000, cb); + +/** + * @param {number} timeout Timeout of the debounce action + * @return {function(function():void):void} + */ +const createDebouncer = timeout => { + let timer = -1; + return f => { + clearTimeout(timer); + if (f) { + timer = /** @type {any} */ (setTimeout(f, timeout)); + } + } +}; + +var eventloop = /*#__PURE__*/Object.freeze({ + __proto__: null, + enqueue: enqueue, + timeout: timeout, + interval: interval, + Animation: Animation, + animationFrame: animationFrame, + idleCallback: idleCallback, + createDebouncer: createDebouncer +}); + +exports.Animation = Animation; +exports.animationFrame = animationFrame; +exports.createDebouncer = createDebouncer; +exports.enqueue = enqueue; +exports.eventloop = eventloop; +exports.idleCallback = idleCallback; +exports.interval = interval; +exports.timeout = timeout; +//# sourceMappingURL=eventloop-d0571621.cjs.map diff --git a/nodejs/node_modules/lib0/dist/eventloop-d0571621.cjs.map b/nodejs/node_modules/lib0/dist/eventloop-d0571621.cjs.map new file mode 100644 index 00000000..7ca07735 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop-d0571621.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"eventloop-d0571621.cjs","sources":["../eventloop.js"],"sourcesContent":["/* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */\n\n/**\n * Utility module to work with EcmaScript's event loop.\n *\n * @module eventloop\n */\n\n/**\n * @type {Array}\n */\nlet queue = []\n\nconst _runQueue = () => {\n for (let i = 0; i < queue.length; i++) {\n queue[i]()\n }\n queue = []\n}\n\n/**\n * @param {function():void} f\n */\nexport const enqueue = f => {\n queue.push(f)\n if (queue.length === 1) {\n setTimeout(_runQueue, 0)\n }\n}\n\n/**\n * @typedef {Object} TimeoutObject\n * @property {function} TimeoutObject.destroy\n */\n\n/**\n * @param {function(number):void} clearFunction\n */\nconst createTimeoutClass = clearFunction => class TT {\n /**\n * @param {number} timeoutId\n */\n constructor (timeoutId) {\n this._ = timeoutId\n }\n\n destroy () {\n clearFunction(this._)\n }\n}\n\nconst Timeout = createTimeoutClass(clearTimeout)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nexport const timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout))\n\nconst Interval = createTimeoutClass(clearInterval)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nexport const interval = (timeout, callback) => new Interval(setInterval(callback, timeout))\n\n/* c8 ignore next */\nexport const Animation = createTimeoutClass(arg => typeof requestAnimationFrame !== 'undefined' && cancelAnimationFrame(arg))\n\n/**\n * @param {function(number):void} cb\n * @return {TimeoutObject}\n */\n/* c8 ignore next */\nexport const animationFrame = cb => typeof requestAnimationFrame === 'undefined' ? timeout(0, cb) : new Animation(requestAnimationFrame(cb))\n\n/* c8 ignore next */\n// @ts-ignore\nconst Idle = createTimeoutClass(arg => typeof cancelIdleCallback !== 'undefined' && cancelIdleCallback(arg))\n\n/**\n * Note: this is experimental and is probably only useful in browsers.\n *\n * @param {function} cb\n * @return {TimeoutObject}\n */\n/* c8 ignore next 2 */\n// @ts-ignore\nexport const idleCallback = cb => typeof requestIdleCallback !== 'undefined' ? new Idle(requestIdleCallback(cb)) : timeout(1000, cb)\n\n/**\n * @param {number} timeout Timeout of the debounce action\n * @return {function(function():void):void}\n */\nexport const createDebouncer = timeout => {\n let timer = -1\n return f => {\n clearTimeout(timer)\n if (f) {\n timer = /** @type {any} */ (setTimeout(f, timeout))\n }\n }\n}\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,KAAK,GAAG,GAAE;AACd;AACA,MAAM,SAAS,GAAG,MAAM;AACxB,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACzC,IAAI,KAAK,CAAC,CAAC,CAAC,GAAE;AACd,GAAG;AACH,EAAE,KAAK,GAAG,GAAE;AACZ,EAAC;AACD;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,IAAI;AAC5B,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,EAAC;AACf,EAAE,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;AAC1B,IAAI,UAAU,CAAC,SAAS,EAAE,CAAC,EAAC;AAC5B,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;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O,mBAAmB,KAAK,WAAW,GAAG,IAAI,IAAI,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,EAAE,EAAC;AACpI;AACA;AACA;AACA;AACA;AACY,MAAC,eAAe,GAAG,OAAO,IAAI;AAC1C,EAAE,IAAI,KAAK,GAAG,CAAC,EAAC;AAChB,EAAE,OAAO,CAAC,IAAI;AACd,IAAI,YAAY,CAAC,KAAK,EAAC;AACvB,IAAI,IAAI,CAAC,EAAE;AACX,MAAM,KAAK,uBAAuB,UAAU,CAAC,CAAC,EAAE,OAAO,CAAC,EAAC;AACzD,KAAK;AACL,GAAG;AACH;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/eventloop.cjs b/nodejs/node_modules/lib0/dist/eventloop.cjs new file mode 100644 index 00000000..907f90f8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop.cjs @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var eventloop = require('./eventloop-d0571621.cjs'); + + + +exports.Animation = eventloop.Animation; +exports.animationFrame = eventloop.animationFrame; +exports.createDebouncer = eventloop.createDebouncer; +exports.enqueue = eventloop.enqueue; +exports.idleCallback = eventloop.idleCallback; +exports.interval = eventloop.interval; +exports.timeout = eventloop.timeout; +//# sourceMappingURL=eventloop.cjs.map diff --git a/nodejs/node_modules/lib0/dist/eventloop.cjs.map b/nodejs/node_modules/lib0/dist/eventloop.cjs.map new file mode 100644 index 00000000..bd9aca12 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"eventloop.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/eventloop.d.ts b/nodejs/node_modules/lib0/dist/eventloop.d.ts new file mode 100644 index 00000000..3e704d37 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop.d.ts @@ -0,0 +1,16 @@ +export function enqueue(f: () => void): void; +export function timeout(timeout: number, callback: Function): TimeoutObject; +export function interval(timeout: number, callback: Function): TimeoutObject; +export const Animation: { + new (timeoutId: number): { + _: number; + destroy(): void; + }; +}; +export function animationFrame(cb: (arg0: number) => void): TimeoutObject; +export function idleCallback(cb: Function): TimeoutObject; +export function createDebouncer(timeout: number): (arg0: () => void) => void; +export type TimeoutObject = { + destroy: Function; +}; +//# sourceMappingURL=eventloop.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/eventloop.d.ts.map b/nodejs/node_modules/lib0/dist/eventloop.d.ts.map new file mode 100644 index 00000000..9a4d98db --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eventloop.d.ts","sourceRoot":"","sources":["../eventloop.js"],"names":[],"mappings":"AAuBO,iCAFe,IAAI,QAOzB;AA8BM,iCAJI,MAAM,uBAEL,aAAa,CAE+D;AASjF,kCAJI,MAAM,uBAEL,aAAa,CAEkE;AAG3F;oBA9Ba,MAAM;;;;EA8B0G;AAOtH,0CAJa,MAAM,KAAE,IAAI,GACpB,aAAa,CAGmH;AAcrI,4CAJK,aAAa,CAI2G;AAM7H,yCAHI,MAAM,gBACe,IAAI,KAAE,IAAI,CAUzC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/eventloop.test.d.ts b/nodejs/node_modules/lib0/dist/eventloop.test.d.ts new file mode 100644 index 00000000..27f4ab96 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop.test.d.ts @@ -0,0 +1,8 @@ +export function testEventloopOrder(_tc: t.TestCase): Promise<[void, void]>; +export function testTimeout(_tc: t.TestCase): Promise; +export function testInterval(_tc: t.TestCase): Promise; +export function testAnimationFrame(_tc: t.TestCase): Promise; +export function testIdleCallback(_tc: t.TestCase): Promise; +export function testDebouncer(_tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=eventloop.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/eventloop.test.d.ts.map b/nodejs/node_modules/lib0/dist/eventloop.test.d.ts.map new file mode 100644 index 00000000..1a63a994 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/eventloop.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eventloop.test.d.ts","sourceRoot":"","sources":["../eventloop.test.js"],"names":[],"mappings":"AAOO,wCAFI,EAAE,QAAQ,yBAkBpB;AAKM,iCAFI,EAAE,QAAQ,iBAYpB;AAKM,kCAFI,EAAE,QAAQ,iBAepB;AAKM,wCAFI,EAAE,QAAQ,iBAOpB;AAKM,sCAFI,EAAE,QAAQ,iBAMpB;AAKM,mCAFI,EAAE,QAAQ,iBAcpB;mBA3FkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/function-314fdc56.cjs b/nodejs/node_modules/lib0/dist/function-314fdc56.cjs new file mode 100644 index 00000000..ed3d92f4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function-314fdc56.cjs @@ -0,0 +1,221 @@ +'use strict'; + +var array = require('./array-704ca50e.cjs'); +var object = require('./object-fecf6a7b.cjs'); + +/** + * Common functions and function call helpers. + * + * @module function + */ + +/** + * Calls all functions in `fs` with args. Only throws after all functions were called. + * + * @param {Array} fs + * @param {Array} args + */ +const callAll = (fs, args, i = 0) => { + try { + for (; i < fs.length; i++) { + fs[i](...args); + } + } finally { + if (i < fs.length) { + callAll(fs, args, i + 1); + } + } +}; + +const nop = () => {}; + +/** + * @template T + * @param {function():T} f + * @return {T} + */ +const apply = f => f(); + +/** + * @template A + * + * @param {A} a + * @return {A} + */ +const id = a => a; + +/** + * @template T + * + * @param {T} a + * @param {T} b + * @return {boolean} + */ +const equalityStrict = (a, b) => a === b; + +/** + * @template T + * + * @param {Array|object} a + * @param {Array|object} b + * @return {boolean} + */ +const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b)))); + +/* c8 ignore start */ + +/** + * @param {any} a + * @param {any} b + * @return {boolean} + */ +const equalityDeep = (a, b) => { + if (a == null || b == null) { + return equalityStrict(a, b) + } + if (a.constructor !== b.constructor) { + return false + } + if (a === b) { + return true + } + switch (a.constructor) { + case ArrayBuffer: + a = new Uint8Array(a); + b = new Uint8Array(b); + // eslint-disable-next-line no-fallthrough + case Uint8Array: { + if (a.byteLength !== b.byteLength) { + return false + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false + } + } + break + } + case Set: { + if (a.size !== b.size) { + return false + } + for (const value of a) { + if (!b.has(value)) { + return false + } + } + break + } + case Map: { + if (a.size !== b.size) { + return false + } + for (const key of a.keys()) { + if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) { + return false + } + } + break + } + case Object: + if (object.length(a) !== object.length(b)) { + return false + } + for (const key in a) { + if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) { + return false + } + } + break + case Array: + if (a.length !== b.length) { + return false + } + for (let i = 0; i < a.length; i++) { + if (!equalityDeep(a[i], b[i])) { + return false + } + } + break + default: + return false + } + return true +}; + +/** + * @template V + * @template {V} OPTS + * + * @param {V} value + * @param {Array} options + */ +// @ts-ignore +const isOneOf = (value, options) => options.includes(value); +/* c8 ignore stop */ + +const isArray = array.isArray; + +/** + * @param {any} s + * @return {s is String} + */ +const isString = (s) => s && s.constructor === String; + +/** + * @param {any} n + * @return {n is Number} + */ +const isNumber = n => n != null && n.constructor === Number; + +/** + * @template {abstract new (...args: any) => any} TYPE + * @param {any} n + * @param {TYPE} T + * @return {n is InstanceType} + */ +const is = (n, T) => n && n.constructor === T; + +/** + * @template {abstract new (...args: any) => any} TYPE + * @param {TYPE} T + */ +const isTemplate = (T) => + /** + * @param {any} n + * @return {n is InstanceType} + **/ + n => n && n.constructor === T; + +var _function = /*#__PURE__*/Object.freeze({ + __proto__: null, + callAll: callAll, + nop: nop, + apply: apply, + id: id, + equalityStrict: equalityStrict, + equalityFlat: equalityFlat, + equalityDeep: equalityDeep, + isOneOf: isOneOf, + isArray: isArray, + isString: isString, + isNumber: isNumber, + is: is, + isTemplate: isTemplate +}); + +exports._function = _function; +exports.apply = apply; +exports.callAll = callAll; +exports.equalityDeep = equalityDeep; +exports.equalityFlat = equalityFlat; +exports.equalityStrict = equalityStrict; +exports.id = id; +exports.is = is; +exports.isArray = isArray; +exports.isNumber = isNumber; +exports.isOneOf = isOneOf; +exports.isString = isString; +exports.isTemplate = isTemplate; +exports.nop = nop; +//# sourceMappingURL=function-314fdc56.cjs.map diff --git a/nodejs/node_modules/lib0/dist/function-314fdc56.cjs.map b/nodejs/node_modules/lib0/dist/function-314fdc56.cjs.map new file mode 100644 index 00000000..5aee1a18 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function-314fdc56.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"function-314fdc56.cjs","sources":["../function.js"],"sourcesContent":["/**\n * Common functions and function call helpers.\n *\n * @module function\n */\n\nimport * as array from './array.js'\nimport * as object from './object.js'\n\n/**\n * Calls all functions in `fs` with args. Only throws after all functions were called.\n *\n * @param {Array} fs\n * @param {Array} args\n */\nexport const callAll = (fs, args, i = 0) => {\n try {\n for (; i < fs.length; i++) {\n fs[i](...args)\n }\n } finally {\n if (i < fs.length) {\n callAll(fs, args, i + 1)\n }\n }\n}\n\nexport const nop = () => {}\n\n/**\n * @template T\n * @param {function():T} f\n * @return {T}\n */\nexport const apply = f => f()\n\n/**\n * @template A\n *\n * @param {A} a\n * @return {A}\n */\nexport const id = a => a\n\n/**\n * @template T\n *\n * @param {T} a\n * @param {T} b\n * @return {boolean}\n */\nexport const equalityStrict = (a, b) => a === b\n\n/**\n * @template T\n *\n * @param {Array|object} a\n * @param {Array|object} b\n * @return {boolean}\n */\nexport const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b))))\n\n/* c8 ignore start */\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nexport const equalityDeep = (a, b) => {\n if (a == null || b == null) {\n return equalityStrict(a, b)\n }\n if (a.constructor !== b.constructor) {\n return false\n }\n if (a === b) {\n return true\n }\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n return false\n }\n for (const value of a) {\n if (!b.has(value)) {\n return false\n }\n }\n break\n }\n case Map: {\n if (a.size !== b.size) {\n return false\n }\n for (const key of a.keys()) {\n if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {\n return false\n }\n }\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n return false\n }\n for (const key in a) {\n if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) {\n return false\n }\n }\n break\n case Array:\n if (a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!equalityDeep(a[i], b[i])) {\n return false\n }\n }\n break\n default:\n return false\n }\n return true\n}\n\n/**\n * @template V\n * @template {V} OPTS\n *\n * @param {V} value\n * @param {Array} options\n */\n// @ts-ignore\nexport const isOneOf = (value, options) => options.includes(value)\n/* c8 ignore stop */\n\nexport const isArray = array.isArray\n\n/**\n * @param {any} s\n * @return {s is String}\n */\nexport const isString = (s) => s && s.constructor === String\n\n/**\n * @param {any} n\n * @return {n is Number}\n */\nexport const isNumber = n => n != null && n.constructor === Number\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {any} n\n * @param {TYPE} T\n * @return {n is InstanceType}\n */\nexport const is = (n, T) => n && n.constructor === T\n\n/**\n * @template {abstract new (...args: any) => any} TYPE\n * @param {TYPE} T\n */\nexport const isTemplate = (T) =>\n /**\n * @param {any} n\n * @return {n is InstanceType}\n **/\n n => n && n.constructor === T\n"],"names":["array.isArray","array.equalFlat","object.equalFlat","object.length","object.hasProperty"],"mappings":";;;;;AAAA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK;AAC5C,EAAE,IAAI;AACN,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC/B,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,EAAC;AACpB,KAAK;AACL,GAAG,SAAS;AACZ,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE;AACvB,MAAM,OAAO,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,EAAC;AAC9B,KAAK;AACL,GAAG;AACH,EAAC;AACD;AACY,MAAC,GAAG,GAAG,MAAM,GAAE;AAC3B;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,CAAC,IAAI,CAAC,GAAE;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,EAAE,GAAG,CAAC,IAAI,EAAC;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,KAAK,EAAC;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,YAAY,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,WAAW,KAAK,CAAC,CAAC,WAAW,KAAK,CAACA,aAAa,CAAC,CAAC,CAAC,IAAIC,eAAe,CAAC,CAAC,2BAA2B,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AAC,EAAE,EAAE;AACzC,QAAQ,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE;AACvC,UAAU,OAAO,KAAK;AACtB,SAAS;AACT,OAAO;AACP,MAAM,KAAK;AACX,IAAI;AACJ,MAAM,OAAO,KAAK;AAClB,GAAG;AACH,EAAE,OAAO,IAAI;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAC;AAClE;AACA;AACY,MAAC,OAAO,GAAGJ,cAAa;AACpC;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,KAAK,OAAM;AAC5D;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,WAAW,KAAK,OAAM;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,KAAK,EAAC;AACpD;AACA;AACA;AACA;AACA;AACY,MAAC,UAAU,GAAG,CAAC,CAAC;AAC5B;AACA;AACA;AACA;AACA,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,WAAW,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/function.cjs b/nodejs/node_modules/lib0/dist/function.cjs new file mode 100644 index 00000000..5ce8cbe6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function.cjs @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./array-704ca50e.cjs'); +require('./object-fecf6a7b.cjs'); +var _function = require('./function-314fdc56.cjs'); +require('./set-0f209abb.cjs'); + + + +exports.apply = _function.apply; +exports.callAll = _function.callAll; +exports.equalityDeep = _function.equalityDeep; +exports.equalityFlat = _function.equalityFlat; +exports.equalityStrict = _function.equalityStrict; +exports.id = _function.id; +exports.is = _function.is; +exports.isArray = _function.isArray; +exports.isNumber = _function.isNumber; +exports.isOneOf = _function.isOneOf; +exports.isString = _function.isString; +exports.isTemplate = _function.isTemplate; +exports.nop = _function.nop; +//# sourceMappingURL=function.cjs.map diff --git a/nodejs/node_modules/lib0/dist/function.cjs.map b/nodejs/node_modules/lib0/dist/function.cjs.map new file mode 100644 index 00000000..87fa2afe --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"function.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/function.d.ts b/nodejs/node_modules/lib0/dist/function.d.ts new file mode 100644 index 00000000..bf9af1ee --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function.d.ts @@ -0,0 +1,14 @@ +export function callAll(fs: Array, args: Array, i?: number): void; +export function nop(): void; +export function apply(f: () => T): T; +export function id
(a: A): A; +export function equalityStrict(a: T, b: T): boolean; +export function equalityFlat(a: object | T[], b: object | T[]): boolean; +export function equalityDeep(a: any, b: any): boolean; +export function isOneOf(value: V, options: OPTS[]): boolean; +export const isArray: (arg: any) => arg is any[]; +export function isString(s: any): s is string; +export function isNumber(n: any): n is number; +export function is any>(n: any, T: TYPE): n is InstanceType; +export function isTemplate any>(T: TYPE): (n: any) => n is InstanceType; +//# sourceMappingURL=function.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/function.d.ts.map b/nodejs/node_modules/lib0/dist/function.d.ts.map new file mode 100644 index 00000000..855f6bad --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"function.d.ts","sourceRoot":"","sources":["../function.js"],"names":[],"mappings":"AAeO,4BAHI,eAAe,QACf,MAAM,GAAG,CAAC,oBAYpB;AAEM,4BAAoB;AAOpB,wCAAsB;AAQtB,+BAAiB;AASjB,+CAFK,OAAO,CAE4B;AASxC,mEAFK,OAAO,CAEyN;AASrO,gCAJI,GAAG,KACH,GAAG,GACF,OAAO,CA0ElB;AAUM,+EAA2D;AAGlE,iDAAoC;AAM7B,4BAHI,GAAG,eAG8C;AAMrD,4BAHI,GAAG,eAGoD;AAQ3D,uDAL8B,GAAG,KAAK,GAAG,KACrC,GAAG,oCAIsC;AAM7C,+DAH8B,GAAG,KAAK,GAAG,gBAKnC,GAAG,6BAGe"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/function.test.d.ts b/nodejs/node_modules/lib0/dist/function.test.d.ts new file mode 100644 index 00000000..8d7b2775 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function.test.d.ts @@ -0,0 +1,5 @@ +export function testBasics(_tc: t.TestCase): void; +export function testCallAll(_tc: t.TestCase): void; +export function testDeepEquality(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=function.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/function.test.d.ts.map b/nodejs/node_modules/lib0/dist/function.test.d.ts.map new file mode 100644 index 00000000..1483a646 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/function.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"function.test.d.ts","sourceRoot":"","sources":["../function.test.js"],"names":[],"mappings":"AAMO,gCAFI,EAAE,QAAQ,QA+CpB;AAKM,iCAFI,EAAE,QAAQ,QAuBpB;AAKM,sCAFI,EAAE,QAAQ,QAkEpB;mBAjJkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin-gf2-polynomial.d.ts b/nodejs/node_modules/lib0/dist/hash/rabin-gf2-polynomial.d.ts new file mode 100644 index 00000000..fa8f26c1 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin-gf2-polynomial.d.ts @@ -0,0 +1,45 @@ +/** + * This is a GF2 Polynomial abstraction that is not meant for production! + * + * It is easy to understand and it's correctness is as obvious as possible. It can be used to verify + * efficient implementations of algorithms on GF2. + */ +export class GF2Polynomial { + /** + * @type {Set} + */ + degrees: Set; +} +export function createFromBytes(bytes: Uint8Array): GF2Polynomial; +export function toUint8Array(p: GF2Polynomial, byteLength?: number): Uint8Array; +export function createFromUint(uint: number): GF2Polynomial; +export function createRandom(degree: number): GF2Polynomial; +export function getHighestDegree(p: GF2Polynomial): number; +export function addInto(p1: GF2Polynomial, p2: GF2Polynomial): void; +export function orInto(p1: GF2Polynomial, p2: GF2Polynomial): void; +export function add(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function clone(p: GF2Polynomial): GF2Polynomial; +export function addDegreeInto(p: GF2Polynomial, degree: number): void; +export function multiply(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function shiftLeft(p: GF2Polynomial, shift: number): GF2Polynomial; +export function mod(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function modPow(p: GF2Polynomial, e: number, m: GF2Polynomial): GF2Polynomial; +export function gcd(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function equals(p1: GF2Polynomial, p2: GF2Polynomial): boolean; +export function isIrreducibleBenOr(p: GF2Polynomial): boolean; +export function createIrreducible(degree: number): GF2Polynomial; +export function fingerprint(buf: Uint8Array, m: GF2Polynomial): Uint8Array; +export class RabinPolynomialEncoder { + /** + * @param {GF2Polynomial} m The irreducible polynomial + */ + constructor(m: GF2Polynomial); + fingerprint: GF2Polynomial; + m: GF2Polynomial; + /** + * @param {number} b + */ + write(b: number): void; + getFingerprint(): Uint8Array; +} +//# sourceMappingURL=rabin-gf2-polynomial.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin-gf2-polynomial.d.ts.map b/nodejs/node_modules/lib0/dist/hash/rabin-gf2-polynomial.d.ts.map new file mode 100644 index 00000000..27352160 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin-gf2-polynomial.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin-gf2-polynomial.d.ts","sourceRoot":"","sources":["../../hash/rabin-gf2-polynomial.js"],"names":[],"mappings":"AAqBA;;;;;GAKG;AACH;IAEI;;QAEI;IACJ,SAFW,IAAI,MAAM,CAAC,CAEE;CAE3B;AAOM,uCAFI,UAAU,iBAcpB;AAQM,gCAHI,aAAa,eACb,MAAM,cAahB;AAOM,qCAFI,MAAM,iBAQhB;AAOM,qCAFI,MAAM,iBAYhB;AAMM,oCAHI,aAAa,UAG2D;AAU5E,4BAHI,aAAa,MACb,aAAa,QAUvB;AAUM,2BAHI,aAAa,MACb,aAAa,QAMvB;AAUM,wBAHI,aAAa,MACb,aAAa,iBAevB;AASM,yBAFI,aAAa,iBAMvB;AAUM,iCAHI,aAAa,UACb,MAAM,QAQhB;AAQM,6BAHI,aAAa,MACb,aAAa,iBAUvB;AAQM,6BAHI,aAAa,SACb,MAAM,iBAShB;AAQM,wBAHI,aAAa,MACb,aAAa,iBAavB;AAWM,0BAJI,aAAa,KACb,MAAM,KACN,aAAa,iBAcvB;AAQM,wBAHI,aAAa,MACb,aAAa,iBASvB;AAQM,2BAHI,aAAa,MACb,aAAa,WAQvB;AAgCM,sCAFI,aAAa,WAYvB;AAKM,0CAFI,MAAM,iBAOhB;AAQM,iCAHI,UAAU,KACV,aAAa,cAE0G;AAElI;IACE;;OAEG;IACH,eAFW,aAAa,EAKvB;IAFC,2BAAsC;IACtC,iBAAU;IAGZ;;OAEG;IACH,SAFW,MAAM,QAOhB;IAED,6BAEC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin-uncached.d.ts b/nodejs/node_modules/lib0/dist/hash/rabin-uncached.d.ts new file mode 100644 index 00000000..89e5dac0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin-uncached.d.ts @@ -0,0 +1,29 @@ +export class RabinUncachedEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor(m: Uint8Array); + m: Uint8Array; + blen: number; + bs: Uint8Array; + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + bpos: number; + /** + * Add/Xor/Substract bytes. + * + * Discards bytes that are out of range. + * @todo put this in function or inline + * + * @param {Uint8Array} cs + */ + add(cs: Uint8Array): void; + /** + * @param {number} byte + */ + write(byte: number): void; + getFingerprint(): Uint8Array; +} +//# sourceMappingURL=rabin-uncached.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin-uncached.d.ts.map b/nodejs/node_modules/lib0/dist/hash/rabin-uncached.d.ts.map new file mode 100644 index 00000000..b154bf72 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin-uncached.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin-uncached.d.ts","sourceRoot":"","sources":["../../hash/rabin-uncached.js"],"names":[],"mappings":"AAUA;IACE;;OAEG;IACH,eAFW,UAAU,EAWpB;IARC,cAAU;IACV,aAAwB;IACxB,eAAmC;IACnC;;;OAGG;IACH,aAAa;IAGf;;;;;;;OAOG;IACH,QAFW,UAAU,QAQpB;IAED;;OAEG;IACH,YAFW,MAAM,QAgBhB;IAED,6BAMC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin.d.ts b/nodejs/node_modules/lib0/dist/hash/rabin.d.ts new file mode 100644 index 00000000..3e1f578d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin.d.ts @@ -0,0 +1,27 @@ +export const StandardIrreducible8: Uint8Array; +export const StandardIrreducible16: Uint8Array; +export const StandardIrreducible32: Uint8Array; +export const StandardIrreducible64: Uint8Array; +export const StandardIrreducible128: Uint8Array; +export class RabinEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor(m: Uint8Array); + m: Uint8Array; + blen: number; + bs: Uint8Array; + cache: Uint8Array; + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + bpos: number; + /** + * @param {number} byte + */ + write(byte: number): void; + getFingerprint(): Uint8Array; +} +export function fingerprint(irreducible: Uint8Array, data: Uint8Array): Uint8Array; +//# sourceMappingURL=rabin.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin.d.ts.map b/nodejs/node_modules/lib0/dist/hash/rabin.d.ts.map new file mode 100644 index 00000000..eb2dfd1f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin.d.ts","sourceRoot":"","sources":["../../hash/rabin.js"],"names":[],"mappings":"AAUA,8CAA4D;AAC5D,+CAAkE;AAClE,+CAA4E;AAC5E,+CAA+F;AAC/F,gDAAmI;AAmCnI;IACE;;OAEG;IACH,eAFW,UAAU,EAYpB;IATC,cAAU;IACV,aAAwB;IACxB,eAAmC;IACnC,kBAA2B;IAC3B;;;OAGG;IACH,aAAa;IAGf;;OAEG;IACH,YAFW,MAAM,QAYhB;IAED,6BAMC;CACF;AAMM,yCAHI,UAAU,QACV,UAAU,cAQpB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin.test.d.ts b/nodejs/node_modules/lib0/dist/hash/rabin.test.d.ts new file mode 100644 index 00000000..6ed6dd5c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin.test.d.ts @@ -0,0 +1,8 @@ +export function testPolynomialBasics(_tc: t.TestCase): void; +export function testIrreducibleInput(_tc: t.TestCase): void; +export function testIrreducibleSpread(_tc: t.TestCase): void; +export function testGenerateIrreducibles(_tc: t.TestCase): void; +export function testFingerprintCompatiblity(tc: t.TestCase): void; +export function testConflicts(tc: t.TestCase): void; +import * as t from '../testing.js'; +//# sourceMappingURL=rabin.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/rabin.test.d.ts.map b/nodejs/node_modules/lib0/dist/hash/rabin.test.d.ts.map new file mode 100644 index 00000000..07e48d82 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/rabin.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin.test.d.ts","sourceRoot":"","sources":["../../hash/rabin.test.js"],"names":[],"mappings":"AAaO,0CAFI,EAAE,QAAQ,QASpB;AAKM,0CAFI,EAAE,QAAQ,QAapB;AAKM,2CAFI,EAAE,QAAQ,QASpB;AAwBM,8CAFI,EAAE,QAAQ,QAyBpB;AAmGM,gDAFI,EAAE,QAAQ,QAQpB;AAKM,kCAFI,EAAE,QAAQ,QA4BpB;mBAvOkB,eAAe"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/sha256.d.ts b/nodejs/node_modules/lib0/dist/hash/sha256.d.ts new file mode 100644 index 00000000..462cb008 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/sha256.d.ts @@ -0,0 +1,2 @@ +export function digest(data: Uint8Array): Uint8Array; +//# sourceMappingURL=sha256.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/sha256.d.ts.map b/nodejs/node_modules/lib0/dist/hash/sha256.d.ts.map new file mode 100644 index 00000000..35f39cd4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/sha256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.d.ts","sourceRoot":"","sources":["../../hash/sha256.js"],"names":[],"mappings":"AA2KO,6BAFI,UAAU,cAEkC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/sha256.node.d.ts b/nodejs/node_modules/lib0/dist/hash/sha256.node.d.ts new file mode 100644 index 00000000..4046b5eb --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/sha256.node.d.ts @@ -0,0 +1,2 @@ +export function digest(data: Uint8Array): Buffer; +//# sourceMappingURL=sha256.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/sha256.node.d.ts.map b/nodejs/node_modules/lib0/dist/hash/sha256.node.d.ts.map new file mode 100644 index 00000000..d1e14cb0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/sha256.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.node.d.ts","sourceRoot":"","sources":["../../hash/sha256.node.js"],"names":[],"mappings":"AAKO,6BAFI,UAAU,UAMpB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/sha256.test.d.ts b/nodejs/node_modules/lib0/dist/hash/sha256.test.d.ts new file mode 100644 index 00000000..39fc5381 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/sha256.test.d.ts @@ -0,0 +1,7 @@ +export function testSelfReferencingHash(_tc: t.TestCase): void; +export function testSha256Basics(_tc: t.TestCase): Promise; +export function testLargeValue(_tc: t.TestCase): Promise; +export function testRepeatSha256Hashing(tc: t.TestCase): Promise; +export function testBenchmarkSha256(_tc: t.TestCase): Promise; +import * as t from '../testing.js'; +//# sourceMappingURL=sha256.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/hash/sha256.test.d.ts.map b/nodejs/node_modules/lib0/dist/hash/sha256.test.d.ts.map new file mode 100644 index 00000000..54607767 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/hash/sha256.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.test.d.ts","sourceRoot":"","sources":["../../hash/sha256.test.js"],"names":[],"mappings":"AAcO,6CAFI,EAAE,QAAQ,QAKpB;AAKM,sCAFI,EAAE,QAAQ,iBA2BpB;AAOM,oCAFI,EAAE,QAAQ,iBA4BpB;AAKM,4CAFI,EAAE,QAAQ,iBAQpB;AAKM,yCAFI,EAAE,QAAQ,iBAmDpB;mBAjJkB,eAAe"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/index.cjs b/nodejs/node_modules/lib0/dist/index.cjs new file mode 100644 index 00000000..3bb69f76 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/index.cjs @@ -0,0 +1,97 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var array = require('./array-704ca50e.cjs'); +var binary = require('./binary-ac8e39e2.cjs'); +var broadcastchannel = require('./broadcastchannel-80813eea.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); +var conditions = require('./conditions-f5c0c102.cjs'); +var decoding = require('./decoding-000d097f.cjs'); +var diff = require('./diff-fbaa426b.cjs'); +var dom = require('./dom-16daf1a0.cjs'); +var encoding = require('./encoding-882cb136.cjs'); +var environment = require('./environment-f4d7c3e5.cjs'); +var error = require('./error-8582d695.cjs'); +var eventloop = require('./eventloop-d0571621.cjs'); +var _function = require('./function-314fdc56.cjs'); +var indexeddb = require('./indexeddb-8d495848.cjs'); +var iterator = require('./iterator-9fc627c1.cjs'); +var json = require('./json-092190a1.cjs'); +var log = require('lib0/logging'); +var map = require('./map-0dabcc55.cjs'); +var math = require('./math-08e068f9.cjs'); +var mutex = require('./mutex-63f09c81.cjs'); +var number = require('./number-466d8922.cjs'); +var object = require('./object-fecf6a7b.cjs'); +var pair = require('./pair-ab022bc3.cjs'); +var prng = require('./prng-e4f28259.cjs'); +var promise = require('./promise-afe9dfc3.cjs'); +var set = require('./set-0f209abb.cjs'); +var sort = require('./sort-b8702761.cjs'); +var statistics = require('./statistics-c2316dca.cjs'); +var string = require('./string-6d104757.cjs'); +var symbol = require('./symbol-c5caa724.cjs'); +var time = require('./time-bc2081b9.cjs'); +var tree = require('./tree-9f3c8837.cjs'); +var websocket = require('./websocket-d9e16a69.cjs'); +require('./storage.cjs'); +require('./metric.cjs'); +require('./observable.cjs'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var log__namespace = /*#__PURE__*/_interopNamespace(log); + + + +exports.array = array.array; +exports.binary = binary.binary; +exports.broadcastchannel = broadcastchannel.broadcastchannel; +exports.buffer = buffer.buffer; +exports.conditions = conditions.conditions; +exports.decoding = decoding.decoding; +exports.diff = diff.diff; +exports.dom = dom.dom; +exports.encoding = encoding.encoding; +exports.environment = environment.environment; +exports.error = error.error; +exports.eventloop = eventloop.eventloop; +exports.func = _function._function; +exports.indexeddb = indexeddb.indexeddb; +exports.iterator = iterator.iterator; +exports.json = json.json; +exports.logging = log__namespace; +exports.map = map.map$1; +exports.math = math.math; +exports.mutex = mutex.mutex; +exports.number = number.number; +exports.object = object.object; +exports.pair = pair.pair; +exports.prng = prng.prng; +exports.promise = promise.promise; +exports.set = set.set; +exports.sort = sort.sort; +exports.statistics = statistics.statistics; +exports.string = string.string; +exports.symbol = symbol.symbol; +exports.time = time.time; +exports.tree = tree.tree; +exports.websocket = websocket.websocket; +//# sourceMappingURL=index.cjs.map diff --git a/nodejs/node_modules/lib0/dist/index.cjs.map b/nodejs/node_modules/lib0/dist/index.cjs.map new file mode 100644 index 00000000..7fc393f9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/index.d.ts b/nodejs/node_modules/lib0/dist/index.d.ts new file mode 100644 index 00000000..8aa3ac2a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/index.d.ts @@ -0,0 +1,35 @@ +import * as array from './array.js'; +import * as binary from './binary.js'; +import * as broadcastchannel from './broadcastchannel.js'; +import * as buffer from './buffer.js'; +import * as conditions from './conditions.js'; +import * as decoding from './decoding.js'; +import * as diff from './diff.js'; +import * as dom from './dom.js'; +import * as encoding from './encoding.js'; +import * as environment from './environment.js'; +import * as error from './error.js'; +import * as eventloop from './eventloop.js'; +import * as func from './function.js'; +import * as indexeddb from './indexeddb.js'; +import * as iterator from './iterator.js'; +import * as json from './json.js'; +import * as logging from 'lib0/logging'; +import * as map from './map.js'; +import * as math from './math.js'; +import * as mutex from './mutex.js'; +import * as number from './number.js'; +import * as object from './object.js'; +import * as pair from './pair.js'; +import * as prng from './prng.js'; +import * as promise from './promise.js'; +import * as set from './set.js'; +import * as sort from './sort.js'; +import * as statistics from './statistics.js'; +import * as string from './string.js'; +import * as symbol from './symbol.js'; +import * as time from './time.js'; +import * as tree from './tree.js'; +import * as websocket from './websocket.js'; +export { array, binary, broadcastchannel, buffer, conditions, decoding, diff, dom, encoding, environment, error, eventloop, func, indexeddb, iterator, json, logging, map, math, mutex, number, object, pair, prng, promise, set, sort, statistics, string, symbol, time, tree, websocket }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/index.d.ts.map b/nodejs/node_modules/lib0/dist/index.d.ts.map new file mode 100644 index 00000000..d84038f6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.js"],"names":[],"mappings":"uBAQuB,YAAY;wBACX,aAAa;kCACH,uBAAuB;wBACjC,aAAa;4BACT,iBAAiB;0BACnB,eAAe;sBACnB,WAAW;qBACZ,UAAU;0BACL,eAAe;6BACZ,kBAAkB;uBACxB,YAAY;2BACR,gBAAgB;sBAErB,eAAe;2BACV,gBAAgB;0BACjB,eAAe;sBACnB,WAAW;yBACR,cAAc;qBAClB,UAAU;sBACT,WAAW;uBACV,YAAY;wBACX,aAAa;wBACb,aAAa;sBACf,WAAW;sBACX,WAAW;yBACR,cAAc;qBAElB,UAAU;sBACT,WAAW;4BACL,iBAAiB;wBACrB,aAAa;wBACb,aAAa;sBAEf,WAAW;sBACX,WAAW;2BACN,gBAAgB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/indexeddb-8d495848.cjs b/nodejs/node_modules/lib0/dist/indexeddb-8d495848.cjs new file mode 100644 index 00000000..7696e519 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb-8d495848.cjs @@ -0,0 +1,311 @@ +'use strict'; + +var promise = require('./promise-afe9dfc3.cjs'); +var error = require('./error-8582d695.cjs'); + +/* eslint-env browser */ + +/* c8 ignore start */ + +/** + * IDB Request to Promise transformer + * + * @param {IDBRequest} request + * @return {Promise} + */ +const rtop = request => promise.create((resolve, reject) => { + // @ts-ignore + request.onerror = event => reject(new Error(event.target.error)); + // @ts-ignore + request.onsuccess = event => resolve(event.target.result); +}); + +/** + * @param {string} name + * @param {function(IDBDatabase):any} initDB Called when the database is first created + * @return {Promise} + */ +const openDB = (name, initDB) => promise.create((resolve, reject) => { + const request = indexedDB.open(name); + /** + * @param {any} event + */ + request.onupgradeneeded = event => initDB(event.target.result); + /** + * @param {any} event + */ + request.onerror = event => reject(error.create(event.target.error)); + /** + * @param {any} event + */ + request.onsuccess = event => { + /** + * @type {IDBDatabase} + */ + const db = event.target.result; + db.onversionchange = () => { db.close(); }; + resolve(db); + }; +}); + +/** + * @param {string} name + */ +const deleteDB = name => rtop(indexedDB.deleteDatabase(name)); + +/** + * @param {IDBDatabase} db + * @param {Array|Array>} definitions + */ +const createStores = (db, definitions) => definitions.forEach(d => + // @ts-ignore + db.createObjectStore.apply(db, d) +); + +/** + * @param {IDBDatabase} db + * @param {Array} stores + * @param {"readwrite"|"readonly"} [access] + * @return {Array} + */ +const transact = (db, stores, access = 'readwrite') => { + const transaction = db.transaction(stores, access); + return stores.map(store => getStore(transaction, store)) +}; + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @return {Promise} + */ +const count = (store, range) => + rtop(store.count(range)); + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | Array } key + * @return {Promise>} + */ +const get = (store, key) => + rtop(store.get(key)); + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | IDBKeyRange | Array } key + */ +const del = (store, key) => + rtop(store.delete(key)); + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | boolean} item + * @param {String | number | ArrayBuffer | Date | Array} [key] + */ +const put = (store, item, key) => + rtop(store.put(item, key)); + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | boolean} item + * @param {String | number | ArrayBuffer | Date | Array} key + * @return {Promise} + */ +const add = (store, item, key) => + rtop(store.add(item, key)); + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date} item + * @return {Promise} Returns the generated key + */ +const addAutoKey = (store, item) => + rtop(store.add(item)); + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @param {number} [limit] + * @return {Promise>} + */ +const getAll = (store, range, limit) => + rtop(store.getAll(range, limit)); + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @param {number} [limit] + * @return {Promise>} + */ +const getAllKeys = (store, range, limit) => + rtop(store.getAllKeys(range, limit)); + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange|null} query + * @param {'next'|'prev'|'nextunique'|'prevunique'} direction + * @return {Promise} + */ +const queryFirst = (store, query, direction) => { + /** + * @type {any} + */ + let first = null; + return iterateKeys(store, query, key => { + first = key; + return false + }, direction).then(() => first) +}; + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange?} [range] + * @return {Promise} + */ +const getLastKey = (store, range = null) => queryFirst(store, range, 'prev'); + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange?} [range] + * @return {Promise} + */ +const getFirstKey = (store, range = null) => queryFirst(store, range, 'next'); + +/** + * @typedef KeyValuePair + * @type {Object} + * @property {any} k key + * @property {any} v Value + */ + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @param {number} [limit] + * @return {Promise>} + */ +const getAllKeysValues = (store, range, limit) => + // @ts-ignore + promise.all([getAllKeys(store, range, limit), getAll(store, range, limit)]).then(([ks, vs]) => ks.map((k, i) => ({ k, v: vs[i] }))); + +/** + * @param {any} request + * @param {function(IDBCursorWithValue):void|boolean|Promise} f + * @return {Promise} + */ +const iterateOnRequest = (request, f) => promise.create((resolve, reject) => { + request.onerror = reject; + /** + * @param {any} event + */ + request.onsuccess = async event => { + const cursor = event.target.result; + if (cursor === null || (await f(cursor)) === false) { + return resolve() + } + cursor.continue(); + }; +}); + +/** + * Iterate on keys and values + * @param {IDBObjectStore} store + * @param {IDBKeyRange|null} keyrange + * @param {function(any,any):void|boolean|Promise} f Callback that receives (value, key) + * @param {'next'|'prev'|'nextunique'|'prevunique'} direction + */ +const iterate = (store, keyrange, f, direction = 'next') => + iterateOnRequest(store.openCursor(keyrange, direction), cursor => f(cursor.value, cursor.key)); + +/** + * Iterate on the keys (no values) + * + * @param {IDBObjectStore} store + * @param {IDBKeyRange|null} keyrange + * @param {function(any):void|boolean|Promise} f callback that receives the key + * @param {'next'|'prev'|'nextunique'|'prevunique'} direction + */ +const iterateKeys = (store, keyrange, f, direction = 'next') => + iterateOnRequest(store.openKeyCursor(keyrange, direction), cursor => f(cursor.key)); + +/** + * Open store from transaction + * @param {IDBTransaction} t + * @param {String} store + * @returns {IDBObjectStore} + */ +const getStore = (t, store) => t.objectStore(store); + +/** + * @param {any} lower + * @param {any} upper + * @param {boolean} lowerOpen + * @param {boolean} upperOpen + */ +const createIDBKeyRangeBound = (lower, upper, lowerOpen, upperOpen) => IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen); + +/** + * @param {any} upper + * @param {boolean} upperOpen + */ +const createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen); + +/** + * @param {any} lower + * @param {boolean} lowerOpen + */ +const createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen); + +/* c8 ignore stop */ + +var indexeddb = /*#__PURE__*/Object.freeze({ + __proto__: null, + rtop: rtop, + openDB: openDB, + deleteDB: deleteDB, + createStores: createStores, + transact: transact, + count: count, + get: get, + del: del, + put: put, + add: add, + addAutoKey: addAutoKey, + getAll: getAll, + getAllKeys: getAllKeys, + queryFirst: queryFirst, + getLastKey: getLastKey, + getFirstKey: getFirstKey, + getAllKeysValues: getAllKeysValues, + iterate: iterate, + iterateKeys: iterateKeys, + getStore: getStore, + createIDBKeyRangeBound: createIDBKeyRangeBound, + createIDBKeyRangeUpperBound: createIDBKeyRangeUpperBound, + createIDBKeyRangeLowerBound: createIDBKeyRangeLowerBound +}); + +exports.add = add; +exports.addAutoKey = addAutoKey; +exports.count = count; +exports.createIDBKeyRangeBound = createIDBKeyRangeBound; +exports.createIDBKeyRangeLowerBound = createIDBKeyRangeLowerBound; +exports.createIDBKeyRangeUpperBound = createIDBKeyRangeUpperBound; +exports.createStores = createStores; +exports.del = del; +exports.deleteDB = deleteDB; +exports.get = get; +exports.getAll = getAll; +exports.getAllKeys = getAllKeys; +exports.getAllKeysValues = getAllKeysValues; +exports.getFirstKey = getFirstKey; +exports.getLastKey = getLastKey; +exports.getStore = getStore; +exports.indexeddb = indexeddb; +exports.iterate = iterate; +exports.iterateKeys = iterateKeys; +exports.openDB = openDB; +exports.put = put; +exports.queryFirst = queryFirst; +exports.rtop = rtop; +exports.transact = transact; +//# sourceMappingURL=indexeddb-8d495848.cjs.map diff --git a/nodejs/node_modules/lib0/dist/indexeddb-8d495848.cjs.map b/nodejs/node_modules/lib0/dist/indexeddb-8d495848.cjs.map new file mode 100644 index 00000000..58c1c266 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb-8d495848.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"indexeddb-8d495848.cjs","sources":["../indexeddb.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Helpers to work with IndexedDB.\n *\n * @module indexeddb\n */\n\nimport * as promise from './promise.js'\nimport * as error from './error.js'\n\n/* c8 ignore start */\n\n/**\n * IDB Request to Promise transformer\n *\n * @param {IDBRequest} request\n * @return {Promise}\n */\nexport const rtop = request => promise.create((resolve, reject) => {\n // @ts-ignore\n request.onerror = event => reject(new Error(event.target.error))\n // @ts-ignore\n request.onsuccess = event => resolve(event.target.result)\n})\n\n/**\n * @param {string} name\n * @param {function(IDBDatabase):any} initDB Called when the database is first created\n * @return {Promise}\n */\nexport const openDB = (name, initDB) => promise.create((resolve, reject) => {\n const request = indexedDB.open(name)\n /**\n * @param {any} event\n */\n request.onupgradeneeded = event => initDB(event.target.result)\n /**\n * @param {any} event\n */\n request.onerror = event => reject(error.create(event.target.error))\n /**\n * @param {any} event\n */\n request.onsuccess = event => {\n /**\n * @type {IDBDatabase}\n */\n const db = event.target.result\n db.onversionchange = () => { db.close() }\n resolve(db)\n }\n})\n\n/**\n * @param {string} name\n */\nexport const deleteDB = name => rtop(indexedDB.deleteDatabase(name))\n\n/**\n * @param {IDBDatabase} db\n * @param {Array|Array>} definitions\n */\nexport const createStores = (db, definitions) => definitions.forEach(d =>\n // @ts-ignore\n db.createObjectStore.apply(db, d)\n)\n\n/**\n * @param {IDBDatabase} db\n * @param {Array} stores\n * @param {\"readwrite\"|\"readonly\"} [access]\n * @return {Array}\n */\nexport const transact = (db, stores, access = 'readwrite') => {\n const transaction = db.transaction(stores, access)\n return stores.map(store => getStore(transaction, store))\n}\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @return {Promise}\n */\nexport const count = (store, range) =>\n rtop(store.count(range))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | Array } key\n * @return {Promise>}\n */\nexport const get = (store, key) =>\n rtop(store.get(key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | IDBKeyRange | Array } key\n */\nexport const del = (store, key) =>\n rtop(store.delete(key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | boolean} item\n * @param {String | number | ArrayBuffer | Date | Array} [key]\n */\nexport const put = (store, item, key) =>\n rtop(store.put(item, key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date | boolean} item\n * @param {String | number | ArrayBuffer | Date | Array} key\n * @return {Promise}\n */\nexport const add = (store, item, key) =>\n rtop(store.add(item, key))\n\n/**\n * @param {IDBObjectStore} store\n * @param {String | number | ArrayBuffer | Date} item\n * @return {Promise} Returns the generated key\n */\nexport const addAutoKey = (store, item) =>\n rtop(store.add(item))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAll = (store, range, limit) =>\n rtop(store.getAll(range, limit))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAllKeys = (store, range, limit) =>\n rtop(store.getAllKeys(range, limit))\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} query\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n * @return {Promise}\n */\nexport const queryFirst = (store, query, direction) => {\n /**\n * @type {any}\n */\n let first = null\n return iterateKeys(store, query, key => {\n first = key\n return false\n }, direction).then(() => first)\n}\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange?} [range]\n * @return {Promise}\n */\nexport const getLastKey = (store, range = null) => queryFirst(store, range, 'prev')\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange?} [range]\n * @return {Promise}\n */\nexport const getFirstKey = (store, range = null) => queryFirst(store, range, 'next')\n\n/**\n * @typedef KeyValuePair\n * @type {Object}\n * @property {any} k key\n * @property {any} v Value\n */\n\n/**\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange} [range]\n * @param {number} [limit]\n * @return {Promise>}\n */\nexport const getAllKeysValues = (store, range, limit) =>\n // @ts-ignore\n promise.all([getAllKeys(store, range, limit), getAll(store, range, limit)]).then(([ks, vs]) => ks.map((k, i) => ({ k, v: vs[i] })))\n\n/**\n * @param {any} request\n * @param {function(IDBCursorWithValue):void|boolean|Promise} f\n * @return {Promise}\n */\nconst iterateOnRequest = (request, f) => promise.create((resolve, reject) => {\n request.onerror = reject\n /**\n * @param {any} event\n */\n request.onsuccess = async event => {\n const cursor = event.target.result\n if (cursor === null || (await f(cursor)) === false) {\n return resolve()\n }\n cursor.continue()\n }\n})\n\n/**\n * Iterate on keys and values\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} keyrange\n * @param {function(any,any):void|boolean|Promise} f Callback that receives (value, key)\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n */\nexport const iterate = (store, keyrange, f, direction = 'next') =>\n iterateOnRequest(store.openCursor(keyrange, direction), cursor => f(cursor.value, cursor.key))\n\n/**\n * Iterate on the keys (no values)\n *\n * @param {IDBObjectStore} store\n * @param {IDBKeyRange|null} keyrange\n * @param {function(any):void|boolean|Promise} f callback that receives the key\n * @param {'next'|'prev'|'nextunique'|'prevunique'} direction\n */\nexport const iterateKeys = (store, keyrange, f, direction = 'next') =>\n iterateOnRequest(store.openKeyCursor(keyrange, direction), cursor => f(cursor.key))\n\n/**\n * Open store from transaction\n * @param {IDBTransaction} t\n * @param {String} store\n * @returns {IDBObjectStore}\n */\nexport const getStore = (t, store) => t.objectStore(store)\n\n/**\n * @param {any} lower\n * @param {any} upper\n * @param {boolean} lowerOpen\n * @param {boolean} upperOpen\n */\nexport const createIDBKeyRangeBound = (lower, upper, lowerOpen, upperOpen) => IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen)\n\n/**\n * @param {any} upper\n * @param {boolean} upperOpen\n */\nexport const createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen)\n\n/**\n * @param {any} lower\n * @param {boolean} lowerOpen\n */\nexport const createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen)\n\n/* c8 ignore stop */\n"],"names":["promise.create","error.create","promise.all"],"mappings":";;;;;AAAA;AA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E,QAAQ,EAAE,CAAC,EAAE,SAAS,GAAG,MAAM;AAClE,EAAE,gBAAgB,CAAC,KAAK,CAAC,aAAa,CAAC,QAAQ,EAAE,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAC;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,CAAC,WAAW,CAAC,KAAK,EAAC;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,sBAAsB,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,KAAK,WAAW,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAC;AACnI;AACA;AACA;AACA;AACA;AACY,MAAC,2BAA2B,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,WAAW,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,EAAC;AACzG;AACA;AACA;AACA;AACA;AACY,MAAC,2BAA2B,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,WAAW,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,EAAC;AACzG;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/indexeddb.cjs b/nodejs/node_modules/lib0/dist/indexeddb.cjs new file mode 100644 index 00000000..8aaa782e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb.cjs @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./promise-afe9dfc3.cjs'); +require('./error-8582d695.cjs'); +var indexeddb = require('./indexeddb-8d495848.cjs'); +require('./time-bc2081b9.cjs'); +require('./metric.cjs'); +require('./math-08e068f9.cjs'); + + + +exports.add = indexeddb.add; +exports.addAutoKey = indexeddb.addAutoKey; +exports.count = indexeddb.count; +exports.createIDBKeyRangeBound = indexeddb.createIDBKeyRangeBound; +exports.createIDBKeyRangeLowerBound = indexeddb.createIDBKeyRangeLowerBound; +exports.createIDBKeyRangeUpperBound = indexeddb.createIDBKeyRangeUpperBound; +exports.createStores = indexeddb.createStores; +exports.del = indexeddb.del; +exports.deleteDB = indexeddb.deleteDB; +exports.get = indexeddb.get; +exports.getAll = indexeddb.getAll; +exports.getAllKeys = indexeddb.getAllKeys; +exports.getAllKeysValues = indexeddb.getAllKeysValues; +exports.getFirstKey = indexeddb.getFirstKey; +exports.getLastKey = indexeddb.getLastKey; +exports.getStore = indexeddb.getStore; +exports.iterate = indexeddb.iterate; +exports.iterateKeys = indexeddb.iterateKeys; +exports.openDB = indexeddb.openDB; +exports.put = indexeddb.put; +exports.queryFirst = indexeddb.queryFirst; +exports.rtop = indexeddb.rtop; +exports.transact = indexeddb.transact; +//# sourceMappingURL=indexeddb.cjs.map diff --git a/nodejs/node_modules/lib0/dist/indexeddb.cjs.map b/nodejs/node_modules/lib0/dist/indexeddb.cjs.map new file mode 100644 index 00000000..5bfcf7ff --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"indexeddb.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/indexeddb.d.ts b/nodejs/node_modules/lib0/dist/indexeddb.d.ts new file mode 100644 index 00000000..712e7dcf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb.d.ts @@ -0,0 +1,34 @@ +export function rtop(request: IDBRequest): Promise; +export function openDB(name: string, initDB: (arg0: IDBDatabase) => any): Promise; +export function deleteDB(name: string): Promise; +export function createStores(db: IDBDatabase, definitions: Array | Array>): void; +export function transact(db: IDBDatabase, stores: Array, access?: "readonly" | "readwrite" | undefined): Array; +export function count(store: IDBObjectStore, range?: IDBKeyRange | undefined): Promise; +export function get(store: IDBObjectStore, key: string | number | ArrayBuffer | Date | Array): Promise>; +export function del(store: IDBObjectStore, key: string | number | ArrayBuffer | Date | IDBKeyRange | Array): Promise; +export function put(store: IDBObjectStore, item: string | number | ArrayBuffer | Date | boolean, key?: string | number | any[] | Date | ArrayBuffer | undefined): Promise; +export function add(store: IDBObjectStore, item: string | number | ArrayBuffer | Date | boolean, key: string | number | ArrayBuffer | Date | Array): Promise; +export function addAutoKey(store: IDBObjectStore, item: string | number | ArrayBuffer | Date): Promise; +export function getAll(store: IDBObjectStore, range?: IDBKeyRange | undefined, limit?: number | undefined): Promise>; +export function getAllKeys(store: IDBObjectStore, range?: IDBKeyRange | undefined, limit?: number | undefined): Promise>; +export function queryFirst(store: IDBObjectStore, query: IDBKeyRange | null, direction: 'next' | 'prev' | 'nextunique' | 'prevunique'): Promise; +export function getLastKey(store: IDBObjectStore, range?: IDBKeyRange | null | undefined): Promise; +export function getFirstKey(store: IDBObjectStore, range?: IDBKeyRange | null | undefined): Promise; +export function getAllKeysValues(store: IDBObjectStore, range?: IDBKeyRange | undefined, limit?: number | undefined): Promise>; +export function iterate(store: IDBObjectStore, keyrange: IDBKeyRange | null, f: (arg0: any, arg1: any) => void | boolean | Promise, direction?: 'next' | 'prev' | 'nextunique' | 'prevunique'): Promise; +export function iterateKeys(store: IDBObjectStore, keyrange: IDBKeyRange | null, f: (arg0: any) => void | boolean | Promise, direction?: 'next' | 'prev' | 'nextunique' | 'prevunique'): Promise; +export function getStore(t: IDBTransaction, store: string): IDBObjectStore; +export function createIDBKeyRangeBound(lower: any, upper: any, lowerOpen: boolean, upperOpen: boolean): IDBKeyRange; +export function createIDBKeyRangeUpperBound(upper: any, upperOpen: boolean): IDBKeyRange; +export function createIDBKeyRangeLowerBound(lower: any, lowerOpen: boolean): IDBKeyRange; +export type KeyValuePair = { + /** + * key + */ + k: any; + /** + * Value + */ + v: any; +}; +//# sourceMappingURL=indexeddb.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/indexeddb.d.ts.map b/nodejs/node_modules/lib0/dist/indexeddb.d.ts.map new file mode 100644 index 00000000..68eeba85 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"indexeddb.d.ts","sourceRoot":"","sources":["../indexeddb.js"],"names":[],"mappings":"AAmBO,8BAHI,UAAU,GACT,QAAQ,GAAG,CAAC,CAOtB;AAOK,6BAJI,MAAM,iBACG,WAAW,KAAE,GAAG,GACxB,QAAQ,WAAW,CAAC,CAuB9B;AAKK,+BAFI,MAAM,gBAEmD;AAM7D,iCAHI,WAAW,eACX,MAAM,MAAM,MAAM,CAAC,GAAC,MAAM,MAAM,GAAC,wBAAwB,GAAC,SAAS,CAAC,CAAC,QAK/E;AAQM,6BALI,WAAW,UACX,MAAM,MAAM,CAAC,kDAEZ,MAAM,cAAc,CAAC,CAKhC;AAOM,6BAJI,cAAc,oCAEb,QAAQ,MAAM,CAAC,CAGD;AAOnB,2BAJI,cAAc,OACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,GAChD,QAAQ,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,CAAC,CAGhD;AAMf,2BAHI,cAAc,OACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,WAAW,GAAG,MAAM,GAAG,CAAC,gBAGjD;AAOlB,2BAJI,cAAc,QACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,OAAO,gFAI7B;AAQrB,2BALI,cAAc,QACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,OAAO,OAC9C,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,GAChD,QAAQ,GAAG,CAAC,CAGI;AAOrB,kCAJI,cAAc,QACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GACnC,QAAQ,MAAM,CAAC,CAGJ;AAQhB,8BALI,cAAc,gEAGb,QAAQ,MAAM,GAAG,CAAC,CAAC,CAGG;AAQ3B,kCALI,cAAc,gEAGb,QAAQ,MAAM,GAAG,CAAC,CAAC,CAGO;AAQ/B,kCALI,cAAc,SACd,WAAW,GAAC,IAAI,aAChB,MAAM,GAAC,MAAM,GAAC,YAAY,GAAC,YAAY,GACtC,QAAQ,GAAG,CAAC,CAWvB;AAOM,kCAJI,cAAc,2CAEb,QAAQ,GAAG,CAAC,CAE2D;AAO5E,mCAJI,cAAc,2CAEb,QAAQ,GAAG,CAAC,CAE4D;AAe7E,wCALI,cAAc,gEAGb,QAAQ,MAAM,YAAY,CAAC,CAAC,CAI6F;AA4B9H,+BALI,cAAc,YACd,WAAW,GAAC,IAAI,YACP,GAAG,QAAC,GAAG,KAAE,IAAI,GAAC,OAAO,GAAC,QAAQ,IAAI,GAAC,OAAO,CAAC,cACpD,MAAM,GAAC,MAAM,GAAC,YAAY,GAAC,YAAY,iBAG8C;AAUzF,mCALI,cAAc,YACd,WAAW,GAAC,IAAI,YACP,GAAG,KAAE,IAAI,GAAC,OAAO,GAAC,QAAQ,IAAI,GAAC,OAAO,CAAC,cAChD,MAAM,GAAC,MAAM,GAAC,YAAY,GAAC,YAAY,iBAGmC;AAQ9E,4BAJI,cAAc,kBAEZ,cAAc,CAE+B;AAQnD,8CALI,GAAG,SACH,GAAG,aACH,OAAO,aACP,OAAO,eAEiH;AAM5H,mDAHI,GAAG,aACH,OAAO,eAEuF;AAMlG,mDAHI,GAAG,aACH,OAAO,eAEuF;;;;;OAhF3F,GAAG;;;;OACH,GAAG"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/indexeddb.test.d.ts b/nodejs/node_modules/lib0/dist/indexeddb.test.d.ts new file mode 100644 index 00000000..e45d0c98 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb.test.d.ts @@ -0,0 +1,3 @@ +export function testRetrieveElements(): Promise; +export function testBlocked(): Promise; +//# sourceMappingURL=indexeddb.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/indexeddb.test.d.ts.map b/nodejs/node_modules/lib0/dist/indexeddb.test.d.ts.map new file mode 100644 index 00000000..ecfbc2d1 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/indexeddb.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"indexeddb.test.d.ts","sourceRoot":"","sources":["../indexeddb.test.js"],"names":[],"mappings":"AAyBO,sDAoEN;AAGM,6CAWN"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/isomorphic.cjs b/nodejs/node_modules/lib0/dist/isomorphic.cjs new file mode 100644 index 00000000..4663b382 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/isomorphic.cjs @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var isomorphic_js = require('isomorphic.js'); + + + +Object.defineProperty(exports, 'cryptoRandomBuffer', { + enumerable: true, + get: function () { return isomorphic_js.cryptoRandomBuffer; } +}); +Object.defineProperty(exports, 'performance', { + enumerable: true, + get: function () { return isomorphic_js.performance; } +}); +//# sourceMappingURL=isomorphic.cjs.map diff --git a/nodejs/node_modules/lib0/dist/isomorphic.cjs.map b/nodejs/node_modules/lib0/dist/isomorphic.cjs.map new file mode 100644 index 00000000..76549af7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/isomorphic.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"isomorphic.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/isomorphic.d.ts b/nodejs/node_modules/lib0/dist/isomorphic.d.ts new file mode 100644 index 00000000..05103a67 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/isomorphic.d.ts @@ -0,0 +1,2 @@ +export { performance, cryptoRandomBuffer } from "isomorphic.js"; +//# sourceMappingURL=isomorphic.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/isomorphic.d.ts.map b/nodejs/node_modules/lib0/dist/isomorphic.d.ts.map new file mode 100644 index 00000000..89b90ca8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/isomorphic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isomorphic.d.ts","sourceRoot":"","sources":["../isomorphic.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/iterator-9fc627c1.cjs b/nodejs/node_modules/lib0/dist/iterator-9fc627c1.cjs new file mode 100644 index 00000000..96af2b9e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/iterator-9fc627c1.cjs @@ -0,0 +1,78 @@ +'use strict'; + +/** + * Utility module to create and manipulate Iterators. + * + * @module iterator + */ + +/** + * @template T,R + * @param {Iterator} iterator + * @param {function(T):R} f + * @return {IterableIterator} + */ +const mapIterator = (iterator, f) => ({ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next () { + const r = iterator.next(); + return { value: r.done ? undefined : f(r.value), done: r.done } + } +}); + +/** + * @template T + * @param {function():IteratorResult} next + * @return {IterableIterator} + */ +const createIterator = next => ({ + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next +}); + +/** + * @template T + * @param {Iterator} iterator + * @param {function(T):boolean} filter + */ +const iteratorFilter = (iterator, filter) => createIterator(() => { + let res; + do { + res = iterator.next(); + } while (!res.done && !filter(res.value)) + return res +}); + +/** + * @template T,M + * @param {Iterator} iterator + * @param {function(T):M} fmap + */ +const iteratorMap = (iterator, fmap) => createIterator(() => { + const { done, value } = iterator.next(); + return { done, value: done ? undefined : fmap(value) } +}); + +var iterator = /*#__PURE__*/Object.freeze({ + __proto__: null, + mapIterator: mapIterator, + createIterator: createIterator, + iteratorFilter: iteratorFilter, + iteratorMap: iteratorMap +}); + +exports.createIterator = createIterator; +exports.iterator = iterator; +exports.iteratorFilter = iteratorFilter; +exports.iteratorMap = iteratorMap; +exports.mapIterator = mapIterator; +//# sourceMappingURL=iterator-9fc627c1.cjs.map diff --git a/nodejs/node_modules/lib0/dist/iterator-9fc627c1.cjs.map b/nodejs/node_modules/lib0/dist/iterator-9fc627c1.cjs.map new file mode 100644 index 00000000..39a3dedc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/iterator-9fc627c1.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"iterator-9fc627c1.cjs","sources":["../iterator.js"],"sourcesContent":["/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator} iterator\n * @param {function(T):R} f\n * @return {IterableIterator}\n */\nexport const mapIterator = (iterator, f) => ({\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next () {\n const r = iterator.next()\n return { value: r.done ? undefined : f(r.value), done: r.done }\n }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult} next\n * @return {IterableIterator}\n */\nexport const createIterator = next => ({\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return this\n },\n // @ts-ignore\n next\n})\n\n/**\n * @template T\n * @param {Iterator} iterator\n * @param {function(T):boolean} filter\n */\nexport const iteratorFilter = (iterator, filter) => createIterator(() => {\n let res\n do {\n res = iterator.next()\n } while (!res.done && !filter(res.value))\n return res\n})\n\n/**\n * @template T,M\n * @param {Iterator} iterator\n * @param {function(T):M} fmap\n */\nexport const iteratorMap = (iterator, fmap) => createIterator(() => {\n const { done, value } = iterator.next()\n return { done, value: done ? undefined : fmap(value) }\n})\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,QAAQ,EAAE,CAAC,MAAM;AAC7C,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG;AACvB,IAAI,OAAO,IAAI;AACf,GAAG;AACH;AACA,EAAE,IAAI,CAAC,GAAG;AACV,IAAI,MAAM,CAAC,GAAG,QAAQ,CAAC,IAAI,GAAE;AAC7B,IAAI,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,IAAI,GAAG,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE;AACnE,GAAG;AACH,CAAC,EAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,IAAI,KAAK;AACvC;AACA;AACA;AACA,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG;AACvB,IAAI,OAAO,IAAI;AACf,GAAG;AACH;AACA,EAAE,IAAI;AACN,CAAC,EAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,cAAc,CAAC,MAAM;AACzE,EAAE,IAAI,IAAG;AACT,EAAE,GAAG;AACL,IAAI,GAAG,GAAG,QAAQ,CAAC,IAAI,GAAE;AACzB,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAC3C,EAAE,OAAO,GAAG;AACZ,CAAC,EAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,QAAQ,EAAE,IAAI,KAAK,cAAc,CAAC,MAAM;AACpE,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC,IAAI,GAAE;AACzC,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE;AACxD,CAAC;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/iterator.cjs b/nodejs/node_modules/lib0/dist/iterator.cjs new file mode 100644 index 00000000..f09575e6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/iterator.cjs @@ -0,0 +1,13 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var iterator = require('./iterator-9fc627c1.cjs'); + + + +exports.createIterator = iterator.createIterator; +exports.iteratorFilter = iterator.iteratorFilter; +exports.iteratorMap = iterator.iteratorMap; +exports.mapIterator = iterator.mapIterator; +//# sourceMappingURL=iterator.cjs.map diff --git a/nodejs/node_modules/lib0/dist/iterator.cjs.map b/nodejs/node_modules/lib0/dist/iterator.cjs.map new file mode 100644 index 00000000..298b3d0a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/iterator.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"iterator.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/iterator.d.ts b/nodejs/node_modules/lib0/dist/iterator.d.ts new file mode 100644 index 00000000..0254cc99 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/iterator.d.ts @@ -0,0 +1,5 @@ +export function mapIterator(iterator: Iterator, f: (arg0: T) => R): IterableIterator; +export function createIterator(next: () => IteratorResult): IterableIterator; +export function iteratorFilter(iterator: Iterator, filter: (arg0: T) => boolean): IterableIterator; +export function iteratorMap(iterator: Iterator, fmap: (arg0: T) => M): IterableIterator; +//# sourceMappingURL=iterator.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/iterator.d.ts.map b/nodejs/node_modules/lib0/dist/iterator.d.ts.map new file mode 100644 index 00000000..223bb331 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/iterator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"iterator.d.ts","sourceRoot":"","sources":["../iterator.js"],"names":[],"mappings":"AAYO,iHASL;AAOK,2FASL;AAOK,8FAFgB,OAAO,uBAQ5B;AAOK,gIAGL"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/json-092190a1.cjs b/nodejs/node_modules/lib0/dist/json-092190a1.cjs new file mode 100644 index 00000000..c68df3c4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/json-092190a1.cjs @@ -0,0 +1,34 @@ +'use strict'; + +/** + * JSON utility functions. + * + * @module json + */ + +/** + * Transform JavaScript object to JSON. + * + * @param {any} object + * @return {string} + */ +const stringify = JSON.stringify; + +/** + * Parse JSON object. + * + * @param {string} json + * @return {any} + */ +const parse = JSON.parse; + +var json = /*#__PURE__*/Object.freeze({ + __proto__: null, + stringify: stringify, + parse: parse +}); + +exports.json = json; +exports.parse = parse; +exports.stringify = stringify; +//# sourceMappingURL=json-092190a1.cjs.map diff --git a/nodejs/node_modules/lib0/dist/json-092190a1.cjs.map b/nodejs/node_modules/lib0/dist/json-092190a1.cjs.map new file mode 100644 index 00000000..a1f913e8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/json-092190a1.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"json-092190a1.cjs","sources":["../json.js"],"sourcesContent":["/**\n * JSON utility functions.\n *\n * @module json\n */\n\n/**\n * Transform JavaScript object to JSON.\n *\n * @param {any} object\n * @return {string}\n */\nexport const stringify = JSON.stringify\n\n/**\n * Parse JSON object.\n *\n * @param {string} json\n * @return {any}\n */\nexport const parse = JSON.parse\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,IAAI,CAAC,UAAS;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,IAAI,CAAC;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/json.cjs b/nodejs/node_modules/lib0/dist/json.cjs new file mode 100644 index 00000000..e660d4b7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/json.cjs @@ -0,0 +1,11 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var json = require('./json-092190a1.cjs'); + + + +exports.parse = json.parse; +exports.stringify = json.stringify; +//# sourceMappingURL=json.cjs.map diff --git a/nodejs/node_modules/lib0/dist/json.cjs.map b/nodejs/node_modules/lib0/dist/json.cjs.map new file mode 100644 index 00000000..c3dabfb0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/json.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"json.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/json.d.ts b/nodejs/node_modules/lib0/dist/json.d.ts new file mode 100644 index 00000000..494abcf6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/json.d.ts @@ -0,0 +1,23 @@ +/** + * JSON utility functions. + * + * @module json + */ +/** + * Transform JavaScript object to JSON. + * + * @param {any} object + * @return {string} + */ +export const stringify: { + (value: any, replacer?: ((this: any, key: string, value: any) => any) | undefined, space?: string | number | undefined): string; + (value: any, replacer?: (string | number)[] | null | undefined, space?: string | number | undefined): string; +}; +/** + * Parse JSON object. + * + * @param {string} json + * @return {any} + */ +export const parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any; +//# sourceMappingURL=json.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/json.d.ts.map b/nodejs/node_modules/lib0/dist/json.d.ts.map new file mode 100644 index 00000000..516b9d60 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/json.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../json.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;GAKG;AACH;;;EAAuC;AAEvC;;;;;GAKG;AACH,+GAA+B"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/jwt.cjs b/nodejs/node_modules/lib0/dist/jwt.cjs new file mode 100644 index 00000000..0a76cabc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/jwt.cjs @@ -0,0 +1,95 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var error = require('./error-8582d695.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); +var string = require('./string-6d104757.cjs'); +var json = require('./json-092190a1.cjs'); +var ecdsa = require('./ecdsa.cjs'); +var time = require('./time-bc2081b9.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./map-0dabcc55.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./object-fecf6a7b.cjs'); +require('./math-08e068f9.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./decoding-000d097f.cjs'); +require('lib0/webcrypto'); +require('./common.cjs'); +require('./metric.cjs'); + +/** + * @param {Object} data + */ +const _stringify = data => buffer.toBase64UrlEncoded(string.encodeUtf8(json.stringify(data))); + +/** + * @param {string} base64url + */ +const _parse = base64url => json.parse(string.decodeUtf8(buffer.fromBase64UrlEncoded(base64url))); + +/** + * @param {CryptoKey} privateKey + * @param {Object} payload + */ +const encodeJwt = (privateKey, payload) => { + const { name: algName, namedCurve: algCurve } = /** @type {any} */ (privateKey.algorithm); + /* c8 ignore next 3 */ + if (algName !== 'ECDSA' || algCurve !== 'P-384') { + error.unexpectedCase(); + } + const header = { + alg: 'ES384', + typ: 'JWT' + }; + const jwt = _stringify(header) + '.' + _stringify(payload); + return ecdsa.sign(privateKey, string.encodeUtf8(jwt)).then(signature => + jwt + '.' + buffer.toBase64UrlEncoded(signature) + ) +}; + +/** + * @param {CryptoKey} publicKey + * @param {string} jwt + */ +const verifyJwt = async (publicKey, jwt) => { + const [headerBase64, payloadBase64, signatureBase64] = jwt.split('.'); + const verified = await ecdsa.verify(publicKey, buffer.fromBase64UrlEncoded(signatureBase64), string.encodeUtf8(headerBase64 + '.' + payloadBase64)); + /* c8 ignore next 3 */ + if (!verified) { + throw new Error('Invalid JWT') + } + const payload = _parse(payloadBase64); + if (payload.exp != null && time.getUnixTime() > payload.exp) { + throw new Error('Expired JWT') + } + return { + header: _parse(headerBase64), + payload + } +}; + +/** + * Decode a jwt without verifying it. Probably a bad idea to use this. Only use if you know the jwt was already verified! + * + * @param {string} jwt + */ +const unsafeDecode = jwt => { + const [headerBase64, payloadBase64] = jwt.split('.'); + return { + header: _parse(headerBase64), + payload: _parse(payloadBase64) + } +}; + +exports.encodeJwt = encodeJwt; +exports.unsafeDecode = unsafeDecode; +exports.verifyJwt = verifyJwt; +//# sourceMappingURL=jwt.cjs.map diff --git a/nodejs/node_modules/lib0/dist/jwt.cjs.map b/nodejs/node_modules/lib0/dist/jwt.cjs.map new file mode 100644 index 00000000..9a0fab48 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/jwt.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"jwt.cjs","sources":["../crypto/jwt.js"],"sourcesContent":["import * as error from '../error.js'\nimport * as buffer from '../buffer.js'\nimport * as string from '../string.js'\nimport * as json from '../json.js'\nimport * as ecdsa from '../crypto/ecdsa.js'\nimport * as time from '../time.js'\n\n/**\n * @param {Object} data\n */\nconst _stringify = data => buffer.toBase64UrlEncoded(string.encodeUtf8(json.stringify(data)))\n\n/**\n * @param {string} base64url\n */\nconst _parse = base64url => json.parse(string.decodeUtf8(buffer.fromBase64UrlEncoded(base64url)))\n\n/**\n * @param {CryptoKey} privateKey\n * @param {Object} payload\n */\nexport const encodeJwt = (privateKey, payload) => {\n const { name: algName, namedCurve: algCurve } = /** @type {any} */ (privateKey.algorithm)\n /* c8 ignore next 3 */\n if (algName !== 'ECDSA' || algCurve !== 'P-384') {\n error.unexpectedCase()\n }\n const header = {\n alg: 'ES384',\n typ: 'JWT'\n }\n const jwt = _stringify(header) + '.' + _stringify(payload)\n return ecdsa.sign(privateKey, string.encodeUtf8(jwt)).then(signature =>\n jwt + '.' + buffer.toBase64UrlEncoded(signature)\n )\n}\n\n/**\n * @param {CryptoKey} publicKey\n * @param {string} jwt\n */\nexport const verifyJwt = async (publicKey, jwt) => {\n const [headerBase64, payloadBase64, signatureBase64] = jwt.split('.')\n const verified = await ecdsa.verify(publicKey, buffer.fromBase64UrlEncoded(signatureBase64), string.encodeUtf8(headerBase64 + '.' + payloadBase64))\n /* c8 ignore next 3 */\n if (!verified) {\n throw new Error('Invalid JWT')\n }\n const payload = _parse(payloadBase64)\n if (payload.exp != null && time.getUnixTime() > payload.exp) {\n throw new Error('Expired JWT')\n }\n return {\n header: _parse(headerBase64),\n payload\n }\n}\n\n/**\n * Decode a jwt without verifying it. Probably a bad idea to use this. Only use if you know the jwt was already verified!\n *\n * @param {string} jwt\n */\nexport const unsafeDecode = jwt => {\n const [headerBase64, payloadBase64] = jwt.split('.')\n return {\n header: _parse(headerBase64),\n payload: _parse(payloadBase64)\n }\n}\n"],"names":["buffer.toBase64UrlEncoded","string.encodeUtf8","json.stringify","json.parse","string.decodeUtf8","buffer.fromBase64UrlEncoded","error.unexpectedCase","ecdsa.sign","ecdsa.verify","time.getUnixTime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA;AACA;AACA;AACA,MAAM,UAAU,GAAG,IAAI,IAAIA,yBAAyB,CAACC,iBAAiB,CAACC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAC;AAC7F;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,SAAS,IAAIC,UAAU,CAACC,iBAAiB,CAACC,2BAA2B,CAAC,SAAS,CAAC,CAAC,EAAC;AACjG;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,CAAC,UAAU,EAAE,OAAO,KAAK;AAClD,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,uBAAuB,UAAU,CAAC,SAAS,EAAC;AAC3F;AACA,EAAE,IAAI,OAAO,KAAK,OAAO,IAAI,QAAQ,KAAK,OAAO,EAAE;AACnD,IAAIC,oBAAoB,GAAE;AAC1B,GAAG;AACH,EAAE,MAAM,MAAM,GAAG;AACjB,IAAI,GAAG,EAAE,OAAO;AAChB,IAAI,GAAG,EAAE,KAAK;AACd,IAAG;AACH,EAAE,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,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MAAM,CAAC,aAAa,CAAC;AAClC,GAAG;AACH;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/list.cjs b/nodejs/node_modules/lib0/dist/list.cjs new file mode 100644 index 00000000..0999d321 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/list.cjs @@ -0,0 +1,225 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var _function = require('./function-314fdc56.cjs'); +var error = require('./error-8582d695.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./object-fecf6a7b.cjs'); + +class ListNode { + constructor () { + /** + * @type {this|null} + */ + this.next = null; + /** + * @type {this|null} + */ + this.prev = null; + } +} + +/** + * @template {ListNode} N + */ +class List { + constructor () { + /** + * @type {N | null} + */ + this.start = null; + /** + * @type {N | null} + */ + this.end = null; + this.len = 0; + } +} + +/** + * @note The queue implementation is experimental and unfinished. + * Don't use this in production yet. + * + * @template {ListNode} N + * + * @return {List} + */ +const create = () => new List(); + +/** + * @template {ListNode} N + * + * @param {List} queue + */ +const isEmpty = queue => queue.start === null; + +/** + * Remove a single node from the queue. Only works with Queues that operate on Doubly-linked lists of nodes. + * + * @template {ListNode} N + * + * @param {List} queue + * @param {N} node + */ +const remove = (queue, node) => { + const prev = node.prev; + const next = node.next; + if (prev) { + prev.next = next; + } else { + queue.start = next; + } + if (next) { + next.prev = prev; + } else { + queue.end = prev; + } + queue.len--; + return node +}; + +/** + * @deprecated @todo remove in next major release + */ +const removeNode = remove; + +/** + * @template {ListNode} N + * + * @param {List} queue + * @param {N| null} left + * @param {N| null} right + * @param {N} node + */ +const insertBetween = (queue, left, right, node) => { + /* c8 ignore start */ + if (left != null && left.next !== right) { + throw error.unexpectedCase() + } + /* c8 ignore stop */ + if (left) { + left.next = node; + } else { + queue.start = node; + } + if (right) { + right.prev = node; + } else { + queue.end = node; + } + node.prev = left; + node.next = right; + queue.len++; +}; + +/** + * Remove a single node from the queue. Only works with Queues that operate on Doubly-linked lists of nodes. + * + * @template {ListNode} N + * + * @param {List} queue + * @param {N} node + * @param {N} newNode + */ +const replace = (queue, node, newNode) => { + insertBetween(queue, node, node.next, newNode); + remove(queue, node); +}; + +/** + * @template {ListNode} N + * + * @param {List} queue + * @param {N} n + */ +const pushEnd = (queue, n) => + insertBetween(queue, queue.end, null, n); + +/** + * @template {ListNode} N + * + * @param {List} queue + * @param {N} n + */ +const pushFront = (queue, n) => + insertBetween(queue, null, queue.start, n); + +/** + * @template {ListNode} N + * + * @param {List} list + * @return {N| null} + */ +const popFront = list => + list.start ? removeNode(list, list.start) : null; + +/** + * @template {ListNode} N + * + * @param {List} list + * @return {N| null} + */ +const popEnd = list => + list.end ? removeNode(list, list.end) : null; + +/** + * @template {ListNode} N + * @template M + * + * @param {List} list + * @param {function(N):M} f + * @return {Array} + */ +const map = (list, f) => { + /** + * @type {Array} + */ + const arr = []; + let n = list.start; + while (n) { + arr.push(f(n)); + n = n.next; + } + return arr +}; + +/** + * @template {ListNode} N + * + * @param {List} list + */ +const toArray = list => map(list, _function.id); + +/** + * @template {ListNode} N + * @template M + * + * @param {List} list + * @param {function(N):M} f + */ +const forEach = (list, f) => { + let n = list.start; + while (n) { + f(n); + n = n.next; + } +}; + +exports.List = List; +exports.ListNode = ListNode; +exports.create = create; +exports.forEach = forEach; +exports.insertBetween = insertBetween; +exports.isEmpty = isEmpty; +exports.map = map; +exports.popEnd = popEnd; +exports.popFront = popFront; +exports.pushEnd = pushEnd; +exports.pushFront = pushFront; +exports.remove = remove; +exports.removeNode = removeNode; +exports.replace = replace; +exports.toArray = toArray; +//# sourceMappingURL=list.cjs.map diff --git a/nodejs/node_modules/lib0/dist/list.cjs.map b/nodejs/node_modules/lib0/dist/list.cjs.map new file mode 100644 index 00000000..5e77f063 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/list.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"list.cjs","sources":["../list.js"],"sourcesContent":["import { id } from './function.js'\nimport * as error from './error.js'\n\nexport class ListNode {\n constructor () {\n /**\n * @type {this|null}\n */\n this.next = null\n /**\n * @type {this|null}\n */\n this.prev = null\n }\n}\n\n/**\n * @template {ListNode} N\n */\nexport class List {\n constructor () {\n /**\n * @type {N | null}\n */\n this.start = null\n /**\n * @type {N | null}\n */\n this.end = null\n this.len = 0\n }\n}\n\n/**\n * @note The queue implementation is experimental and unfinished.\n * Don't use this in production yet.\n *\n * @template {ListNode} N\n *\n * @return {List}\n */\nexport const create = () => new List()\n\n/**\n * @template {ListNode} N\n *\n * @param {List} queue\n */\nexport const isEmpty = queue => queue.start === null\n\n/**\n * Remove a single node from the queue. Only works with Queues that operate on Doubly-linked lists of nodes.\n *\n * @template {ListNode} N\n *\n * @param {List} queue\n * @param {N} node\n */\nexport const remove = (queue, node) => {\n const prev = node.prev\n const next = node.next\n if (prev) {\n prev.next = next\n } else {\n queue.start = next\n }\n if (next) {\n next.prev = prev\n } else {\n queue.end = prev\n }\n queue.len--\n return node\n}\n\n/**\n * @deprecated @todo remove in next major release\n */\nexport const removeNode = remove\n\n/**\n * @template {ListNode} N\n *\n * @param {List} queue\n * @param {N| null} left\n * @param {N| null} right\n * @param {N} node\n */\nexport const insertBetween = (queue, left, right, node) => {\n /* c8 ignore start */\n if (left != null && left.next !== right) {\n throw error.unexpectedCase()\n }\n /* c8 ignore stop */\n if (left) {\n left.next = node\n } else {\n queue.start = node\n }\n if (right) {\n right.prev = node\n } else {\n queue.end = node\n }\n node.prev = left\n node.next = right\n queue.len++\n}\n\n/**\n * Remove a single node from the queue. Only works with Queues that operate on Doubly-linked lists of nodes.\n *\n * @template {ListNode} N\n *\n * @param {List} queue\n * @param {N} node\n * @param {N} newNode\n */\nexport const replace = (queue, node, newNode) => {\n insertBetween(queue, node, node.next, newNode)\n remove(queue, node)\n}\n\n/**\n * @template {ListNode} N\n *\n * @param {List} queue\n * @param {N} n\n */\nexport const pushEnd = (queue, n) =>\n insertBetween(queue, queue.end, null, n)\n\n/**\n * @template {ListNode} N\n *\n * @param {List} queue\n * @param {N} n\n */\nexport const pushFront = (queue, n) =>\n insertBetween(queue, null, queue.start, n)\n\n/**\n * @template {ListNode} N\n *\n * @param {List} list\n * @return {N| null}\n */\nexport const popFront = list =>\n list.start ? removeNode(list, list.start) : null\n\n/**\n * @template {ListNode} N\n *\n * @param {List} list\n * @return {N| null}\n */\nexport const popEnd = list =>\n list.end ? removeNode(list, list.end) : null\n\n/**\n * @template {ListNode} N\n * @template M\n *\n * @param {List} list\n * @param {function(N):M} f\n * @return {Array}\n */\nexport const map = (list, f) => {\n /**\n * @type {Array}\n */\n const arr = []\n let n = list.start\n while (n) {\n arr.push(f(n))\n n = n.next\n }\n return arr\n}\n\n/**\n * @template {ListNode} N\n *\n * @param {List} list\n */\nexport const toArray = list => map(list, id)\n\n/**\n * @template {ListNode} N\n * @template M\n *\n * @param {List} list\n * @param {function(N):M} f\n */\nexport const forEach = (list, f) => {\n let n = list.start\n while (n) {\n f(n)\n n = n.next\n }\n}\n"],"names":["error.unexpectedCase","id"],"mappings":";;;;;;;;;;AAGO,MAAM,QAAQ,CAAC;AACtB,EAAE,WAAW,CAAC,GAAG;AACjB;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACO,MAAM,IAAI,CAAC;AAClB,EAAE,WAAW,CAAC,GAAG;AACjB;AACA;AACA;AACA,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB;AACA;AACA;AACA,IAAI,IAAI,CAAC,GAAG,GAAG,KAAI;AACnB,IAAI,IAAI,CAAC,GAAG,GAAG,EAAC;AAChB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,IAAI,IAAI,GAAE;AACtC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GA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,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAC;AAClB,IAAI,CAAC,GAAG,CAAC,CAAC,KAAI;AACd,GAAG;AACH,EAAE,OAAO,GAAG;AACZ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,IAAI,IAAI,GAAG,CAAC,IAAI,EAAEC,YAAE,EAAC;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK;AACpC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAK;AACpB,EAAE,OAAO,CAAC,EAAE;AACZ,IAAI,CAAC,CAAC,CAAC,EAAC;AACR,IAAI,CAAC,GAAG,CAAC,CAAC,KAAI;AACd,GAAG;AACH;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/list.d.ts b/nodejs/node_modules/lib0/dist/list.d.ts new file mode 100644 index 00000000..77b148a7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/list.d.ts @@ -0,0 +1,38 @@ +export class ListNode { + /** + * @type {this|null} + */ + next: ListNode | null; + /** + * @type {this|null} + */ + prev: ListNode | null; +} +/** + * @template {ListNode} N + */ +export class List { + /** + * @type {N | null} + */ + start: N | null; + /** + * @type {N | null} + */ + end: N | null; + len: number; +} +export function create(): List; +export function isEmpty(queue: List): boolean; +export function remove(queue: List, node: N): N; +export function removeNode(queue: List, node: N): N; +export function insertBetween(queue: List, left: N | null, right: N | null, node: N): void; +export function replace(queue: List, node: N, newNode: N): void; +export function pushEnd(queue: List, n: N): void; +export function pushFront(queue: List, n: N): void; +export function popFront(list: List): N | null; +export function popEnd(list: List): N | null; +export function map(list: List, f: (arg0: N) => M): M[]; +export function toArray(list: List): N[]; +export function forEach(list: List, f: (arg0: N) => M): void; +//# sourceMappingURL=list.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/list.d.ts.map b/nodejs/node_modules/lib0/dist/list.d.ts.map new file mode 100644 index 00000000..4043539a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/list.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../list.js"],"names":[],"mappings":"AAGA;IAEI;;OAEG;IACH,sBAAgB;IAChB;;OAEG;IACH,sBAAgB;CAEnB;AAED;;GAEG;AACH;IAEI;;OAEG;IACH,OAFU,CAAC,GAAG,IAAI,CAED;IACjB;;OAEG;IACH,KAFU,CAAC,GAAG,IAAI,CAEH;IACf,YAAY;CAEf;AAUM,sDAA+B;AAO/B,qEAA6C;AAU7C,uEAeN;AAfM,2EAeN;AAeM,kHAmBN;AAWM,uFAGN;AAQM,wEACmC;AAQnC,0EACqC;AAQrC,sEAC2C;AAQ3C,oEACuC;AAUvC,kFAWN;AAOM,gEAAqC;AASrC,uFAMN"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/list.test.d.ts b/nodejs/node_modules/lib0/dist/list.test.d.ts new file mode 100644 index 00000000..006aeae5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/list.test.d.ts @@ -0,0 +1,4 @@ +export function testEnqueueDequeue(_tc: t.TestCase): void; +export function testSelectivePop(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=list.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/list.test.d.ts.map b/nodejs/node_modules/lib0/dist/list.test.d.ts.map new file mode 100644 index 00000000..b065747d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/list.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"list.test.d.ts","sourceRoot":"","sources":["../list.test.js"],"names":[],"mappings":"AAgBO,wCAFI,EAAE,QAAQ,QA8BpB;AAKM,sCAFI,EAAE,QAAQ,QA+BpB;mBA9EkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.cjs b/nodejs/node_modules/lib0/dist/logging.cjs new file mode 100644 index 00000000..87680e6e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.cjs @@ -0,0 +1,419 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var environment = require('./environment-f4d7c3e5.cjs'); +var set = require('./set-0f209abb.cjs'); +var pair = require('./pair-ab022bc3.cjs'); +var dom = require('./dom-16daf1a0.cjs'); +var json = require('./json-092190a1.cjs'); +var map = require('./map-0dabcc55.cjs'); +var eventloop = require('./eventloop-d0571621.cjs'); +var math = require('./math-08e068f9.cjs'); +var logging_common = require('./logging.common.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./symbol-c5caa724.cjs'); +require('./time-bc2081b9.cjs'); +require('./metric.cjs'); + +/** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + +/** + * @type {Object>} + */ +const _browserStyleMap = { + [logging_common.BOLD]: pair.create('font-weight', 'bold'), + [logging_common.UNBOLD]: pair.create('font-weight', 'normal'), + [logging_common.BLUE]: pair.create('color', 'blue'), + [logging_common.GREEN]: pair.create('color', 'green'), + [logging_common.GREY]: pair.create('color', 'grey'), + [logging_common.RED]: pair.create('color', 'red'), + [logging_common.PURPLE]: pair.create('color', 'purple'), + [logging_common.ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate + [logging_common.UNCOLOR]: pair.create('color', 'black') +}; + +/** + * @param {Array} args + * @return {Array} + */ +/* c8 ignore start */ +const computeBrowserLoggingArgs = (args) => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]()); + } + const strBuilder = []; + const styles = []; + const currentStyle = map.create(); + /** + * @type {Array} + */ + let logArgs = []; + // try with formatting until we find something unsupported + let i = 0; + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg === undefined) { + break + } + if (arg.constructor === String || arg.constructor === Number) { + const style = dom.mapToStyleString(currentStyle); + if (i > 0 || style.length > 0) { + strBuilder.push('%c' + arg); + styles.push(style); + } else { + strBuilder.push(arg); + } + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + logArgs = styles; + logArgs.unshift(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs +}; +/* c8 ignore stop */ + +/* c8 ignore start */ +const computeLoggingArgs = environment.supportsColor + ? computeBrowserLoggingArgs + : logging_common.computeNoColorLoggingArgs; +/* c8 ignore stop */ + +/** + * @param {Array} args + */ +const print = (...args) => { + console.log(...computeLoggingArgs(args)); + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.print(args)); +}; + +/* c8 ignore start */ +/** + * @param {Array} args + */ +const warn = (...args) => { + console.warn(...computeLoggingArgs(args)); + args.unshift(logging_common.ORANGE); + vconsoles.forEach((vc) => vc.print(args)); +}; +/* c8 ignore stop */ + +/** + * @param {Error} err + */ +/* c8 ignore start */ +const printError = (err) => { + console.error(err); + vconsoles.forEach((vc) => vc.printError(err)); +}; +/* c8 ignore stop */ + +/** + * @param {string} url image location + * @param {number} height height of the image in pixel + */ +/* c8 ignore start */ +const printImg = (url, height) => { + if (environment.isBrowser) { + console.log( + '%c ', + `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})` + ); + // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`) + } + vconsoles.forEach((vc) => vc.printImg(url, height)); +}; +/* c8 ignore stop */ + +/** + * @param {string} base64 + * @param {number} height + */ +/* c8 ignore next 2 */ +const printImgBase64 = (base64, height) => + printImg(`data:image/gif;base64,${base64}`, height); + +/** + * @param {Array} args + */ +const group = (...args) => { + console.group(...computeLoggingArgs(args)); + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.group(args)); +}; + +/** + * @param {Array} args + */ +const groupCollapsed = (...args) => { + console.groupCollapsed(...computeLoggingArgs(args)); + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.groupCollapsed(args)); +}; + +const groupEnd = () => { + console.groupEnd(); + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.groupEnd()); +}; + +/** + * @param {function():Node} createNode + */ +/* c8 ignore next 2 */ +const printDom = (createNode) => + vconsoles.forEach((vc) => vc.printDom(createNode())); + +/** + * @param {HTMLCanvasElement} canvas + * @param {number} height + */ +/* c8 ignore next 2 */ +const printCanvas = (canvas, height) => + printImg(canvas.toDataURL(), height); + +const vconsoles = set.create(); + +/** + * @param {Array} args + * @return {Array} + */ +/* c8 ignore start */ +const _computeLineSpans = (args) => { + const spans = []; + const currentStyle = new Map(); + // try with formatting until we find something unsupported + let i = 0; + for (; i < args.length; i++) { + let arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg === undefined) { + arg = 'undefined '; + } + if (arg.constructor === String || arg.constructor === Number) { + // @ts-ignore + const span = dom.element('span', [ + pair.create('style', dom.mapToStyleString(currentStyle)) + ], [dom.text(arg.toString())]); + if (span.innerHTML === '') { + span.innerHTML = ' '; + } + spans.push(span); + } else { + break + } + } + } + // append the rest + for (; i < args.length; i++) { + let content = args[i]; + if (!(content instanceof Symbol)) { + if (content.constructor !== String && content.constructor !== Number) { + content = ' ' + json.stringify(content) + ' '; + } + spans.push( + dom.element('span', [], [dom.text(/** @type {string} */ (content))]) + ); + } + } + return spans +}; +/* c8 ignore stop */ + +const lineStyle = + 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'; + +/* c8 ignore start */ +class VConsole { + /** + * @param {Element} dom + */ + constructor (dom) { + this.dom = dom; + /** + * @type {Element} + */ + this.ccontainer = this.dom; + this.depth = 0; + vconsoles.add(this); + } + + /** + * @param {Array} args + * @param {boolean} collapsed + */ + group (args, collapsed = false) { + eventloop.enqueue(() => { + const triangleDown = dom.element('span', [ + pair.create('hidden', collapsed), + pair.create('style', 'color:grey;font-size:120%;') + ], [dom.text('▼')]); + const triangleRight = dom.element('span', [ + pair.create('hidden', !collapsed), + pair.create('style', 'color:grey;font-size:125%;') + ], [dom.text('▶')]); + const content = dom.element( + 'div', + [pair.create( + 'style', + `${lineStyle};padding-left:${this.depth * 10}px` + )], + [triangleDown, triangleRight, dom.text(' ')].concat( + _computeLineSpans(args) + ) + ); + const nextContainer = dom.element('div', [ + pair.create('hidden', collapsed) + ]); + const nextLine = dom.element('div', [], [content, nextContainer]); + dom.append(this.ccontainer, [nextLine]); + this.ccontainer = nextContainer; + this.depth++; + // when header is clicked, collapse/uncollapse container + dom.addEventListener(content, 'click', (_event) => { + nextContainer.toggleAttribute('hidden'); + triangleDown.toggleAttribute('hidden'); + triangleRight.toggleAttribute('hidden'); + }); + }); + } + + /** + * @param {Array} args + */ + groupCollapsed (args) { + this.group(args, true); + } + + groupEnd () { + eventloop.enqueue(() => { + if (this.depth > 0) { + this.depth--; + // @ts-ignore + this.ccontainer = this.ccontainer.parentElement.parentElement; + } + }); + } + + /** + * @param {Array} args + */ + print (args) { + eventloop.enqueue(() => { + dom.append(this.ccontainer, [ + dom.element('div', [ + pair.create( + 'style', + `${lineStyle};padding-left:${this.depth * 10}px` + ) + ], _computeLineSpans(args)) + ]); + }); + } + + /** + * @param {Error} err + */ + printError (err) { + this.print([logging_common.RED, logging_common.BOLD, err.toString()]); + } + + /** + * @param {string} url + * @param {number} height + */ + printImg (url, height) { + eventloop.enqueue(() => { + dom.append(this.ccontainer, [ + dom.element('img', [ + pair.create('src', url), + pair.create('height', `${math.round(height * 1.5)}px`) + ]) + ]); + }); + } + + /** + * @param {Node} node + */ + printDom (node) { + eventloop.enqueue(() => { + dom.append(this.ccontainer, [node]); + }); + } + + destroy () { + eventloop.enqueue(() => { + vconsoles.delete(this); + }); + } +} +/* c8 ignore stop */ + +/** + * @param {Element} dom + */ +/* c8 ignore next */ +const createVConsole = (dom) => new VConsole(dom); + +/** + * @param {string} moduleName + * @return {function(...any):void} + */ +const createModuleLogger = (moduleName) => logging_common.createModuleLogger(print, moduleName); + +exports.BLUE = logging_common.BLUE; +exports.BOLD = logging_common.BOLD; +exports.GREEN = logging_common.GREEN; +exports.GREY = logging_common.GREY; +exports.ORANGE = logging_common.ORANGE; +exports.PURPLE = logging_common.PURPLE; +exports.RED = logging_common.RED; +exports.UNBOLD = logging_common.UNBOLD; +exports.UNCOLOR = logging_common.UNCOLOR; +exports.VConsole = VConsole; +exports.createModuleLogger = createModuleLogger; +exports.createVConsole = createVConsole; +exports.group = group; +exports.groupCollapsed = groupCollapsed; +exports.groupEnd = groupEnd; +exports.print = print; +exports.printCanvas = printCanvas; +exports.printDom = printDom; +exports.printError = printError; +exports.printImg = printImg; +exports.printImgBase64 = printImgBase64; +exports.vconsoles = vconsoles; +exports.warn = warn; +//# sourceMappingURL=logging.cjs.map diff --git a/nodejs/node_modules/lib0/dist/logging.cjs.map b/nodejs/node_modules/lib0/dist/logging.cjs.map new file mode 100644 index 00000000..144b1604 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.cjs","sources":["../logging.js"],"sourcesContent":["/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as set from './set.js'\nimport * as pair from './pair.js'\nimport * as dom from './dom.js'\nimport * as json from './json.js'\nimport * as map from './map.js'\nimport * as eventloop from './eventloop.js'\nimport * as math from './math.js'\nimport * as common from './logging.common.js'\n\nexport { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from './logging.common.js'\n\n/**\n * @type {Object>}\n */\nconst _browserStyleMap = {\n [common.BOLD]: pair.create('font-weight', 'bold'),\n [common.UNBOLD]: pair.create('font-weight', 'normal'),\n [common.BLUE]: pair.create('color', 'blue'),\n [common.GREEN]: pair.create('color', 'green'),\n [common.GREY]: pair.create('color', 'grey'),\n [common.RED]: pair.create('color', 'red'),\n [common.PURPLE]: pair.create('color', 'purple'),\n [common.ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n [common.UNCOLOR]: pair.create('color', 'black')\n}\n\n/**\n * @param {Array} args\n * @return {Array}\n */\n/* c8 ignore start */\nconst computeBrowserLoggingArgs = (args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const styles = []\n const currentStyle = map.create()\n /**\n * @type {Array}\n */\n let logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg === undefined) {\n break\n }\n if (arg.constructor === String || arg.constructor === Number) {\n const style = dom.mapToStyleString(currentStyle)\n if (i > 0 || style.length > 0) {\n strBuilder.push('%c' + arg)\n styles.push(style)\n } else {\n strBuilder.push(arg)\n }\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n logArgs = styles\n logArgs.unshift(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst computeLoggingArgs = env.supportsColor\n ? computeBrowserLoggingArgs\n : common.computeNoColorLoggingArgs\n/* c8 ignore stop */\n\n/**\n * @param {Array} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.print(args))\n}\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n args.unshift(common.ORANGE)\n vconsoles.forEach((vc) => vc.print(args))\n}\n/* c8 ignore stop */\n\n/**\n * @param {Error} err\n */\n/* c8 ignore start */\nexport const printError = (err) => {\n console.error(err)\n vconsoles.forEach((vc) => vc.printError(err))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\n/* c8 ignore start */\nexport const printImg = (url, height) => {\n if (env.isBrowser) {\n console.log(\n '%c ',\n `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`\n )\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n }\n vconsoles.forEach((vc) => vc.printImg(url, height))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} base64\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printImgBase64 = (base64, height) =>\n printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array} args\n */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.group(args))\n}\n\n/**\n * @param {Array} args\n */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.groupCollapsed(args))\n}\n\nexport const groupEnd = () => {\n console.groupEnd()\n /* c8 ignore next */\n vconsoles.forEach((vc) => vc.groupEnd())\n}\n\n/**\n * @param {function():Node} createNode\n */\n/* c8 ignore next 2 */\nexport const printDom = (createNode) =>\n vconsoles.forEach((vc) => vc.printDom(createNode()))\n\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printCanvas = (canvas, height) =>\n printImg(canvas.toDataURL(), height)\n\nexport const vconsoles = set.create()\n\n/**\n * @param {Array} args\n * @return {Array}\n */\n/* c8 ignore start */\nconst _computeLineSpans = (args) => {\n const spans = []\n const currentStyle = new Map()\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n let arg = args[i]\n // @ts-ignore\n const style = _browserStyleMap[arg]\n if (style !== undefined) {\n currentStyle.set(style.left, style.right)\n } else {\n if (arg === undefined) {\n arg = 'undefined '\n }\n if (arg.constructor === String || arg.constructor === Number) {\n // @ts-ignore\n const span = dom.element('span', [\n pair.create('style', dom.mapToStyleString(currentStyle))\n ], [dom.text(arg.toString())])\n if (span.innerHTML === '') {\n span.innerHTML = ' '\n }\n spans.push(span)\n } else {\n break\n }\n }\n }\n // append the rest\n for (; i < args.length; i++) {\n let content = args[i]\n if (!(content instanceof Symbol)) {\n if (content.constructor !== String && content.constructor !== Number) {\n content = ' ' + json.stringify(content) + ' '\n }\n spans.push(\n dom.element('span', [], [dom.text(/** @type {string} */ (content))])\n )\n }\n }\n return spans\n}\n/* c8 ignore stop */\n\nconst lineStyle =\n 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* c8 ignore start */\nexport class VConsole {\n /**\n * @param {Element} dom\n */\n constructor (dom) {\n this.dom = dom\n /**\n * @type {Element}\n */\n this.ccontainer = this.dom\n this.depth = 0\n vconsoles.add(this)\n }\n\n /**\n * @param {Array} args\n * @param {boolean} collapsed\n */\n group (args, collapsed = false) {\n eventloop.enqueue(() => {\n const triangleDown = dom.element('span', [\n pair.create('hidden', collapsed),\n pair.create('style', 'color:grey;font-size:120%;')\n ], [dom.text('▼')])\n const triangleRight = dom.element('span', [\n pair.create('hidden', !collapsed),\n pair.create('style', 'color:grey;font-size:125%;')\n ], [dom.text('▶')])\n const content = dom.element(\n 'div',\n [pair.create(\n 'style',\n `${lineStyle};padding-left:${this.depth * 10}px`\n )],\n [triangleDown, triangleRight, dom.text(' ')].concat(\n _computeLineSpans(args)\n )\n )\n const nextContainer = dom.element('div', [\n pair.create('hidden', collapsed)\n ])\n const nextLine = dom.element('div', [], [content, nextContainer])\n dom.append(this.ccontainer, [nextLine])\n this.ccontainer = nextContainer\n this.depth++\n // when header is clicked, collapse/uncollapse container\n dom.addEventListener(content, 'click', (_event) => {\n nextContainer.toggleAttribute('hidden')\n triangleDown.toggleAttribute('hidden')\n triangleRight.toggleAttribute('hidden')\n })\n })\n }\n\n /**\n * @param {Array} args\n */\n groupCollapsed (args) {\n this.group(args, true)\n }\n\n groupEnd () {\n eventloop.enqueue(() => {\n if (this.depth > 0) {\n this.depth--\n // @ts-ignore\n this.ccontainer = this.ccontainer.parentElement.parentElement\n }\n })\n }\n\n /**\n * @param {Array} args\n */\n print (args) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [\n dom.element('div', [\n pair.create(\n 'style',\n `${lineStyle};padding-left:${this.depth * 10}px`\n )\n ], _computeLineSpans(args))\n ])\n })\n }\n\n /**\n * @param {Error} err\n */\n printError (err) {\n this.print([common.RED, common.BOLD, err.toString()])\n }\n\n /**\n * @param {string} url\n * @param {number} height\n */\n printImg (url, height) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [\n dom.element('img', [\n pair.create('src', url),\n pair.create('height', `${math.round(height * 1.5)}px`)\n ])\n ])\n })\n }\n\n /**\n * @param {Node} node\n */\n printDom (node) {\n eventloop.enqueue(() => {\n dom.append(this.ccontainer, [node])\n })\n }\n\n destroy () {\n eventloop.enqueue(() => {\n vconsoles.delete(this)\n })\n }\n}\n/* c8 ignore stop */\n\n/**\n * @param {Element} dom\n */\n/* c8 ignore next */\nexport const createVConsole = (dom) => new VConsole(dom)\n\n/**\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = (moduleName) => common.createModuleLogger(print, moduleName)\n"],"names":["common.BOLD","pair.create","common.UNBOLD","common.BLUE","common.GREEN","common.GREY","common.RED","common.PURPLE","common.ORANGE","common.UNCOLOR","map.create","dom.mapToStyleString","env.supportsColor","common.computeNoColorLoggingArgs","env.isBrowser","set.create","dom.element","dom.text","json.stringify","eventloop.enqueue","dom.append","dom.addEventListener","math.round","common.createModuleLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AAaA;AACA;AACA;AACA;AACA,MAAM,gBAAgB,GAAG;AACzB,EAAE,CAAC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C;AACjC,UAAUA,WAAW,CAAC,QAAQ,EAAE,CAAC,EAAEqB,UAAU,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;AAChE,SAAS,CAAC;AACV,OAAO,EAAC;AACR,KAAK,EAAC;AACN,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE,QAAQ,CAAC,CAAC,IAAI,EAAE;AAClB,IAAIH,iBAAiB,CAAC,MAAM;AAC5B,MAAMC,UAAU,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC,EAAC;AACzC,KAAK,EAAC;AACN,GAAG;AACH;AACA,EAAE,OAAO,CAAC,GAAG;AACb,IAAID,iBAAiB,CAAC,MAAM;AAC5B,MAAM,SAAS,CAAC,MAAM,CAAC,IAAI,EAAC;AAC5B,KAAK,EAAC;AACN,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,GAAG,KAAK,IAAI,QAAQ,CAAC,GAAG,EAAC;AACxD;AACA;AACA;AACA;AACA;AACY,MAAC,kBAAkB,GAAG,CAAC,UAAU,KAAKI,iCAAyB,CAAC,KAAK,EAAE,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.common.cjs b/nodejs/node_modules/lib0/dist/logging.common.cjs new file mode 100644 index 00000000..e9e90bc5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.common.cjs @@ -0,0 +1,115 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var symbol = require('./symbol-c5caa724.cjs'); +var time = require('./time-bc2081b9.cjs'); +var environment = require('./environment-f4d7c3e5.cjs'); +var _function = require('./function-314fdc56.cjs'); +var json = require('./json-092190a1.cjs'); +require('./metric.cjs'); +require('./math-08e068f9.cjs'); +require('./map-0dabcc55.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./object-fecf6a7b.cjs'); + +const BOLD = symbol.create(); +const UNBOLD = symbol.create(); +const BLUE = symbol.create(); +const GREY = symbol.create(); +const GREEN = symbol.create(); +const RED = symbol.create(); +const PURPLE = symbol.create(); +const ORANGE = symbol.create(); +const UNCOLOR = symbol.create(); + +/* c8 ignore start */ +/** + * @param {Array} args + * @return {Array} + */ +const computeNoColorLoggingArgs = args => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]()); + } + const logArgs = []; + // try with formatting until we find something unsupported + let i = 0; + for (; i < args.length; i++) { + const arg = args[i]; + if (arg === undefined) ; else if (arg.constructor === String || arg.constructor === Number) ; else if (arg.constructor === Object) { + logArgs.push(JSON.stringify(arg)); + } + } + return logArgs +}; +/* c8 ignore stop */ + +const loggingColors = [GREEN, PURPLE, ORANGE, BLUE]; +let nextColor = 0; +let lastLoggingTime = time.getUnixTime(); + +/* c8 ignore start */ +/** + * @param {function(...any):void} _print + * @param {string} moduleName + * @return {function(...any):void} + */ +const createModuleLogger = (_print, moduleName) => { + const color = loggingColors[nextColor]; + const debugRegexVar = environment.getVariable('log'); + const doLogging = debugRegexVar !== null && + (debugRegexVar === '*' || debugRegexVar === 'true' || + new RegExp(debugRegexVar, 'gi').test(moduleName)); + nextColor = (nextColor + 1) % loggingColors.length; + moduleName += ': '; + return !doLogging + ? _function.nop + : (...args) => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = args[0](); + } + const timeNow = time.getUnixTime(); + const timeDiff = timeNow - lastLoggingTime; + lastLoggingTime = timeNow; + _print( + color, + moduleName, + UNCOLOR, + ...args.map((arg) => { + if (arg != null && arg.constructor === Uint8Array) { + arg = Array.from(arg); + } + const t = typeof arg; + switch (t) { + case 'string': + case 'symbol': + return arg + default: { + return json.stringify(arg) + } + } + }), + color, + ' +' + timeDiff + 'ms' + ); + } +}; +/* c8 ignore stop */ + +exports.BLUE = BLUE; +exports.BOLD = BOLD; +exports.GREEN = GREEN; +exports.GREY = GREY; +exports.ORANGE = ORANGE; +exports.PURPLE = PURPLE; +exports.RED = RED; +exports.UNBOLD = UNBOLD; +exports.UNCOLOR = UNCOLOR; +exports.computeNoColorLoggingArgs = computeNoColorLoggingArgs; +exports.createModuleLogger = createModuleLogger; +//# sourceMappingURL=logging.common.cjs.map diff --git a/nodejs/node_modules/lib0/dist/logging.common.cjs.map b/nodejs/node_modules/lib0/dist/logging.common.cjs.map new file mode 100644 index 00000000..5f870635 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.common.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.common.cjs","sources":["../logging.common.js"],"sourcesContent":["import * as symbol from './symbol.js'\nimport * as time from './time.js'\nimport * as env from './environment.js'\nimport * as func from './function.js'\nimport * as json from './json.js'\n\nexport const BOLD = symbol.create()\nexport const UNBOLD = symbol.create()\nexport const BLUE = symbol.create()\nexport const GREY = symbol.create()\nexport const GREEN = symbol.create()\nexport const RED = symbol.create()\nexport const PURPLE = symbol.create()\nexport const ORANGE = symbol.create()\nexport const UNCOLOR = symbol.create()\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n * @return {Array}\n */\nexport const computeNoColorLoggingArgs = args => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n if (arg === undefined) {\n strBuilder.push('undefined')\n } else if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else if (arg.constructor === Object) {\n logArgs.push(JSON.stringify(arg))\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = time.getUnixTime()\n\n/* c8 ignore start */\n/**\n * @param {function(...any):void} _print\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nexport const createModuleLogger = (_print, moduleName) => {\n const color = loggingColors[nextColor]\n const debugRegexVar = env.getVariable('log')\n const doLogging = debugRegexVar !== null &&\n (debugRegexVar === '*' || debugRegexVar === 'true' ||\n new RegExp(debugRegexVar, 'gi').test(moduleName))\n nextColor = (nextColor + 1) % loggingColors.length\n moduleName += ': '\n return !doLogging\n ? func.nop\n : (...args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = args[0]()\n }\n const timeNow = time.getUnixTime()\n const timeDiff = timeNow - lastLoggingTime\n lastLoggingTime = timeNow\n _print(\n color,\n moduleName,\n UNCOLOR,\n ...args.map((arg) => {\n if (arg != null && arg.constructor === Uint8Array) {\n arg = Array.from(arg)\n }\n const t = typeof arg\n switch (t) {\n case 'string':\n case 'symbol':\n return arg\n default: {\n return json.stringify(arg)\n }\n }\n }),\n color,\n ' +' + timeDiff + 'ms'\n )\n }\n}\n/* c8 ignore stop */\n"],"names":["symbol.create","time.getUnixTime","env.getVariable","func.nop","json.stringify"],"mappings":";;;;;;;;;;;;;;;;;;;AAMY,MAAC,IAAI,GAAGA,aAAa,GAAE;AACvB,MAAC,MAAM,GAAGA,aAAa,GAAE;AACzB,MAAC,IAAI,GAAGA,aAAa,GAAE;AACvB,MAAC,IAAI,GAAGA,aAAa,GAAE;AACvB,MAAC,KAAK,GAAGA,aAAa,GAAE;AACxB,MAAC,GAAG,GAAGA,aAAa,GAAE;AACtB,MAAC,MAAM,GAAGA,aAAa,GAAE;AACzB,MAAC,MAAM,GAAGA,aAAa,GAAE;AACzB,MAAC,OAAO,GAAGA,aAAa,GAAE;AACtC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,yBAAyB,GAAG,IAAI,IAAI;AACjD,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,WAAW,KAAK,QAAQ,EAAE;AAC9D,IAAI,IAAI,gFAAgF,CAAC,IAAI,EAAE,C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OAAO,CAAC,SAAS;AACnB,MAAMC,aAAQ;AACd,MAAM,CAAC,GAAG,IAAI,KAAK;AACnB,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,WAAW,KAAK,QAAQ,EAAE;AACpE,UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,GAAE;AAC1B,SAAS;AACT,QAAQ,MAAM,OAAO,GAAGF,gBAAgB,GAAE;AAC1C,QAAQ,MAAM,QAAQ,GAAG,OAAO,GAAG,gBAAe;AAClD,QAAQ,eAAe,GAAG,QAAO;AACjC,QAAQ,MAAM;AACd,UAAU,KAAK;AACf,UAAU,UAAU;AACpB,UAAU,OAAO;AACjB,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK;AAC/B,YAAY,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC,WAAW,KAAK,UAAU,EAAE;AAC/D,cAAc,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAAC;AACnC,aAAa;AACb,YAAY,MAAM,CAAC,GAAG,OAAO,IAAG;AAChC,YAAY,QAAQ,CAAC;AACrB,cAAc,KAAK,QAAQ,CAAC;AAC5B,cAAc,KAAK,QAAQ;AAC3B,gBAAgB,OAAO,GAAG;AAC1B,cAAc,SAAS;AACvB,gBAAgB,OAAOG,cAAc,CAAC,GAAG,CAAC;AAC1C,eAAe;AACf,aAAa;AACb,WAAW,CAAC;AACZ,UAAU,KAAK;AACf,UAAU,IAAI,GAAG,QAAQ,GAAG,IAAI;AAChC,UAAS;AACT,OAAO;AACP,EAAC;AACD;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.common.d.ts b/nodejs/node_modules/lib0/dist/logging.common.d.ts new file mode 100644 index 00000000..23e47917 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.common.d.ts @@ -0,0 +1,12 @@ +export const BOLD: symbol; +export const UNBOLD: symbol; +export const BLUE: symbol; +export const GREY: symbol; +export const GREEN: symbol; +export const RED: symbol; +export const PURPLE: symbol; +export const ORANGE: symbol; +export const UNCOLOR: symbol; +export function computeNoColorLoggingArgs(args: Array any)>): Array; +export function createModuleLogger(_print: (...args: any[]) => void, moduleName: string): (...args: any[]) => void; +//# sourceMappingURL=logging.common.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.common.d.ts.map b/nodejs/node_modules/lib0/dist/logging.common.d.ts.map new file mode 100644 index 00000000..8314a6d0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.common.d.ts","sourceRoot":"","sources":["../logging.common.js"],"names":[],"mappings":"AAMA,0BAAmC;AACnC,4BAAqC;AACrC,0BAAmC;AACnC,0BAAmC;AACnC,2BAAoC;AACpC,yBAAkC;AAClC,4BAAqC;AACrC,4BAAqC;AACrC,6BAAsC;AAO/B,gDAHI,MAAM,SAAS,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,UAAY,GAAG,CAAA,CAAC,GAC1D,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,CAqBtC;AAaM,qDAJgB,GAAG,OAAE,IAAI,cACrB,MAAM,aACO,GAAG,OAAE,IAAI,CAyChC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.d.ts b/nodejs/node_modules/lib0/dist/logging.d.ts new file mode 100644 index 00000000..a768a17d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.d.ts @@ -0,0 +1,55 @@ +export function print(...args: Array): void; +export function warn(...args: Array): void; +export function printError(err: Error): void; +export function printImg(url: string, height: number): void; +export function printImgBase64(base64: string, height: number): void; +export function group(...args: Array): void; +export function groupCollapsed(...args: Array): void; +export function groupEnd(): void; +export function printDom(createNode: () => Node): void; +export function printCanvas(canvas: HTMLCanvasElement, height: number): void; +export const vconsoles: Set; +export class VConsole { + /** + * @param {Element} dom + */ + constructor(dom: Element); + dom: Element; + /** + * @type {Element} + */ + ccontainer: Element; + depth: number; + /** + * @param {Array} args + * @param {boolean} collapsed + */ + group(args: Array, collapsed?: boolean): void; + /** + * @param {Array} args + */ + groupCollapsed(args: Array): void; + groupEnd(): void; + /** + * @param {Array} args + */ + print(args: Array): void; + /** + * @param {Error} err + */ + printError(err: Error): void; + /** + * @param {string} url + * @param {number} height + */ + printImg(url: string, height: number): void; + /** + * @param {Node} node + */ + printDom(node: Node): void; + destroy(): void; +} +export function createVConsole(dom: Element): VConsole; +export function createModuleLogger(moduleName: string): (...args: any[]) => void; +export { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from "./logging.common.js"; +//# sourceMappingURL=logging.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.d.ts.map b/nodejs/node_modules/lib0/dist/logging.d.ts.map new file mode 100644 index 00000000..3c55c946 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.d.ts","sourceRoot":"","sources":["../logging.js"],"names":[],"mappings":"AAmGO,+BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAMM,8BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAOM,gCAHI,KAAK,QAMf;AAQM,8BAJI,MAAM,UACN,MAAM,QAYhB;AAQM,uCAJI,MAAM,UACN,MAAM,QAIoC;AAK9C,+BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAKM,wCAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAEM,iCAIN;AAMM,2CAHe,IAAI,QAI4B;AAO/C,oCAJI,iBAAiB,UACjB,MAAM,QAIqB;AAEtC,iCAAqC;AAwDrC;IACE;;OAEG;IACH,iBAFW,OAAO,EAUjB;IAPC,aAAc;IACd;;OAEG;IACH,YAFU,OAAO,CAES;IAC1B,cAAc;IAIhB;;;OAGG;IACH,YAHW,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,cAClC,OAAO,QAoCjB;IAED;;OAEG;IACH,qBAFW,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAI5C;IAED,iBAQC;IAED;;OAEG;IACH,YAFW,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAa5C;IAED;;OAEG;IACH,gBAFW,KAAK,QAIf;IAED;;;OAGG;IACH,cAHW,MAAM,UACN,MAAM,QAWhB;IAED;;OAEG;IACH,eAFW,IAAI,QAMd;IAED,gBAIC;CACF;AAOM,oCAHI,OAAO,YAGsC;AAMjD,+CAHI,MAAM,aACO,GAAG,OAAE,IAAI,CAE6D"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.node.cjs b/nodejs/node_modules/lib0/dist/logging.node.cjs new file mode 100644 index 00000000..b884512e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.node.cjs @@ -0,0 +1,202 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var environment = require('./environment-f4d7c3e5.cjs'); +var logging_common = require('./logging.common.cjs'); +require('./map-0dabcc55.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./symbol-c5caa724.cjs'); +require('./time-bc2081b9.cjs'); +require('./metric.cjs'); +require('./math-08e068f9.cjs'); +require('./json-092190a1.cjs'); + +/** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + +const _nodeStyleMap = { + [logging_common.BOLD]: '\u001b[1m', + [logging_common.UNBOLD]: '\u001b[2m', + [logging_common.BLUE]: '\x1b[34m', + [logging_common.GREEN]: '\x1b[32m', + [logging_common.GREY]: '\u001b[37m', + [logging_common.RED]: '\x1b[31m', + [logging_common.PURPLE]: '\x1b[35m', + [logging_common.ORANGE]: '\x1b[38;5;208m', + [logging_common.UNCOLOR]: '\x1b[0m' +}; + +/* c8 ignore start */ +/** + * @param {Array>} args + * @return {Array} + */ +const computeNodeLoggingArgs = (args) => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]()); + } + const strBuilder = []; + const logArgs = []; + // try with formatting until we find something unsupported + let i = 0; + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _nodeStyleMap[arg]; + if (style !== undefined) { + strBuilder.push(style); + } else { + if (arg === undefined) { + break + } else if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg); + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + strBuilder.push('\x1b[0m'); + logArgs.push(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs +}; +/* c8 ignore stop */ + +/* c8 ignore start */ +const computeLoggingArgs = environment.supportsColor + ? computeNodeLoggingArgs + : logging_common.computeNoColorLoggingArgs; +/* c8 ignore stop */ + +/** + * @param {Array} args + */ +const print = (...args) => { + console.log(...computeLoggingArgs(args)); +}; + +/* c8 ignore start */ +/** + * @param {Array} args + */ +const warn = (...args) => { + console.warn(...computeLoggingArgs(args)); +}; +/* c8 ignore stop */ + +/** + * @param {Error} err + */ +/* c8 ignore start */ +const printError = (err) => { + console.error(err); +}; +/* c8 ignore stop */ + +/** + * @param {string} _url image location + * @param {number} _height height of the image in pixel + */ +/* c8 ignore start */ +const printImg = (_url, _height) => { + // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`) +}; +/* c8 ignore stop */ + +/** + * @param {string} base64 + * @param {number} height + */ +/* c8 ignore next 2 */ +const printImgBase64 = (base64, height) => + printImg(); + +/** + * @param {Array} args + */ +/* c8 ignore next 3 */ +const group = (...args) => { + console.group(...computeLoggingArgs(args)); +}; + +/** + * @param {Array} args + */ +/* c8 ignore next 3 */ +const groupCollapsed = (...args) => { + console.groupCollapsed(...computeLoggingArgs(args)); +}; + +/* c8 ignore next 3 */ +const groupEnd = () => { + console.groupEnd(); +}; + +/** + * @param {function():Node} _createNode + */ +/* c8 ignore next 2 */ +const printDom = (_createNode) => {}; + +/** + * @param {HTMLCanvasElement} canvas + * @param {number} height + */ +/* c8 ignore next 2 */ +const printCanvas = (canvas, height) => + printImg(canvas.toDataURL()); + +/** + * @param {Element} _dom + */ +/* c8 ignore next */ +const createVConsole = (_dom) => {}; + +/** + * @param {string} moduleName + * @return {function(...any):void} + */ +/* c8 ignore next */ +const createModuleLogger = (moduleName) => logging_common.createModuleLogger(print, moduleName); + +exports.BLUE = logging_common.BLUE; +exports.BOLD = logging_common.BOLD; +exports.GREEN = logging_common.GREEN; +exports.GREY = logging_common.GREY; +exports.ORANGE = logging_common.ORANGE; +exports.PURPLE = logging_common.PURPLE; +exports.RED = logging_common.RED; +exports.UNBOLD = logging_common.UNBOLD; +exports.UNCOLOR = logging_common.UNCOLOR; +exports.createModuleLogger = createModuleLogger; +exports.createVConsole = createVConsole; +exports.group = group; +exports.groupCollapsed = groupCollapsed; +exports.groupEnd = groupEnd; +exports.print = print; +exports.printCanvas = printCanvas; +exports.printDom = printDom; +exports.printError = printError; +exports.printImg = printImg; +exports.printImgBase64 = printImgBase64; +exports.warn = warn; +//# sourceMappingURL=logging.node.cjs.map diff --git a/nodejs/node_modules/lib0/dist/logging.node.cjs.map b/nodejs/node_modules/lib0/dist/logging.node.cjs.map new file mode 100644 index 00000000..b4a3d684 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.node.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.node.cjs","sources":["../logging.node.js"],"sourcesContent":["/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\nimport * as env from './environment.js'\nimport * as common from './logging.common.js'\n\nexport { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from './logging.common.js'\n\nconst _nodeStyleMap = {\n [common.BOLD]: '\\u001b[1m',\n [common.UNBOLD]: '\\u001b[2m',\n [common.BLUE]: '\\x1b[34m',\n [common.GREEN]: '\\x1b[32m',\n [common.GREY]: '\\u001b[37m',\n [common.RED]: '\\x1b[31m',\n [common.PURPLE]: '\\x1b[35m',\n [common.ORANGE]: '\\x1b[38;5;208m',\n [common.UNCOLOR]: '\\x1b[0m'\n}\n\n/* c8 ignore start */\n/**\n * @param {Array>} args\n * @return {Array}\n */\nconst computeNodeLoggingArgs = (args) => {\n if (args.length === 1 && args[0]?.constructor === Function) {\n args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]())\n }\n const strBuilder = []\n const logArgs = []\n // try with formatting until we find something unsupported\n let i = 0\n for (; i < args.length; i++) {\n const arg = args[i]\n // @ts-ignore\n const style = _nodeStyleMap[arg]\n if (style !== undefined) {\n strBuilder.push(style)\n } else {\n if (arg === undefined) {\n break\n } else if (arg.constructor === String || arg.constructor === Number) {\n strBuilder.push(arg)\n } else {\n break\n }\n }\n }\n if (i > 0) {\n // create logArgs with what we have so far\n strBuilder.push('\\x1b[0m')\n logArgs.push(strBuilder.join(''))\n }\n // append the rest\n for (; i < args.length; i++) {\n const arg = args[i]\n if (!(arg instanceof Symbol)) {\n logArgs.push(arg)\n }\n }\n return logArgs\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst computeLoggingArgs = env.supportsColor\n ? computeNodeLoggingArgs\n : common.computeNoColorLoggingArgs\n/* c8 ignore stop */\n\n/**\n * @param {Array} args\n */\nexport const print = (...args) => {\n console.log(...computeLoggingArgs(args))\n}\n\n/* c8 ignore start */\n/**\n * @param {Array} args\n */\nexport const warn = (...args) => {\n console.warn(...computeLoggingArgs(args))\n}\n/* c8 ignore stop */\n\n/**\n * @param {Error} err\n */\n/* c8 ignore start */\nexport const printError = (err) => {\n console.error(err)\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} _url image location\n * @param {number} _height height of the image in pixel\n */\n/* c8 ignore start */\nexport const printImg = (_url, _height) => {\n // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} base64\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printImgBase64 = (base64, height) =>\n printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array} args\n */\n/* c8 ignore next 3 */\nexport const group = (...args) => {\n console.group(...computeLoggingArgs(args))\n}\n\n/**\n * @param {Array} args\n */\n/* c8 ignore next 3 */\nexport const groupCollapsed = (...args) => {\n console.groupCollapsed(...computeLoggingArgs(args))\n}\n\n/* c8 ignore next 3 */\nexport const groupEnd = () => {\n console.groupEnd()\n}\n\n/**\n * @param {function():Node} _createNode\n */\n/* c8 ignore next 2 */\nexport const printDom = (_createNode) => {}\n\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\n/* c8 ignore next 2 */\nexport const printCanvas = (canvas, height) =>\n printImg(canvas.toDataURL(), height)\n\n/**\n * @param {Element} _dom\n */\n/* c8 ignore next */\nexport const createVConsole = (_dom) => {}\n\n/**\n * @param {string} moduleName\n * @return {function(...any):void}\n */\n/* c8 ignore next */\nexport const createModuleLogger = (moduleName) => common.createModuleLogger(print, moduleName)\n"],"names":["common.BOLD","common.UNBOLD","common.BLUE","common.GREEN","common.GREY","common.RED","common.PURPLE","common.ORANGE","common.UNCOLOR","env.supportsColor","common.computeNoColorLoggingArgs","common.createModuleLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AAMA;AACA,MAAM,aAAa,GAAG;AACtB,EAAE,CAACA,mBAAW,GAAG,WAAW;AAC5B,EAAE,CAACC,qBAAa,GAAG,WAAW;AAC9B,EAAE,CAACC,mBAAW,GAAG,UAAU;A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C,KAAK,GAAG,CAAC,GAAG,IAAI,KAAK;AAClC,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,kBAAkB,CAAC,IAAI,CAAC,EAAC;AAC5C,EAAC;AACD;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,GAAG,IAAI,KAAK;AAC3C,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC,IAAI,CAAC,EAAC;AACrD,EAAC;AACD;AACA;AACY,MAAC,QAAQ,GAAG,MAAM;AAC9B,EAAE,OAAO,CAAC,QAAQ,GAAE;AACpB,EAAC;AACD;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,WAAW,KAAK,GAAE;AAC3C;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM;AAC1C,EAAE,QAAQ,CAAC,MAAM,CAAC,SAAS,EAAU,EAAC;AACtC;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,IAAI,KAAK,GAAE;AAC1C;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,kBAAkB,GAAG,CAAC,UAAU,KAAKC,iCAAyB,CAAC,KAAK,EAAE,UAAU;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.node.d.ts b/nodejs/node_modules/lib0/dist/logging.node.d.ts new file mode 100644 index 00000000..69edeebd --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.node.d.ts @@ -0,0 +1,14 @@ +export function print(...args: Array): void; +export function warn(...args: Array): void; +export function printError(err: Error): void; +export function printImg(_url: string, _height: number): void; +export function printImgBase64(base64: string, height: number): void; +export function group(...args: Array): void; +export function groupCollapsed(...args: Array): void; +export function groupEnd(): void; +export function printDom(_createNode: () => Node): void; +export function printCanvas(canvas: HTMLCanvasElement, height: number): void; +export function createVConsole(_dom: Element): void; +export function createModuleLogger(moduleName: string): (...args: any[]) => void; +export { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from "./logging.common.js"; +//# sourceMappingURL=logging.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.node.d.ts.map b/nodejs/node_modules/lib0/dist/logging.node.d.ts.map new file mode 100644 index 00000000..e18c5fbf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.node.d.ts","sourceRoot":"","sources":["../logging.node.js"],"names":[],"mappings":"AA6EO,+BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,SAAS,CAAC,QAItD;AAMM,8BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAI5C;AAOM,gCAHI,KAAK,QAKf;AAQM,+BAJI,MAAM,WACN,MAAM,QAKhB;AAQM,uCAJI,MAAM,UACN,MAAM,QAIoC;AAM9C,+BAHI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAK5C;AAMM,wCAHI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAK5C;AAGM,iCAEN;AAMM,4CAHe,IAAI,QAGiB;AAOpC,oCAJI,iBAAiB,UACjB,MAAM,QAIqB;AAM/B,qCAHI,OAAO,QAGwB;AAOnC,+CAJI,MAAM,aACO,GAAG,OAAE,IAAI,CAG6D"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.test.d.ts b/nodejs/node_modules/lib0/dist/logging.test.d.ts new file mode 100644 index 00000000..0bdf3291 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.test.d.ts @@ -0,0 +1,3 @@ +export function testLogging(): void; +export function testModuleLogger(): void; +//# sourceMappingURL=logging.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/logging.test.d.ts.map b/nodejs/node_modules/lib0/dist/logging.test.d.ts.map new file mode 100644 index 00000000..6c437106 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/logging.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.test.d.ts","sourceRoot":"","sources":["../logging.test.js"],"names":[],"mappings":"AAEO,oCAgBN;AAEM,yCAON"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/map-0dabcc55.cjs b/nodejs/node_modules/lib0/dist/map-0dabcc55.cjs new file mode 100644 index 00000000..29e32730 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map-0dabcc55.cjs @@ -0,0 +1,133 @@ +'use strict'; + +/** + * Utility module to work with key-value stores. + * + * @module map + */ + +/** + * Creates a new Map instance. + * + * @function + * @return {Map} + * + * @function + */ +const create = () => new Map(); + +/** + * Copy a Map object into a fresh Map object. + * + * @function + * @template K,V + * @param {Map} m + * @return {Map} + */ +const copy = m => { + const r = create(); + m.forEach((v, k) => { r.set(k, v); }); + return r +}; + +/** + * Get map property. Create T if property is undefined and set T on map. + * + * ```js + * const listeners = map.setIfUndefined(events, 'eventName', set.create) + * listeners.add(listener) + * ``` + * + * @function + * @template {Map} MAP + * @template {MAP extends Map ? function():V : unknown} CF + * @param {MAP} map + * @param {MAP extends Map ? K : unknown} key + * @param {CF} createT + * @return {ReturnType} + */ +const setIfUndefined = (map, key, createT) => { + let set = map.get(key); + if (set === undefined) { + map.set(key, set = createT()); + } + return set +}; + +/** + * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function. + * + * @function + * @template K + * @template V + * @template R + * @param {Map} m + * @param {function(V,K):R} f + * @return {Array} + */ +const map = (m, f) => { + const res = []; + for (const [key, value] of m) { + res.push(f(value, key)); + } + return res +}; + +/** + * Tests whether any key-value pairs pass the test implemented by `f(value, key)`. + * + * @todo should rename to some - similarly to Array.some + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ +const any = (m, f) => { + for (const [key, value] of m) { + if (f(value, key)) { + return true + } + } + return false +}; + +/** + * Tests whether all key-value pairs pass the test implemented by `f(value, key)`. + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ +const all = (m, f) => { + for (const [key, value] of m) { + if (!f(value, key)) { + return false + } + } + return true +}; + +var map$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + create: create, + copy: copy, + setIfUndefined: setIfUndefined, + map: map, + any: any, + all: all +}); + +exports.all = all; +exports.any = any; +exports.copy = copy; +exports.create = create; +exports.map = map; +exports.map$1 = map$1; +exports.setIfUndefined = setIfUndefined; +//# sourceMappingURL=map-0dabcc55.cjs.map diff --git a/nodejs/node_modules/lib0/dist/map-0dabcc55.cjs.map b/nodejs/node_modules/lib0/dist/map-0dabcc55.cjs.map new file mode 100644 index 00000000..d9769ef8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map-0dabcc55.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"map-0dabcc55.cjs","sources":["../map.js"],"sourcesContent":["/**\n * Utility module to work with key-value stores.\n *\n * @module map\n */\n\n/**\n * Creates a new Map instance.\n *\n * @function\n * @return {Map}\n *\n * @function\n */\nexport const create = () => new Map()\n\n/**\n * Copy a Map object into a fresh Map object.\n *\n * @function\n * @template K,V\n * @param {Map} m\n * @return {Map}\n */\nexport const copy = m => {\n const r = create()\n m.forEach((v, k) => { r.set(k, v) })\n return r\n}\n\n/**\n * Get map property. Create T if property is undefined and set T on map.\n *\n * ```js\n * const listeners = map.setIfUndefined(events, 'eventName', set.create)\n * listeners.add(listener)\n * ```\n *\n * @function\n * @template {Map} MAP\n * @template {MAP extends Map ? function():V : unknown} CF\n * @param {MAP} map\n * @param {MAP extends Map ? K : unknown} key\n * @param {CF} createT\n * @return {ReturnType}\n */\nexport const setIfUndefined = (map, key, createT) => {\n let set = map.get(key)\n if (set === undefined) {\n map.set(key, set = createT())\n }\n return set\n}\n\n/**\n * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.\n *\n * @function\n * @template K\n * @template V\n * @template R\n * @param {Map} m\n * @param {function(V,K):R} f\n * @return {Array}\n */\nexport const map = (m, f) => {\n const res = []\n for (const [key, value] of m) {\n res.push(f(value, key))\n }\n return res\n}\n\n/**\n * Tests whether any key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @todo should rename to some - similarly to Array.some\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const any = (m, f) => {\n for (const [key, value] of m) {\n if (f(value, key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Tests whether all key-value pairs pass the test implemented by `f(value, key)`.\n *\n * @function\n * @template K\n * @template V\n * @param {Map} m\n * @param {function(V,K):boolean} f\n * @return {boolean}\n */\nexport const all = (m, f) => {\n for (const [key, value] of m) {\n if (!f(value, key)) {\n return false\n }\n }\n return true\n}\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,CAAC,IAAI;AACzB,EAAE,MAAM,CAAC,GAAG,MAAM,GAAE;AACpB,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAC,EAAE,EAAC;AACtC,EAAE,OAAO,CAAC;AACV,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,KAAK;AACrD,EAAE,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AACxB,EAAE,IAAI,GAAG,KAAK,SAAS,EAAE;AACzB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,EAAE,EAAC;AACjC,GAAG;AACH,EAAE,OAAO,GAAG;AACZ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK;AAC7B,EAAE,MAAM,GAAG,GAAG,GAAE;AAChB,EAAE,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE;AAChC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,GAAG,CAAC,EAAC;AAC3B,GAAG;AACH,EAAE,OAAO,GAAG;AACZ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK;AAC7B,EAAE,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE;AAChC,IAAI,IAAI,CAAC,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE;AACvB,MAAM,OAAO,IAAI;AACjB,KAAK;AACL,GAAG;AACH,EAAE,OAAO,KAAK;AACd,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK;AAC7B,EAAE,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE;AAChC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE;AACxB,MAAM,OAAO,KAAK;AAClB,KAAK;AACL,GAAG;AACH,EAAE,OAAO,IAAI;AACb;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/map.cjs b/nodejs/node_modules/lib0/dist/map.cjs new file mode 100644 index 00000000..51d90779 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map.cjs @@ -0,0 +1,15 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var map = require('./map-0dabcc55.cjs'); + + + +exports.all = map.all; +exports.any = map.any; +exports.copy = map.copy; +exports.create = map.create; +exports.map = map.map; +exports.setIfUndefined = map.setIfUndefined; +//# sourceMappingURL=map.cjs.map diff --git a/nodejs/node_modules/lib0/dist/map.cjs.map b/nodejs/node_modules/lib0/dist/map.cjs.map new file mode 100644 index 00000000..26c68a03 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"map.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/map.d.ts b/nodejs/node_modules/lib0/dist/map.d.ts new file mode 100644 index 00000000..da32bdd3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map.d.ts @@ -0,0 +1,7 @@ +export function create(): Map; +export function copy(m: Map): Map; +export function setIfUndefined, CF extends MAP extends Map ? () => V : unknown>(map: MAP, key: MAP extends Map ? K : unknown, createT: CF): ReturnType; +export function map(m: Map, f: (arg0: V, arg1: K) => R): R[]; +export function any(m: Map, f: (arg0: V, arg1: K) => boolean): boolean; +export function all(m: Map, f: (arg0: V, arg1: K) => boolean): boolean; +//# sourceMappingURL=map.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/map.d.ts.map b/nodejs/node_modules/lib0/dist/map.d.ts.map new file mode 100644 index 00000000..88b01e68 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../map.js"],"names":[],"mappings":"AAcO,0BAJK,IAAI,GAAG,EAAE,GAAG,CAAC,CAIY;AAU9B,oDAIN;AAkBM,iNAMN;AAaM,4EAMN;AAcM,iEAHkB,OAAO,GACpB,OAAO,CASlB;AAYM,iEAHkB,OAAO,GACpB,OAAO,CASlB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/map.test.d.ts b/nodejs/node_modules/lib0/dist/map.test.d.ts new file mode 100644 index 00000000..ca8dbcc5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map.test.d.ts @@ -0,0 +1,4 @@ +export function testMap(_tc: t.TestCase): void; +export function testTypeDefinitions(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=map.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/map.test.d.ts.map b/nodejs/node_modules/lib0/dist/map.test.d.ts.map new file mode 100644 index 00000000..a99e5958 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/map.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.test.d.ts","sourceRoot":"","sources":["../map.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QAsBpB;AAKM,yCAFI,EAAE,QAAQ,QAwBpB;mBApDkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/math-08e068f9.cjs b/nodejs/node_modules/lib0/dist/math-08e068f9.cjs new file mode 100644 index 00000000..710809a1 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math-08e068f9.cjs @@ -0,0 +1,101 @@ +'use strict'; + +/** + * Common Math expressions. + * + * @module math + */ + +const floor = Math.floor; +const ceil = Math.ceil; +const abs = Math.abs; +const imul = Math.imul; +const round = Math.round; +const log10 = Math.log10; +const log2 = Math.log2; +const log = Math.log; +const sqrt = Math.sqrt; + +/** + * @function + * @param {number} a + * @param {number} b + * @return {number} The sum of a and b + */ +const add = (a, b) => a + b; + +/** + * @function + * @param {number} a + * @param {number} b + * @return {number} The smaller element of a and b + */ +const min = (a, b) => a < b ? a : b; + +/** + * @function + * @param {number} a + * @param {number} b + * @return {number} The bigger element of a and b + */ +const max = (a, b) => a > b ? a : b; + +const isNaN = Number.isNaN; + +const pow = Math.pow; +/** + * Base 10 exponential function. Returns the value of 10 raised to the power of pow. + * + * @param {number} exp + * @return {number} + */ +const exp10 = exp => Math.pow(10, exp); + +const sign = Math.sign; + +/** + * @param {number} n + * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0 + */ +const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0; + +var math = /*#__PURE__*/Object.freeze({ + __proto__: null, + floor: floor, + ceil: ceil, + abs: abs, + imul: imul, + round: round, + log10: log10, + log2: log2, + log: log, + sqrt: sqrt, + add: add, + min: min, + max: max, + isNaN: isNaN, + pow: pow, + exp10: exp10, + sign: sign, + isNegativeZero: isNegativeZero +}); + +exports.abs = abs; +exports.add = add; +exports.ceil = ceil; +exports.exp10 = exp10; +exports.floor = floor; +exports.imul = imul; +exports.isNaN = isNaN; +exports.isNegativeZero = isNegativeZero; +exports.log = log; +exports.log10 = log10; +exports.log2 = log2; +exports.math = math; +exports.max = max; +exports.min = min; +exports.pow = pow; +exports.round = round; +exports.sign = sign; +exports.sqrt = sqrt; +//# sourceMappingURL=math-08e068f9.cjs.map diff --git a/nodejs/node_modules/lib0/dist/math-08e068f9.cjs.map b/nodejs/node_modules/lib0/dist/math-08e068f9.cjs.map new file mode 100644 index 00000000..73d85c63 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math-08e068f9.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"math-08e068f9.cjs","sources":["../math.js"],"sourcesContent":["/**\n * Common Math expressions.\n *\n * @module math\n */\n\nexport const floor = Math.floor\nexport const ceil = Math.ceil\nexport const abs = Math.abs\nexport const imul = Math.imul\nexport const round = Math.round\nexport const log10 = Math.log10\nexport const log2 = Math.log2\nexport const log = Math.log\nexport const sqrt = Math.sqrt\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The sum of a and b\n */\nexport const add = (a, b) => a + b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The smaller element of a and b\n */\nexport const min = (a, b) => a < b ? a : b\n\n/**\n * @function\n * @param {number} a\n * @param {number} b\n * @return {number} The bigger element of a and b\n */\nexport const max = (a, b) => a > b ? a : b\n\nexport const isNaN = Number.isNaN\n\nexport const pow = Math.pow\n/**\n * Base 10 exponential function. Returns the value of 10 raised to the power of pow.\n *\n * @param {number} exp\n * @return {number}\n */\nexport const exp10 = exp => Math.pow(10, exp)\n\nexport const sign = Math.sign\n\n/**\n * @param {number} n\n * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0\n */\nexport const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,IAAI,CAAC,MAAK;AACnB,MAAC,IAAI,GAAG,IAAI,CAAC,KAAI;AACjB,MAAC,GAAG,GAAG,IAAI,CAAC,IAAG;AACf,MAAC,IAAI,GAAG,IAAI,CAAC,KAAI;AACjB,MAAC,KAAK,GAAG,IAAI,CAAC,MAAK;AACnB,MAAC,KAAK,GAAG,IAAI,CAAC,MAAK;AACnB,MAAC,IAAI,GAAG,IAAI,CAAC,KAAI;AACjB,MAAC,GAAG,GAAG,IAAI,CAAC,IAAG;AACf,MAAC,IAAI,GAAG,IAAI,CAAC,KAAI;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,EAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAC;AAC1C;AACY,MAAC,KAAK,GAAG,MAAM,CAAC,MAAK;AACjC;AACY,MAAC,GAAG,GAAG,IAAI,CAAC,IAAG;AAC3B;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,EAAC;AAC7C;AACY,MAAC,IAAI,GAAG,IAAI,CAAC,KAAI;AAC7B;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/math.cjs b/nodejs/node_modules/lib0/dist/math.cjs new file mode 100644 index 00000000..38e55818 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math.cjs @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('./math-08e068f9.cjs'); + + + +exports.abs = math.abs; +exports.add = math.add; +exports.ceil = math.ceil; +exports.exp10 = math.exp10; +exports.floor = math.floor; +exports.imul = math.imul; +exports.isNaN = math.isNaN; +exports.isNegativeZero = math.isNegativeZero; +exports.log = math.log; +exports.log10 = math.log10; +exports.log2 = math.log2; +exports.max = math.max; +exports.min = math.min; +exports.pow = math.pow; +exports.round = math.round; +exports.sign = math.sign; +exports.sqrt = math.sqrt; +//# sourceMappingURL=math.cjs.map diff --git a/nodejs/node_modules/lib0/dist/math.cjs.map b/nodejs/node_modules/lib0/dist/math.cjs.map new file mode 100644 index 00000000..3e597d7f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"math.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/math.d.ts b/nodejs/node_modules/lib0/dist/math.d.ts new file mode 100644 index 00000000..7490f904 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math.d.ts @@ -0,0 +1,23 @@ +/** + * Common Math expressions. + * + * @module math + */ +export const floor: (x: number) => number; +export const ceil: (x: number) => number; +export const abs: (x: number) => number; +export const imul: (x: number, y: number) => number; +export const round: (x: number) => number; +export const log10: (x: number) => number; +export const log2: (x: number) => number; +export const log: (x: number) => number; +export const sqrt: (x: number) => number; +export function add(a: number, b: number): number; +export function min(a: number, b: number): number; +export function max(a: number, b: number): number; +export const isNaN: (number: unknown) => boolean; +export const pow: (x: number, y: number) => number; +export function exp10(exp: number): number; +export const sign: (x: number) => number; +export function isNegativeZero(n: number): boolean; +//# sourceMappingURL=math.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/math.d.ts.map b/nodejs/node_modules/lib0/dist/math.d.ts.map new file mode 100644 index 00000000..428acbb7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"math.d.ts","sourceRoot":"","sources":["../math.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,0CAA+B;AAC/B,yCAA6B;AAC7B,wCAA2B;AAC3B,oDAA6B;AAC7B,0CAA+B;AAC/B,0CAA+B;AAC/B,yCAA6B;AAC7B,wCAA2B;AAC3B,yCAA6B;AAQtB,uBAJI,MAAM,KACN,MAAM,GACL,MAAM,CAEgB;AAQ3B,uBAJI,MAAM,KACN,MAAM,GACL,MAAM,CAEwB;AAQnC,uBAJI,MAAM,KACN,MAAM,GACL,MAAM,CAEwB;AAE1C,iDAAiC;AAEjC,mDAA2B;AAOpB,2BAHI,MAAM,GACL,MAAM,CAE2B;AAE7C,yCAA6B;AAMtB,kCAHI,MAAM,GACL,OAAO,CAE2C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/math.test.d.ts b/nodejs/node_modules/lib0/dist/math.test.d.ts new file mode 100644 index 00000000..ff01d80f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math.test.d.ts @@ -0,0 +1,3 @@ +export function testMath(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=math.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/math.test.d.ts.map b/nodejs/node_modules/lib0/dist/math.test.d.ts.map new file mode 100644 index 00000000..351e4f14 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/math.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"math.test.d.ts","sourceRoot":"","sources":["../math.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QA0BpB;mBA/BkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/metric.cjs b/nodejs/node_modules/lib0/dist/metric.cjs new file mode 100644 index 00000000..12043a3b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/metric.cjs @@ -0,0 +1,83 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('./math-08e068f9.cjs'); + +/** + * Utility module to convert metric values. + * + * @module metric + */ + +const yotta = 1e24; +const zetta = 1e21; +const exa = 1e18; +const peta = 1e15; +const tera = 1e12; +const giga = 1e9; +const mega = 1e6; +const kilo = 1e3; +const hecto = 1e2; +const deca = 10; +const deci = 0.1; +const centi = 0.01; +const milli = 1e-3; +const micro = 1e-6; +const nano = 1e-9; +const pico = 1e-12; +const femto = 1e-15; +const atto = 1e-18; +const zepto = 1e-21; +const yocto = 1e-24; + +const prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; +const prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y']; + +/** + * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }` + * + * @param {number} n + * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds + * @return {{n:number,prefix:string}} + */ +const prefix = (n, baseMultiplier = 0) => { + const nPow = n === 0 ? 0 : math.log10(n); + let mult = 0; + while (nPow < mult * 3 && baseMultiplier > -8) { + baseMultiplier--; + mult--; + } + while (nPow >= 3 + mult * 3 && baseMultiplier < 8) { + baseMultiplier++; + mult++; + } + const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier]; + return { + n: math.round((mult > 0 ? n / math.exp10(mult * 3) : n * math.exp10(mult * -3)) * 1e12) / 1e12, + prefix + } +}; + +exports.atto = atto; +exports.centi = centi; +exports.deca = deca; +exports.deci = deci; +exports.exa = exa; +exports.femto = femto; +exports.giga = giga; +exports.hecto = hecto; +exports.kilo = kilo; +exports.mega = mega; +exports.micro = micro; +exports.milli = milli; +exports.nano = nano; +exports.peta = peta; +exports.pico = pico; +exports.prefix = prefix; +exports.tera = tera; +exports.yocto = yocto; +exports.yotta = yotta; +exports.zepto = zepto; +exports.zetta = zetta; +//# sourceMappingURL=metric.cjs.map diff --git a/nodejs/node_modules/lib0/dist/metric.cjs.map b/nodejs/node_modules/lib0/dist/metric.cjs.map new file mode 100644 index 00000000..7868cc03 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/metric.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"metric.cjs","sources":["../metric.js"],"sourcesContent":["/**\n * Utility module to convert metric values.\n *\n * @module metric\n */\n\nimport * as math from './math.js'\n\nexport const yotta = 1e24\nexport const zetta = 1e21\nexport const exa = 1e18\nexport const peta = 1e15\nexport const tera = 1e12\nexport const giga = 1e9\nexport const mega = 1e6\nexport const kilo = 1e3\nexport const hecto = 1e2\nexport const deca = 10\nexport const deci = 0.1\nexport const centi = 0.01\nexport const milli = 1e-3\nexport const micro = 1e-6\nexport const nano = 1e-9\nexport const pico = 1e-12\nexport const femto = 1e-15\nexport const atto = 1e-18\nexport const zepto = 1e-21\nexport const yocto = 1e-24\n\nconst prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']\nconst prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y']\n\n/**\n * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }`\n *\n * @param {number} n\n * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds\n * @return {{n:number,prefix:string}}\n */\nexport const prefix = (n, baseMultiplier = 0) => {\n const nPow = n === 0 ? 0 : math.log10(n)\n let mult = 0\n while (nPow < mult * 3 && baseMultiplier > -8) {\n baseMultiplier--\n mult--\n }\n while (nPow >= 3 + mult * 3 && baseMultiplier < 8) {\n baseMultiplier++\n mult++\n }\n const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier]\n return {\n n: math.round((mult > 0 ? n / math.exp10(mult * 3) : n * math.exp10(mult * -3)) * 1e12) / 1e12,\n prefix\n }\n}\n"],"names":["math.log10","math.round","math.exp10"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AAGA;AACY,MAAC,KAAK,GAAG,KAAI;AACb,MAAC,KAAK,GAAG,KAAI;AACb,MAAC,GAAG,GAAG,KAAI;AACX,MAAC,IAAI,GAAG,KAAI;AACZ,MAAC,IAAI,GAAG,KAAI;AACZ,MAAC,IAAI,GAAG,IAAG;AACX,MAAC,IAAI,GAAG,IAAG;AACX,MAAC,IAAI,GAAG,IAAG;AACX,MAAC,KAAK,GAAG,IAAG;AACZ,MAAC,IAAI,GAAG,GAAE;AACV,MAAC,IAAI,GAAG,IAAG;AACX,MAAC,KAAK,GAAG,KAAI;AACb,MAAC,KAAK,GAAG,KAAI;AACb,MAAC,KAAK,GAAG,KAAI;AACb,MAAC,IAAI,GAAG,KAAI;AACZ,MAAC,IAAI,GAAG,MAAK;AACb,MAAC,KAAK,GAAG,MAAK;AACd,MAAC,IAAI,GAAG,MAAK;AACb,MAAC,KAAK,GAAG,MAAK;AACd,MAAC,KAAK,GAAG,MAAK;AAC1B;AACA,MAAM,QAAQ,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAC;AAC7D,MAAM,UAAU,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAC;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,CAAC,EAAE,cAAc,GAAG,CAAC,KAAK;AACjD,EAAE,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAGA,UAAU,CAAC,CAAC,EAAC;AAC1C,EAAE,IAAI,IAAI,GAAG,EAAC;AACd,EAAE,OAAO,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,cAAc,GAAG,CAAC,CAAC,EAAE;AACjD,IAAI,cAAc,GAAE;AACpB,IAAI,IAAI,GAAE;AACV,GAAG;AACH,EAAE,OAAO,IAAI,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,cAAc,GAAG,CAAC,EAAE;AACrD,IAAI,cAAc,GAAE;AACpB,IAAI,IAAI,GAAE;AACV,GAAG;AACH,EAAE,MAAM,MAAM,GAAG,cAAc,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC,cAAc,CAAC,GAAG,QAAQ,CAAC,cAAc,EAAC;AAC5F,EAAE,OAAO;AACT,IAAI,CAAC,EAAEC,UAAU,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,GAAGC,UAAU,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,GAAGA,UAAU,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,IAAI;AAClG,IAAI,MAAM;AACV,GAAG;AACH;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/metric.d.ts b/nodejs/node_modules/lib0/dist/metric.d.ts new file mode 100644 index 00000000..88482315 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/metric.d.ts @@ -0,0 +1,25 @@ +export const yotta: 1e+24; +export const zetta: 1e+21; +export const exa: 1000000000000000000; +export const peta: 1000000000000000; +export const tera: 1000000000000; +export const giga: 1000000000; +export const mega: 1000000; +export const kilo: 1000; +export const hecto: 100; +export const deca: 10; +export const deci: 0.1; +export const centi: 0.01; +export const milli: 0.001; +export const micro: 0.000001; +export const nano: 1e-9; +export const pico: 1e-12; +export const femto: 1e-15; +export const atto: 1e-18; +export const zepto: 1e-21; +export const yocto: 1e-24; +export function prefix(n: number, baseMultiplier?: number | undefined): { + n: number; + prefix: string; +}; +//# sourceMappingURL=metric.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/metric.d.ts.map b/nodejs/node_modules/lib0/dist/metric.d.ts.map new file mode 100644 index 00000000..469b7e43 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/metric.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metric.d.ts","sourceRoot":"","sources":["../metric.js"],"names":[],"mappings":"AAQA,0BAAyB;AACzB,0BAAyB;AACzB,sCAAuB;AACvB,oCAAwB;AACxB,iCAAwB;AACxB,8BAAuB;AACvB,2BAAuB;AACvB,wBAAuB;AACvB,wBAAwB;AACxB,sBAAsB;AACtB,uBAAuB;AACvB,yBAAyB;AACzB,0BAAyB;AACzB,6BAAyB;AACzB,wBAAwB;AACxB,yBAAyB;AACzB,0BAA0B;AAC1B,yBAAyB;AACzB,0BAA0B;AAC1B,0BAA0B;AAYnB,0BAJI,MAAM;OAEF,MAAM;YAAQ,MAAM;EAkBlC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/metric.test.d.ts b/nodejs/node_modules/lib0/dist/metric.test.d.ts new file mode 100644 index 00000000..36727264 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/metric.test.d.ts @@ -0,0 +1,3 @@ +export function testMetricPrefix(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=metric.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/metric.test.d.ts.map b/nodejs/node_modules/lib0/dist/metric.test.d.ts.map new file mode 100644 index 00000000..5a0b1823 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/metric.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metric.test.d.ts","sourceRoot":"","sources":["../metric.test.js"],"names":[],"mappings":"AAMO,qCAFI,EAAE,QAAQ,QA8BpB;mBAlCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/mutex-63f09c81.cjs b/nodejs/node_modules/lib0/dist/mutex-63f09c81.cjs new file mode 100644 index 00000000..5295d3de --- /dev/null +++ b/nodejs/node_modules/lib0/dist/mutex-63f09c81.cjs @@ -0,0 +1,54 @@ +'use strict'; + +/** + * Mutual exclude for JavaScript. + * + * @module mutex + */ + +/** + * @callback mutex + * @param {function():void} cb Only executed when this mutex is not in the current stack + * @param {function():void} [elseCb] Executed when this mutex is in the current stack + */ + +/** + * Creates a mutual exclude function with the following property: + * + * ```js + * const mutex = createMutex() + * mutex(() => { + * // This function is immediately executed + * mutex(() => { + * // This function is not executed, as the mutex is already active. + * }) + * }) + * ``` + * + * @return {mutex} A mutual exclude function + * @public + */ +const createMutex = () => { + let token = true; + return (f, g) => { + if (token) { + token = false; + try { + f(); + } finally { + token = true; + } + } else if (g !== undefined) { + g(); + } + } +}; + +var mutex = /*#__PURE__*/Object.freeze({ + __proto__: null, + createMutex: createMutex +}); + +exports.createMutex = createMutex; +exports.mutex = mutex; +//# sourceMappingURL=mutex-63f09c81.cjs.map diff --git a/nodejs/node_modules/lib0/dist/mutex-63f09c81.cjs.map b/nodejs/node_modules/lib0/dist/mutex-63f09c81.cjs.map new file mode 100644 index 00000000..48c234b5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/mutex-63f09c81.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"mutex-63f09c81.cjs","sources":["../mutex.js"],"sourcesContent":["/**\n * Mutual exclude for JavaScript.\n *\n * @module mutex\n */\n\n/**\n * @callback mutex\n * @param {function():void} cb Only executed when this mutex is not in the current stack\n * @param {function():void} [elseCb] Executed when this mutex is in the current stack\n */\n\n/**\n * Creates a mutual exclude function with the following property:\n *\n * ```js\n * const mutex = createMutex()\n * mutex(() => {\n * // This function is immediately executed\n * mutex(() => {\n * // This function is not executed, as the mutex is already active.\n * })\n * })\n * ```\n *\n * @return {mutex} A mutual exclude function\n * @public\n */\nexport const createMutex = () => {\n let token = true\n return (f, g) => {\n if (token) {\n token = false\n try {\n f()\n } finally {\n token = true\n }\n } else if (g !== undefined) {\n g()\n }\n }\n}\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,MAAM;AACjC,EAAE,IAAI,KAAK,GAAG,KAAI;AAClB,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,KAAK;AACnB,IAAI,IAAI,KAAK,EAAE;AACf,MAAM,KAAK,GAAG,MAAK;AACnB,MAAM,IAAI;AACV,QAAQ,CAAC,GAAE;AACX,OAAO,SAAS;AAChB,QAAQ,KAAK,GAAG,KAAI;AACpB,OAAO;AACP,KAAK,MAAM,IAAI,CAAC,KAAK,SAAS,EAAE;AAChC,MAAM,CAAC,GAAE;AACT,KAAK;AACL,GAAG;AACH;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/mutex.cjs b/nodejs/node_modules/lib0/dist/mutex.cjs new file mode 100644 index 00000000..db550c63 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/mutex.cjs @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var mutex = require('./mutex-63f09c81.cjs'); + + + +exports.createMutex = mutex.createMutex; +//# sourceMappingURL=mutex.cjs.map diff --git a/nodejs/node_modules/lib0/dist/mutex.cjs.map b/nodejs/node_modules/lib0/dist/mutex.cjs.map new file mode 100644 index 00000000..caa21ba8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/mutex.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"mutex.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/mutex.d.ts b/nodejs/node_modules/lib0/dist/mutex.d.ts new file mode 100644 index 00000000..92fd40fd --- /dev/null +++ b/nodejs/node_modules/lib0/dist/mutex.d.ts @@ -0,0 +1,3 @@ +export function createMutex(): mutex; +export type mutex = (cb: () => void, elseCb?: (() => void) | undefined) => any; +//# sourceMappingURL=mutex.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/mutex.d.ts.map b/nodejs/node_modules/lib0/dist/mutex.d.ts.map new file mode 100644 index 00000000..1201ed42 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/mutex.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mutex.d.ts","sourceRoot":"","sources":["../mutex.js"],"names":[],"mappings":"AA4BO,+BAHK,KAAK,CAiBhB;+BAlCqB,IAAI,kBACJ,IAAI"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/number-466d8922.cjs b/nodejs/node_modules/lib0/dist/number-466d8922.cjs new file mode 100644 index 00000000..e048b801 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number-466d8922.cjs @@ -0,0 +1,64 @@ +'use strict'; + +var math = require('./math-08e068f9.cjs'); +var binary = require('./binary-ac8e39e2.cjs'); + +/** + * Utility helpers for working with numbers. + * + * @module number + */ + +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; +const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; + +const LOWEST_INT32 = 1 << 31; +const HIGHEST_INT32 = binary.BITS31; +const HIGHEST_UINT32 = binary.BITS32; + +/* c8 ignore next */ +const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num); +const isNaN = Number.isNaN; +const parseInt = Number.parseInt; + +/** + * Count the number of "1" bits in an unsigned 32bit number. + * + * Super fun bitcount algorithm by Brian Kernighan. + * + * @param {number} n + */ +const countBits = n => { + n &= binary.BITS32; + let count = 0; + while (n) { + n &= (n - 1); + count++; + } + return count +}; + +var number = /*#__PURE__*/Object.freeze({ + __proto__: null, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, + MIN_SAFE_INTEGER: MIN_SAFE_INTEGER, + LOWEST_INT32: LOWEST_INT32, + HIGHEST_INT32: HIGHEST_INT32, + HIGHEST_UINT32: HIGHEST_UINT32, + isInteger: isInteger, + isNaN: isNaN, + parseInt: parseInt, + countBits: countBits +}); + +exports.HIGHEST_INT32 = HIGHEST_INT32; +exports.HIGHEST_UINT32 = HIGHEST_UINT32; +exports.LOWEST_INT32 = LOWEST_INT32; +exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER; +exports.MIN_SAFE_INTEGER = MIN_SAFE_INTEGER; +exports.countBits = countBits; +exports.isInteger = isInteger; +exports.isNaN = isNaN; +exports.number = number; +exports.parseInt = parseInt; +//# sourceMappingURL=number-466d8922.cjs.map diff --git a/nodejs/node_modules/lib0/dist/number-466d8922.cjs.map b/nodejs/node_modules/lib0/dist/number-466d8922.cjs.map new file mode 100644 index 00000000..b74d10d2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number-466d8922.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"number-466d8922.cjs","sources":["../number.js"],"sourcesContent":["/**\n * Utility helpers for working with numbers.\n *\n * @module number\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER\nexport const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER\n\nexport const LOWEST_INT32 = 1 << 31\nexport const HIGHEST_INT32 = binary.BITS31\nexport const HIGHEST_UINT32 = binary.BITS32\n\n/* c8 ignore next */\nexport const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)\nexport const isNaN = Number.isNaN\nexport const parseInt = Number.parseInt\n\n/**\n * Count the number of \"1\" bits in an unsigned 32bit number.\n *\n * Super fun bitcount algorithm by Brian Kernighan.\n *\n * @param {number} n\n */\nexport const countBits = n => {\n n &= binary.BITS32\n let count = 0\n while (n) {\n n &= (n - 1)\n count++\n }\n return count\n}\n"],"names":["binary.BITS31","binary.BITS32","math.floor"],"mappings":";;;;;AAAA;AACA;AACA;AACA;AACA;AAIA;AACY,MAAC,gBAAgB,GAAG,MAAM,CAAC,iBAAgB;AAC3C,MAAC,gBAAgB,GAAG,MAAM,CAAC,iBAAgB;AACvD;AACY,MAAC,YAAY,GAAG,CAAC,IAAI,GAAE;AACvB,MAAC,aAAa,GAAGA,cAAa;AAC9B,MAAC,cAAc,GAAGC,cAAa;AAC3C;AACA;AACY,MAAC,SAAS,GAAG,MAAM,CAAC,SAAS,KAAK,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAIC,UAAU,CAAC,GAAG,CAAC,KAAK,GAAG,EAAC;AAC7G,MAAC,KAAK,GAAG,MAAM,CAAC,MAAK;AACrB,MAAC,QAAQ,GAAG,MAAM,CAAC,SAAQ;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,CAAC,IAAI;AAC9B,EAAE,CAAC,IAAID,cAAa;AACpB,EAAE,IAAI,KAAK,GAAG,EAAC;AACf,EAAE,OAAO,CAAC,EAAE;AACZ,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAC;AAChB,IAAI,KAAK,GAAE;AACX,GAAG;AACH,EAAE,OAAO,KAAK;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/number.cjs b/nodejs/node_modules/lib0/dist/number.cjs new file mode 100644 index 00000000..e70c4465 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number.cjs @@ -0,0 +1,20 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./math-08e068f9.cjs'); +require('./binary-ac8e39e2.cjs'); +var number = require('./number-466d8922.cjs'); + + + +exports.HIGHEST_INT32 = number.HIGHEST_INT32; +exports.HIGHEST_UINT32 = number.HIGHEST_UINT32; +exports.LOWEST_INT32 = number.LOWEST_INT32; +exports.MAX_SAFE_INTEGER = number.MAX_SAFE_INTEGER; +exports.MIN_SAFE_INTEGER = number.MIN_SAFE_INTEGER; +exports.countBits = number.countBits; +exports.isInteger = number.isInteger; +exports.isNaN = number.isNaN; +exports.parseInt = number.parseInt; +//# sourceMappingURL=number.cjs.map diff --git a/nodejs/node_modules/lib0/dist/number.cjs.map b/nodejs/node_modules/lib0/dist/number.cjs.map new file mode 100644 index 00000000..50fed4d5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"number.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/number.d.ts b/nodejs/node_modules/lib0/dist/number.d.ts new file mode 100644 index 00000000..59c3e6a6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number.d.ts @@ -0,0 +1,10 @@ +export const MAX_SAFE_INTEGER: number; +export const MIN_SAFE_INTEGER: number; +export const LOWEST_INT32: number; +export const HIGHEST_INT32: number; +export const HIGHEST_UINT32: number; +export const isInteger: (number: unknown) => boolean; +export const isNaN: (number: unknown) => boolean; +export const parseInt: (string: string, radix?: number | undefined) => number; +export function countBits(n: number): number; +//# sourceMappingURL=number.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/number.d.ts.map b/nodejs/node_modules/lib0/dist/number.d.ts.map new file mode 100644 index 00000000..27a5a479 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.ts","sourceRoot":"","sources":["../number.js"],"names":[],"mappings":"AASA,sCAAuD;AACvD,sCAAuD;AAEvD,kCAAmC;AACnC,mCAA0C;AAC1C,oCAA2C;AAG3C,qDAAyH;AACzH,iDAAiC;AACjC,8EAAuC;AAShC,6BAFI,MAAM,UAUhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/number.test.d.ts b/nodejs/node_modules/lib0/dist/number.test.d.ts new file mode 100644 index 00000000..71df1857 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number.test.d.ts @@ -0,0 +1,4 @@ +export function testNumber(_tc: t.TestCase): void; +export function testShiftVsDivision(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=number.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/number.test.d.ts.map b/nodejs/node_modules/lib0/dist/number.test.d.ts.map new file mode 100644 index 00000000..615dcf70 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/number.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.test.d.ts","sourceRoot":"","sources":["../number.test.js"],"names":[],"mappings":"AAQO,gCAFI,EAAE,QAAQ,QAiBpB;AAOM,wCAFI,EAAE,QAAQ,QA6DpB;mBAzFkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/object-fecf6a7b.cjs b/nodejs/node_modules/lib0/dist/object-fecf6a7b.cjs new file mode 100644 index 00000000..ad730a4f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object-fecf6a7b.cjs @@ -0,0 +1,139 @@ +'use strict'; + +/** + * Utility functions for working with EcmaScript objects. + * + * @module object + */ + +/** + * @return {Object} obj + */ +const create = () => Object.create(null); + +/** + * Object.assign + */ +const assign = Object.assign; + +/** + * @param {Object} obj + */ +const keys = Object.keys; + +/** + * @template V + * @param {{[k:string]:V}} obj + * @param {function(V,string):any} f + */ +const forEach = (obj, f) => { + for (const key in obj) { + f(obj[key], key); + } +}; + +/** + * @todo implement mapToArray & map + * + * @template R + * @param {Object} obj + * @param {function(any,string):R} f + * @return {Array} + */ +const map = (obj, f) => { + const results = []; + for (const key in obj) { + results.push(f(obj[key], key)); + } + return results +}; + +/** + * @param {Object} obj + * @return {number} + */ +const length = obj => keys(obj).length; + +/** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ +const some = (obj, f) => { + for (const key in obj) { + if (f(obj[key], key)) { + return true + } + } + return false +}; + +/** + * @param {Object|undefined} obj + */ +const isEmpty = obj => { + // eslint-disable-next-line + for (const _k in obj) { + return false + } + return true +}; + +/** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ +const every = (obj, f) => { + for (const key in obj) { + if (!f(obj[key], key)) { + return false + } + } + return true +}; + +/** + * Calls `Object.prototype.hasOwnProperty`. + * + * @param {any} obj + * @param {string|symbol} key + * @return {boolean} + */ +const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); + +/** + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ +const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val)); + +var object = /*#__PURE__*/Object.freeze({ + __proto__: null, + create: create, + assign: assign, + keys: keys, + forEach: forEach, + map: map, + length: length, + some: some, + isEmpty: isEmpty, + every: every, + hasProperty: hasProperty, + equalFlat: equalFlat +}); + +exports.assign = assign; +exports.create = create; +exports.equalFlat = equalFlat; +exports.every = every; +exports.forEach = forEach; +exports.hasProperty = hasProperty; +exports.isEmpty = isEmpty; +exports.keys = keys; +exports.length = length; +exports.map = map; +exports.object = object; +exports.some = some; +//# sourceMappingURL=object-fecf6a7b.cjs.map diff --git a/nodejs/node_modules/lib0/dist/object-fecf6a7b.cjs.map b/nodejs/node_modules/lib0/dist/object-fecf6a7b.cjs.map new file mode 100644 index 00000000..b26c4389 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object-fecf6a7b.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"object-fecf6a7b.cjs","sources":["../object.js"],"sourcesContent":["/**\n * Utility functions for working with EcmaScript objects.\n *\n * @module object\n */\n\n/**\n * @return {Object} obj\n */\nexport const create = () => Object.create(null)\n\n/**\n * Object.assign\n */\nexport const assign = Object.assign\n\n/**\n * @param {Object} obj\n */\nexport const keys = Object.keys\n\n/**\n * @template V\n * @param {{[k:string]:V}} obj\n * @param {function(V,string):any} f\n */\nexport const forEach = (obj, f) => {\n for (const key in obj) {\n f(obj[key], key)\n }\n}\n\n/**\n * @todo implement mapToArray & map\n *\n * @template R\n * @param {Object} obj\n * @param {function(any,string):R} f\n * @return {Array}\n */\nexport const map = (obj, f) => {\n const results = []\n for (const key in obj) {\n results.push(f(obj[key], key))\n }\n return results\n}\n\n/**\n * @param {Object} obj\n * @return {number}\n */\nexport const length = obj => keys(obj).length\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const some = (obj, f) => {\n for (const key in obj) {\n if (f(obj[key], key)) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {Object|undefined} obj\n */\nexport const isEmpty = obj => {\n // eslint-disable-next-line\n for (const _k in obj) {\n return false\n }\n return true\n}\n\n/**\n * @param {Object} obj\n * @param {function(any,string):boolean} f\n * @return {boolean}\n */\nexport const every = (obj, f) => {\n for (const key in obj) {\n if (!f(obj[key], key)) {\n return false\n }\n }\n return true\n}\n\n/**\n * Calls `Object.prototype.hasOwnProperty`.\n *\n * @param {any} obj\n * @param {string|symbol} key\n * @return {boolean}\n */\nexport const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)\n\n/**\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nexport const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val))\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,EAAC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AAC;AACD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,CAAC,GAAG,EAAE,CAAC,KAAK;AACjC,EAAE,KAAK,MAAM,GAAG,IAAI,GAAG,EAAE;AACzB,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,EAAE;AAC3B,MAAM,OAAO,KAAK;AAClB,KAAK;AACL,GAAG;AACH,EAAE,OAAO,IAAI;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAC;AACvF;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,GAAG,KAAK,SAAS,IAAI,WAAW,CAAC,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/object.cjs b/nodejs/node_modules/lib0/dist/object.cjs new file mode 100644 index 00000000..bda9b58e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object.cjs @@ -0,0 +1,20 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var object = require('./object-fecf6a7b.cjs'); + + + +exports.assign = object.assign; +exports.create = object.create; +exports.equalFlat = object.equalFlat; +exports.every = object.every; +exports.forEach = object.forEach; +exports.hasProperty = object.hasProperty; +exports.isEmpty = object.isEmpty; +exports.keys = object.keys; +exports.length = object.length; +exports.map = object.map; +exports.some = object.some; +//# sourceMappingURL=object.cjs.map diff --git a/nodejs/node_modules/lib0/dist/object.cjs.map b/nodejs/node_modules/lib0/dist/object.cjs.map new file mode 100644 index 00000000..abde03ba --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"object.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/object.d.ts b/nodejs/node_modules/lib0/dist/object.d.ts new file mode 100644 index 00000000..4233fccc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object.d.ts @@ -0,0 +1,42 @@ +export function create(): { + [x: string]: any; +}; +/** + * Object.assign + */ +export const assign: { + (target: T, source: U): T & U; + (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; + (target: T_2, source1: U_2, source2: V_1, source3: W): T_2 & U_2 & V_1 & W; + (target: object, ...sources: any[]): any; +}; +/** + * @param {Object} obj + */ +export const keys: { + (o: object): string[]; + (o: {}): string[]; +}; +export function forEach(obj: { + [k: string]: V; +}, f: (arg0: V, arg1: string) => any): void; +export function map(obj: { + [x: string]: any; +}, f: (arg0: any, arg1: string) => R): R[]; +export function length(obj: { + [x: string]: any; +}): number; +export function some(obj: { + [x: string]: any; +}, f: (arg0: any, arg1: string) => boolean): boolean; +export function isEmpty(obj: Object | undefined): boolean; +export function every(obj: { + [x: string]: any; +}, f: (arg0: any, arg1: string) => boolean): boolean; +export function hasProperty(obj: any, key: string | symbol): boolean; +export function equalFlat(a: { + [x: string]: any; +}, b: { + [x: string]: any; +}): boolean; +//# sourceMappingURL=object.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/object.d.ts.map b/nodejs/node_modules/lib0/dist/object.d.ts.map new file mode 100644 index 00000000..ed6f175d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../object.js"],"names":[],"mappings":"AASO;QAFY,MAAM,GAAC,GAAG;EAEkB;AAE/C;;GAEG;AACH;;;;;EAAmC;AAEnC;;GAEG;AACH;;;EAA+B;AAOxB;;sBAFe,MAAM,KAAE,GAAG,QAMhC;AAUM;QAJW,MAAM,GAAC,GAAG;aACR,GAAG,QAAC,MAAM,aAS7B;AAMM;QAHW,MAAM,GAAC,GAAG;IAChB,MAAM,CAE2B;AAOtC;QAJW,MAAM,GAAC,GAAG;aACR,GAAG,QAAC,MAAM,KAAE,OAAO,GAC3B,OAAO,CASlB;AAKM,6BAFI,MAAM,GAAC,SAAS,WAQ1B;AAOM;QAJW,MAAM,GAAC,GAAG;aACR,GAAG,QAAC,MAAM,KAAE,OAAO,GAC3B,OAAO,CASlB;AASM,iCAJI,GAAG,OACH,MAAM,GAAC,MAAM,GACZ,OAAO,CAEoE;AAOhF;QAJW,MAAM,GAAC,GAAG;;QACV,MAAM,GAAC,GAAG;IAChB,OAAO,CAE4I"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/object.test.d.ts b/nodejs/node_modules/lib0/dist/object.test.d.ts new file mode 100644 index 00000000..f6472902 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object.test.d.ts @@ -0,0 +1,3 @@ +export function testObject(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=object.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/object.test.d.ts.map b/nodejs/node_modules/lib0/dist/object.test.d.ts.map new file mode 100644 index 00000000..28b142d2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/object.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.test.d.ts","sourceRoot":"","sources":["../object.test.js"],"names":[],"mappings":"AAOO,gCAFI,EAAE,QAAQ,QA+BpB;mBApCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/observable.cjs b/nodejs/node_modules/lib0/dist/observable.cjs new file mode 100644 index 00000000..2ce6c1f8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/observable.cjs @@ -0,0 +1,169 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var map = require('./map-0dabcc55.cjs'); +var set = require('./set-0f209abb.cjs'); +var array = require('./array-704ca50e.cjs'); + +/** + * Observable class prototype. + * + * @module observable + */ + +/** + * Handles named events. + * @experimental + * + * This is basically a (better typed) duplicate of Observable, which will replace Observable in the + * next release. + * + * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS + */ +class ObservableV2 { + constructor () { + /** + * Some desc. + * @type {Map>} + */ + this._observers = map.create(); + } + + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + on (name, f) { + map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f); + return f + } + + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, /** @type {any} */ (_f)); + f(...args); + }; + this.on(name, /** @type {any} */ (_f)); + } + + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + off (name, f) { + const observers = this._observers.get(name); + if (observers !== undefined) { + observers.delete(f); + if (observers.size === 0) { + this._observers.delete(name); + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @template {keyof EVENTS & string} NAME + * @param {NAME} name The event name. + * @param {Parameters} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = map.create(); + } +} + +/* c8 ignore start */ +/** + * Handles named events. + * + * @deprecated + * @template N + */ +class Observable { + constructor () { + /** + * Some desc. + * @type {Map} + */ + this._observers = map.create(); + } + + /** + * @param {N} name + * @param {function} f + */ + on (name, f) { + map.setIfUndefined(this._observers, name, set.create).add(f); + } + + /** + * @param {N} name + * @param {function} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, _f); + f(...args); + }; + this.on(name, _f); + } + + /** + * @param {N} name + * @param {function} f + */ + off (name, f) { + const observers = this._observers.get(name); + if (observers !== undefined) { + observers.delete(f); + if (observers.size === 0) { + this._observers.delete(name); + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = map.create(); + } +} +/* c8 ignore end */ + +exports.Observable = Observable; +exports.ObservableV2 = ObservableV2; +//# sourceMappingURL=observable.cjs.map diff --git a/nodejs/node_modules/lib0/dist/observable.cjs.map b/nodejs/node_modules/lib0/dist/observable.cjs.map new file mode 100644 index 00000000..55793011 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/observable.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"observable.cjs","sources":["../observable.js"],"sourcesContent":["/**\n * Observable class prototype.\n *\n * @module observable\n */\n\nimport * as map from './map.js'\nimport * as set from './set.js'\nimport * as array from './array.js'\n\n/**\n * Handles named events.\n * @experimental\n *\n * This is basically a (better typed) duplicate of Observable, which will replace Observable in the\n * next release.\n *\n * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS\n */\nexport class ObservableV2 {\n constructor () {\n /**\n * Some desc.\n * @type {Map>}\n */\n this._observers = map.create()\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f)\n return f\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, /** @type {any} */ (_f))\n f(...args)\n }\n this.on(name, /** @type {any} */ (_f))\n }\n\n /**\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name\n * @param {EVENTS[NAME]} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @template {keyof EVENTS & string} NAME\n * @param {NAME} name The event name.\n * @param {Parameters} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n\n/* c8 ignore start */\n/**\n * Handles named events.\n *\n * @deprecated\n * @template N\n */\nexport class Observable {\n constructor () {\n /**\n * Some desc.\n * @type {Map}\n */\n this._observers = map.create()\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n on (name, f) {\n map.setIfUndefined(this._observers, name, set.create).add(f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n once (name, f) {\n /**\n * @param {...any} args\n */\n const _f = (...args) => {\n this.off(name, _f)\n f(...args)\n }\n this.on(name, _f)\n }\n\n /**\n * @param {N} name\n * @param {function} f\n */\n off (name, f) {\n const observers = this._observers.get(name)\n if (observers !== undefined) {\n observers.delete(f)\n if (observers.size === 0) {\n this._observers.delete(name)\n }\n }\n }\n\n /**\n * Emit a named event. All registered event listeners that listen to the\n * specified name will receive the event.\n *\n * @todo This should catch exceptions\n *\n * @param {N} name The event name.\n * @param {Array} args The arguments that are applied to the event listener.\n */\n emit (name, args) {\n // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called.\n return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args))\n }\n\n destroy () {\n this._observers = map.create()\n }\n}\n/* c8 ignore end */\n"],"names":["map.create","map.setIfUndefined","set.create","array.from"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,YAAY,CAAC;AAC1B,EAAE,WAAW,CAAC,GAAG;AACjB;AACA;AACA;AACA;AACA,IAAI,IAAI,CAAC,UAAU,GAAGA,UAAU,GAAE;AAClC,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE;AACf,IAAIC,kBAAkB,CAAC,IAAI,CAAC,UAAU,yBAAyB,IAAI,GAAGC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,EAAC;AACxF,IAAI,OAAO,CAAC;AACZ,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE;AACjB;AACA;AACA;AACA,IAAI,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,KAAK;AAC5B,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,sBAAsB,EAAE,GAAE;AAC7C,MAAM,CAAC,CAAC,GAAG,IAAI,EAAC;AAChB,MAAK;AACL,IAAI,IAAI,CAAC,EAAE,CAAC,IAAI,sBAAsB,EAAE,GAAE;AAC1C,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE;AAChB,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAC;AAC/C,IAAI,IAAI,SAAS,KAAK,SAAS,EAAE;AACjC,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC,EAAC;AACzB,MAAM,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;AAChC,QAAQ,IAAI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,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE;AAChB,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAC;AAC/C,IAAI,IAAI,SAAS,KAAK,SAAS,EAAE;AACjC,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC,EAAC;AACzB,MAAM,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE;AAChC,QAAQ,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAC;AACpC,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE;AACpB;AACA,IAAI,OAAOC,UAAU,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAIH,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;AACpG,GAAG;AACH;AACA,EAAE,OAAO,CAAC,GAAG;AACb,IAAI,IAAI,CAAC,UAAU,GAAGA,UAAU,GAAE;AAClC,GAAG;AACH,CAAC;AACD;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/observable.d.ts b/nodejs/node_modules/lib0/dist/observable.d.ts new file mode 100644 index 00000000..590b1566 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/observable.d.ts @@ -0,0 +1,86 @@ +/** + * Handles named events. + * @experimental + * + * This is basically a (better typed) duplicate of Observable, which will replace Observable in the + * next release. + * + * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS + */ +export class ObservableV2 void; }> { + /** + * Some desc. + * @type {Map>} + */ + _observers: Map>; + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + on(name: NAME, f: EVENTS[NAME]): EVENTS[NAME]; + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + once(name: NAME_1, f: EVENTS[NAME_1]): void; + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + off(name: NAME_2, f: EVENTS[NAME_2]): void; + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @template {keyof EVENTS & string} NAME + * @param {NAME} name The event name. + * @param {Parameters} args The arguments that are applied to the event listener. + */ + emit(name: NAME_3, args: Parameters): void; + destroy(): void; +} +/** + * Handles named events. + * + * @deprecated + * @template N + */ +export class Observable { + /** + * Some desc. + * @type {Map} + */ + _observers: Map; + /** + * @param {N} name + * @param {function} f + */ + on(name: N, f: Function): void; + /** + * @param {N} name + * @param {function} f + */ + once(name: N, f: Function): void; + /** + * @param {N} name + * @param {function} f + */ + off(name: N, f: Function): void; + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit(name: N, args: Array): void; + destroy(): void; +} +//# sourceMappingURL=observable.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/observable.d.ts.map b/nodejs/node_modules/lib0/dist/observable.d.ts.map new file mode 100644 index 00000000..46f4ade3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/observable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"observable.d.ts","sourceRoot":"","sources":["../observable.js"],"names":[],"mappings":"AAUA;;;;;;;;GAQG;AACH,4EAFkD,GAAG,OAAE,IAAI;IAIvD;;;OAGG;IACH,YAFU,IAAI,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,CAED;IAGhC;;;;OAIG;IACH,kFAGC;IAED;;;;OAIG;IACH,kFASC;IAED;;;;OAIG;IACH,iFAQC;IAED;;;;;;;;;OASG;IACH,iGAGC;IAED,gBAEC;CACF;AAGD;;;;;GAKG;AACH;IAEI;;;OAGG;IACH,YAFU,IAAI,CAAC,EAAE,GAAG,CAAC,CAES;IAGhC;;;OAGG;IACH,SAHW,CAAC,qBAKX;IAED;;;OAGG;IACH,WAHW,CAAC,qBAYX;IAED;;;OAGG;IACH,UAHW,CAAC,qBAWX;IAED;;;;;;;;OAQG;IACH,WAHW,CAAC,QACD,MAAM,GAAG,CAAC,QAKpB;IAED,gBAEC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/observable.test.d.ts b/nodejs/node_modules/lib0/dist/observable.test.d.ts new file mode 100644 index 00000000..895ebfe4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/observable.test.d.ts @@ -0,0 +1,3 @@ +export function testTypedObservable(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=observable.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/observable.test.d.ts.map b/nodejs/node_modules/lib0/dist/observable.test.d.ts.map new file mode 100644 index 00000000..53f4c23e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/observable.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"observable.test.d.ts","sourceRoot":"","sources":["../observable.test.js"],"names":[],"mappings":"AAMO,yCAFI,EAAE,QAAQ,QA6CpB;mBAjDkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/pair-ab022bc3.cjs b/nodejs/node_modules/lib0/dist/pair-ab022bc3.cjs new file mode 100644 index 00000000..1df371e3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair-ab022bc3.cjs @@ -0,0 +1,69 @@ +'use strict'; + +/** + * Working with value pairs. + * + * @module pair + */ + +/** + * @template L,R + */ +class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor (left, right) { + this.left = left; + this.right = right; + } +} + +/** + * @template L,R + * @param {L} left + * @param {R} right + * @return {Pair} + */ +const create = (left, right) => new Pair(left, right); + +/** + * @template L,R + * @param {R} right + * @param {L} left + * @return {Pair} + */ +const createReversed = (right, left) => new Pair(left, right); + +/** + * @template L,R + * @param {Array>} arr + * @param {function(L, R):any} f + */ +const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right)); + +/** + * @template L,R,X + * @param {Array>} arr + * @param {function(L, R):X} f + * @return {Array} + */ +const map = (arr, f) => arr.map(p => f(p.left, p.right)); + +var pair = /*#__PURE__*/Object.freeze({ + __proto__: null, + Pair: Pair, + create: create, + createReversed: createReversed, + forEach: forEach, + map: map +}); + +exports.Pair = Pair; +exports.create = create; +exports.createReversed = createReversed; +exports.forEach = forEach; +exports.map = map; +exports.pair = pair; +//# sourceMappingURL=pair-ab022bc3.cjs.map diff --git a/nodejs/node_modules/lib0/dist/pair-ab022bc3.cjs.map b/nodejs/node_modules/lib0/dist/pair-ab022bc3.cjs.map new file mode 100644 index 00000000..6b99924a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair-ab022bc3.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"pair-ab022bc3.cjs","sources":["../pair.js"],"sourcesContent":["/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nexport class Pair {\n /**\n * @param {L} left\n * @param {R} right\n */\n constructor (left, right) {\n this.left = left\n this.right = right\n }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair}\n */\nexport const create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair}\n */\nexport const createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array>} arr\n * @param {function(L, R):any} f\n */\nexport const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array>} arr\n * @param {function(L, R):X} f\n * @return {Array}\n */\nexport const map = (arr, f) => arr.map(p => f(p.left, p.right))\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,IAAI,CAAC;AAClB;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE;AAC5B,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB,IAAI,IAAI,CAAC,KAAK,GAAG,MAAK;AACtB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAC;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,KAAK,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAC;AACpE;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,EAAC;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,CAAC,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/pair.cjs b/nodejs/node_modules/lib0/dist/pair.cjs new file mode 100644 index 00000000..f16af584 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair.cjs @@ -0,0 +1,14 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var pair = require('./pair-ab022bc3.cjs'); + + + +exports.Pair = pair.Pair; +exports.create = pair.create; +exports.createReversed = pair.createReversed; +exports.forEach = pair.forEach; +exports.map = pair.map; +//# sourceMappingURL=pair.cjs.map diff --git a/nodejs/node_modules/lib0/dist/pair.cjs.map b/nodejs/node_modules/lib0/dist/pair.cjs.map new file mode 100644 index 00000000..4ba3e245 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"pair.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/pair.d.ts b/nodejs/node_modules/lib0/dist/pair.d.ts new file mode 100644 index 00000000..fcb7d8b0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair.d.ts @@ -0,0 +1,22 @@ +/** + * Working with value pairs. + * + * @module pair + */ +/** + * @template L,R + */ +export class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor(left: L, right: R); + left: L; + right: R; +} +export function create(left: L, right: R): Pair; +export function createReversed(right: R, left: L): Pair; +export function forEach(arr: Pair[], f: (arg0: L, arg1: R) => any): void; +export function map(arr: Pair[], f: (arg0: L, arg1: R) => X): X[]; +//# sourceMappingURL=pair.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/pair.d.ts.map b/nodejs/node_modules/lib0/dist/pair.d.ts.map new file mode 100644 index 00000000..84e28800 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pair.d.ts","sourceRoot":"","sources":["../pair.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH;IACE;;;OAGG;IACH,kBAHW,CAAC,SACD,CAAC,EAKX;IAFC,QAAgB;IAChB,SAAkB;CAErB;AAQM,4DAAqD;AAQrD,oEAA6D;AAO7D,0EAFmB,GAAG,QAE0C;AAQhE,iFAAwD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/pair.test.d.ts b/nodejs/node_modules/lib0/dist/pair.test.d.ts new file mode 100644 index 00000000..ab51b8bc --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair.test.d.ts @@ -0,0 +1,3 @@ +export function testPair(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=pair.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/pair.test.d.ts.map b/nodejs/node_modules/lib0/dist/pair.test.d.ts.map new file mode 100644 index 00000000..6a7bd6ff --- /dev/null +++ b/nodejs/node_modules/lib0/dist/pair.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pair.test.d.ts","sourceRoot":"","sources":["../pair.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QAepB;mBApBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/performance.cjs b/nodejs/node_modules/lib0/dist/performance.cjs new file mode 100644 index 00000000..641f4d71 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.cjs @@ -0,0 +1,14 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/* eslint-env browser */ + +const measure = performance.measure.bind(performance); +const now = performance.now.bind(performance); +const mark = performance.mark.bind(performance); + +exports.mark = mark; +exports.measure = measure; +exports.now = now; +//# sourceMappingURL=performance.cjs.map diff --git a/nodejs/node_modules/lib0/dist/performance.cjs.map b/nodejs/node_modules/lib0/dist/performance.cjs.map new file mode 100644 index 00000000..072c415e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"performance.cjs","sources":["../performance.js"],"sourcesContent":["/* eslint-env browser */\n\nexport const measure = performance.measure.bind(performance)\nexport const now = performance.now.bind(performance)\nexport const mark = performance.mark.bind(performance)\n"],"names":[],"mappings":";;;;AAAA;AACA;AACY,MAAC,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAC;AAChD,MAAC,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAC;AACxC,MAAC,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/performance.d.ts b/nodejs/node_modules/lib0/dist/performance.d.ts new file mode 100644 index 00000000..7d24b63a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.d.ts @@ -0,0 +1,4 @@ +export const measure: (measureName: string, startOrMeasureOptions?: string | PerformanceMeasureOptions | undefined, endMark?: string | undefined) => PerformanceMeasure; +export const now: () => number; +export const mark: (markName: string, markOptions?: PerformanceMarkOptions | undefined) => PerformanceMark; +//# sourceMappingURL=performance.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/performance.d.ts.map b/nodejs/node_modules/lib0/dist/performance.d.ts.map new file mode 100644 index 00000000..9d2dedf4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"performance.d.ts","sourceRoot":"","sources":["../performance.js"],"names":[],"mappings":"AAEA,wKAA4D;AAC5D,+BAAoD;AACpD,2GAAsD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/performance.node.cjs b/nodejs/node_modules/lib0/dist/performance.node.cjs new file mode 100644 index 00000000..95686e83 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.node.cjs @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var node_perf_hooks = require('node:perf_hooks'); +var _function = require('./function-314fdc56.cjs'); +var time = require('./time-bc2081b9.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./object-fecf6a7b.cjs'); +require('./metric.cjs'); +require('./math-08e068f9.cjs'); + +/** + * @type {typeof performance.measure} + */ +/* c8 ignore next */ +const measure = node_perf_hooks.performance.measure ? node_perf_hooks.performance.measure.bind(node_perf_hooks.performance) : /** @type {any} */ (_function.nop); + +/** + * @type {typeof performance.now} + */ +/* c8 ignore next */ +const now = node_perf_hooks.performance.now ? node_perf_hooks.performance.now.bind(node_perf_hooks.performance) : time.getUnixTime; + +/** + * @type {typeof performance.mark} + */ +/* c8 ignore next */ +const mark = node_perf_hooks.performance.mark ? node_perf_hooks.performance.mark.bind(node_perf_hooks.performance) : /** @type {any} */ (_function.nop); + +exports.mark = mark; +exports.measure = measure; +exports.now = now; +//# sourceMappingURL=performance.node.cjs.map diff --git a/nodejs/node_modules/lib0/dist/performance.node.cjs.map b/nodejs/node_modules/lib0/dist/performance.node.cjs.map new file mode 100644 index 00000000..7d10ce0f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.node.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"performance.node.cjs","sources":["../performance.node.js"],"sourcesContent":["import { performance } from 'node:perf_hooks'\nimport { nop } from './function.js'\nimport * as time from './time.js'\n\n/**\n * @type {typeof performance.measure}\n */\n/* c8 ignore next */\nexport const measure = performance.measure ? performance.measure.bind(performance) : /** @type {any} */ (nop)\n\n/**\n * @type {typeof performance.now}\n */\n/* c8 ignore next */\nexport const now = performance.now ? performance.now.bind(performance) : time.getUnixTime\n\n/**\n * @type {typeof performance.mark}\n */\n/* c8 ignore next */\nexport const mark = performance.mark ? performance.mark.bind(performance) : /** @type {any} */ (nop)\n"],"names":["performance","nop","time.getUnixTime"],"mappings":";;;;;;;;;;;;;AAIA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAGA,2BAAW,CAAC,OAAO,GAAGA,2BAAW,CAAC,OAAO,CAAC,IAAI,CAACA,2BAAW,CAAC,uBAAuBC,aAAG,EAAC;AAC7G;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAGD,2BAAW,CAAC,GAAG,GAAGA,2BAAW,CAAC,GAAG,CAAC,IAAI,CAACA,2BAAW,CAAC,GAAGE,iBAAgB;AACzF;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAGF,2BAAW,CAAC,IAAI,GAAGA,2BAAW,CAAC,IAAI,CAAC,IAAI,CAACA,2BAAW,CAAC,uBAAuBC,aAAG;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/performance.node.d.ts b/nodejs/node_modules/lib0/dist/performance.node.d.ts new file mode 100644 index 00000000..261fa7c2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.node.d.ts @@ -0,0 +1,15 @@ +/// +/** + * @type {typeof performance.measure} + */ +export const measure: typeof performance.measure; +/** + * @type {typeof performance.now} + */ +export const now: typeof performance.now; +/** + * @type {typeof performance.mark} + */ +export const mark: typeof performance.mark; +import { performance } from 'node:perf_hooks'; +//# sourceMappingURL=performance.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/performance.node.d.ts.map b/nodejs/node_modules/lib0/dist/performance.node.d.ts.map new file mode 100644 index 00000000..2c9a7a10 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/performance.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"performance.node.d.ts","sourceRoot":"","sources":["../performance.node.js"],"names":[],"mappings":";AAIA;;GAEG;AAEH,sBAHU,OAAO,mBAAmB,CAGyE;AAE7G;;GAEG;AAEH,kBAHU,OAAO,eAAe,CAGyD;AAEzF;;GAEG;AAEH,mBAHU,OAAO,gBAAgB,CAGmE;4BApBxE,iBAAiB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng-e4f28259.cjs b/nodejs/node_modules/lib0/dist/prng-e4f28259.cjs new file mode 100644 index 00000000..b6fb112b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng-e4f28259.cjs @@ -0,0 +1,387 @@ +'use strict'; + +var binary = require('./binary-ac8e39e2.cjs'); +var string = require('./string-6d104757.cjs'); +var math = require('./math-08e068f9.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); + +/** + * @module prng + */ + +/** + * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`. + */ +class Xorshift32 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed; + /** + * @type {number} + */ + this._state = seed; + } + + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next () { + let x = this._state; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + this._state = x; + return (x >>> 0) / (binary.BITS32 + 1) + } +} + +/** + * @module prng + */ + +/** + * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures. + * + * This implementation follows the idea of the original xoroshiro128plus implementation, + * but is optimized for the JavaScript runtime. I.e. + * * The operations are performed on 32bit integers (the original implementation works with 64bit values). + * * The initial 128bit state is computed based on a 32bit seed and Xorshift32. + * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus. + * Caution: The last addition step works slightly different than in the original implementation - the add carry of the + * first 32bit addition is not carried over to the last 32bit. + * + * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c) + */ +class Xoroshiro128plus { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed; + // This is a variant of Xoroshiro128plus to fill the initial state + const xorshift32 = new Xorshift32(seed); + this.state = new Uint32Array(4); + for (let i = 0; i < 4; i++) { + this.state[i] = xorshift32.next() * binary.BITS32; + } + this._fresh = true; + } + + /** + * @return {number} Float/Double in [0,1) + */ + next () { + const state = this.state; + if (this._fresh) { + this._fresh = false; + return ((state[0] + state[2]) >>> 0) / (binary.BITS32 + 1) + } else { + this._fresh = true; + const s0 = state[0]; + const s1 = state[1]; + const s2 = state[2] ^ s0; + const s3 = state[3] ^ s1; + // function js_rotl (x, k) { + // k = k - 32 + // const x1 = x[0] + // const x2 = x[1] + // x[0] = x2 << k | x1 >>> (32 - k) + // x[1] = x1 << k | x2 >>> (32 - k) + // } + // rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23 + state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18); + state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14); + // rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9 + state[2] = s3 << 4 | s2 >>> 28; + state[3] = s2 << 4 | s3 >>> 28; + return (((state[1] + state[3]) >>> 0) / (binary.BITS32 + 1)) + } + } +} + +/* +// Reference implementation +// Source: http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c +// By David Blackman and Sebastiano Vigna +// Who published the reference implementation under Public Domain (CC0) + +#include +#include + +uint64_t s[2]; + +static inline uint64_t rotl(const uint64_t x, int k) { + return (x << k) | (x >> (64 - k)); +} + +uint64_t next(void) { + const uint64_t s0 = s[0]; + uint64_t s1 = s[1]; + s1 ^= s0; + s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b + s[1] = rotl(s1, 36); // c + return (s[0] + s[1]) & 0xFFFFFFFF; +} + +int main(void) +{ + int i; + s[0] = 1111 | (1337ul << 32); + s[1] = 1234 | (9999ul << 32); + + printf("1000 outputs of genrand_int31()\n"); + for (i=0; i<100; i++) { + printf("%10lu ", i); + printf("%10lu ", next()); + printf("- %10lu ", s[0] >> 32); + printf("%10lu ", (s[0] << 32) >> 32); + printf("%10lu ", s[1] >> 32); + printf("%10lu ", (s[1] << 32) >> 32); + printf("\n"); + // if (i%5==4) printf("\n"); + } + return 0; +} +*/ + +/** + * Fast Pseudo Random Number Generators. + * + * Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted. + * Two PRNGs must generate the same random sequence of numbers if given the same seed. + * + * @module prng + */ + +/** + * Description of the function + * @callback generatorNext + * @return {number} A random float in the cange of [0,1) + */ + +/** + * A random type generator. + * + * @typedef {Object} PRNG + * @property {generatorNext} next Generate new number + */ +const DefaultPRNG = Xoroshiro128plus; + +/** + * Create a Xoroshiro128plus Pseudo-Random-Number-Generator. + * This is the fastest full-period generator passing BigCrush without systematic failures. + * But there are more PRNGs available in ./PRNG/. + * + * @param {number} seed A positive 32bit integer. Do not use negative numbers. + * @return {PRNG} + */ +const create = seed => new DefaultPRNG(seed); + +/** + * Generates a single random bool. + * + * @param {PRNG} gen A random number generator. + * @return {Boolean} A random boolean + */ +const bool = gen => (gen.next() >= 0.5); + +/** + * Generates a random integer with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +const int53 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min); + +/** + * Generates a random integer with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +const uint53 = (gen, min, max) => math.abs(int53(gen, min, max)); + +/** + * Generates a random integer with 32 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +const int32 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min); + +/** + * Generates a random integer with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +const uint32 = (gen, min, max) => int32(gen, min, max) >>> 0; + +/** + * @deprecated + * Optimized version of prng.int32. It has the same precision as prng.int32, but should be preferred when + * openaring on smaller ranges. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). The max inclusive number is `binary.BITS31-1` + * @return {Number} A random integer on [min, max] + */ +const int31 = (gen, min, max) => int32(gen, min, max); + +/** + * Generates a random real on [0, 1) with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @return {Number} A random real number on [0, 1). + */ +const real53 = gen => gen.next(); // (((gen.next() >>> 5) * binary.BIT26) + (gen.next() >>> 6)) / MAX_SAFE_INTEGER + +/** + * Generates a random character from char code 32 - 126. I.e. Characters, Numbers, special characters, and Space: + * + * @param {PRNG} gen A random number generator. + * @return {string} + * + * (Space)!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~ + */ +const char = gen => string.fromCharCode(int31(gen, 32, 126)); + +/** + * @param {PRNG} gen + * @return {string} A single letter (a-z) + */ +const letter = gen => string.fromCharCode(int31(gen, 97, 122)); + +/** + * @param {PRNG} gen + * @param {number} [minLen=0] + * @param {number} [maxLen=20] + * @return {string} A random word (0-20 characters) without spaces consisting of letters (a-z) + */ +const word = (gen, minLen = 0, maxLen = 20) => { + const len = int31(gen, minLen, maxLen); + let str = ''; + for (let i = 0; i < len; i++) { + str += letter(gen); + } + return str +}; + +/** + * TODO: this function produces invalid runes. Does not cover all of utf16!! + * + * @param {PRNG} gen + * @return {string} + */ +const utf16Rune = gen => { + const codepoint = int31(gen, 0, 256); + return string.fromCodePoint(codepoint) +}; + +/** + * @param {PRNG} gen + * @param {number} [maxlen = 20] + */ +const utf16String = (gen, maxlen = 20) => { + const len = int31(gen, 0, maxlen); + let str = ''; + for (let i = 0; i < len; i++) { + str += utf16Rune(gen); + } + return str +}; + +/** + * Returns one element of a given array. + * + * @param {PRNG} gen A random number generator. + * @param {Array} array Non empty Array of possible values. + * @return {T} One of the values of the supplied Array. + * @template T + */ +const oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)]; + +/** + * @param {PRNG} gen + * @param {number} len + * @return {Uint8Array} + */ +const uint8Array = (gen, len) => { + const buf = buffer.createUint8ArrayFromLen(len); + for (let i = 0; i < buf.length; i++) { + buf[i] = int32(gen, 0, binary.BITS8); + } + return buf +}; + +/* c8 ignore start */ +/** + * @param {PRNG} gen + * @param {number} len + * @return {Uint16Array} + */ +const uint16Array = (gen, len) => new Uint16Array(uint8Array(gen, len * 2).buffer); + +/** + * @param {PRNG} gen + * @param {number} len + * @return {Uint32Array} + */ +const uint32Array = (gen, len) => new Uint32Array(uint8Array(gen, len * 4).buffer); +/* c8 ignore stop */ + +var prng = /*#__PURE__*/Object.freeze({ + __proto__: null, + DefaultPRNG: DefaultPRNG, + create: create, + bool: bool, + int53: int53, + uint53: uint53, + int32: int32, + uint32: uint32, + int31: int31, + real53: real53, + char: char, + letter: letter, + word: word, + utf16Rune: utf16Rune, + utf16String: utf16String, + oneOf: oneOf, + uint8Array: uint8Array, + uint16Array: uint16Array, + uint32Array: uint32Array +}); + +exports.DefaultPRNG = DefaultPRNG; +exports.bool = bool; +exports.char = char; +exports.create = create; +exports.int31 = int31; +exports.int32 = int32; +exports.int53 = int53; +exports.letter = letter; +exports.oneOf = oneOf; +exports.prng = prng; +exports.real53 = real53; +exports.uint16Array = uint16Array; +exports.uint32 = uint32; +exports.uint32Array = uint32Array; +exports.uint53 = uint53; +exports.uint8Array = uint8Array; +exports.utf16Rune = utf16Rune; +exports.utf16String = utf16String; +exports.word = word; +//# sourceMappingURL=prng-e4f28259.cjs.map diff --git a/nodejs/node_modules/lib0/dist/prng-e4f28259.cjs.map b/nodejs/node_modules/lib0/dist/prng-e4f28259.cjs.map new file mode 100644 index 00000000..b9ccad91 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng-e4f28259.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"prng-e4f28259.cjs","sources":["../prng/Xorshift32.js","../prng/Xoroshiro128plus.js","../prng.js"],"sourcesContent":["/**\n * @module prng\n */\n\nimport * as binary from '../binary.js'\n\n/**\n * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`.\n */\nexport class Xorshift32 {\n /**\n * @param {number} seed Unsigned 32 bit number\n */\n constructor (seed) {\n this.seed = seed\n /**\n * @type {number}\n */\n this._state = seed\n }\n\n /**\n * Generate a random signed integer.\n *\n * @return {Number} A 32 bit signed integer.\n */\n next () {\n let x = this._state\n x ^= x << 13\n x ^= x >> 17\n x ^= x << 5\n this._state = x\n return (x >>> 0) / (binary.BITS32 + 1)\n }\n}\n","/**\n * @module prng\n */\n\nimport { Xorshift32 } from './Xorshift32.js'\nimport * as binary from '../binary.js'\n\n/**\n * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures.\n *\n * This implementation follows the idea of the original xoroshiro128plus implementation,\n * but is optimized for the JavaScript runtime. I.e.\n * * The operations are performed on 32bit integers (the original implementation works with 64bit values).\n * * The initial 128bit state is computed based on a 32bit seed and Xorshift32.\n * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus.\n * Caution: The last addition step works slightly different than in the original implementation - the add carry of the\n * first 32bit addition is not carried over to the last 32bit.\n *\n * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c)\n */\nexport class Xoroshiro128plus {\n /**\n * @param {number} seed Unsigned 32 bit number\n */\n constructor (seed) {\n this.seed = seed\n // This is a variant of Xoroshiro128plus to fill the initial state\n const xorshift32 = new Xorshift32(seed)\n this.state = new Uint32Array(4)\n for (let i = 0; i < 4; i++) {\n this.state[i] = xorshift32.next() * binary.BITS32\n }\n this._fresh = true\n }\n\n /**\n * @return {number} Float/Double in [0,1)\n */\n next () {\n const state = this.state\n if (this._fresh) {\n this._fresh = false\n return ((state[0] + state[2]) >>> 0) / (binary.BITS32 + 1)\n } else {\n this._fresh = true\n const s0 = state[0]\n const s1 = state[1]\n const s2 = state[2] ^ s0\n const s3 = state[3] ^ s1\n // function js_rotl (x, k) {\n // k = k - 32\n // const x1 = x[0]\n // const x2 = x[1]\n // x[0] = x2 << k | x1 >>> (32 - k)\n // x[1] = x1 << k | x2 >>> (32 - k)\n // }\n // rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23\n state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18)\n state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14)\n // rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9\n state[2] = s3 << 4 | s2 >>> 28\n state[3] = s2 << 4 | s3 >>> 28\n return (((state[1] + state[3]) >>> 0) / (binary.BITS32 + 1))\n }\n }\n}\n\n/*\n// Reference implementation\n// Source: http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c\n// By David Blackman and Sebastiano Vigna\n// Who published the reference implementation under Public Domain (CC0)\n\n#include \n#include \n\nuint64_t s[2];\n\nstatic inline uint64_t rotl(const uint64_t x, int k) {\n return (x << k) | (x >> (64 - k));\n}\n\nuint64_t next(void) {\n const uint64_t s0 = s[0];\n uint64_t s1 = s[1];\n s1 ^= s0;\n s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b\n s[1] = rotl(s1, 36); // c\n return (s[0] + s[1]) & 0xFFFFFFFF;\n}\n\nint main(void)\n{\n int i;\n s[0] = 1111 | (1337ul << 32);\n s[1] = 1234 | (9999ul << 32);\n\n printf(\"1000 outputs of genrand_int31()\\n\");\n for (i=0; i<100; i++) {\n printf(\"%10lu \", i);\n printf(\"%10lu \", next());\n printf(\"- %10lu \", s[0] >> 32);\n printf(\"%10lu \", (s[0] << 32) >> 32);\n printf(\"%10lu \", s[1] >> 32);\n printf(\"%10lu \", (s[1] << 32) >> 32);\n printf(\"\\n\");\n // if (i%5==4) printf(\"\\n\");\n }\n return 0;\n}\n*/\n","/**\n * Fast Pseudo Random Number Generators.\n *\n * Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted.\n * Two PRNGs must generate the same random sequence of numbers if given the same seed.\n *\n * @module prng\n */\n\nimport * as binary from './binary.js'\nimport { fromCharCode, fromCodePoint } from './string.js'\nimport * as math from './math.js'\nimport { Xoroshiro128plus } from './prng/Xoroshiro128plus.js'\nimport * as buffer from './buffer.js'\n\n/**\n * Description of the function\n * @callback generatorNext\n * @return {number} A random float in the cange of [0,1)\n */\n\n/**\n * A random type generator.\n *\n * @typedef {Object} PRNG\n * @property {generatorNext} next Generate new number\n */\nexport const DefaultPRNG = Xoroshiro128plus\n\n/**\n * Create a Xoroshiro128plus Pseudo-Random-Number-Generator.\n * This is the fastest full-period generator passing BigCrush without systematic failures.\n * But there are more PRNGs available in ./PRNG/.\n *\n * @param {number} seed A positive 32bit integer. Do not use negative numbers.\n * @return {PRNG}\n */\nexport const create = seed => new DefaultPRNG(seed)\n\n/**\n * Generates a single random bool.\n *\n * @param {PRNG} gen A random number generator.\n * @return {Boolean} A random boolean\n */\nexport const bool = gen => (gen.next() >= 0.5)\n\n/**\n * Generates a random integer with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const int53 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min)\n\n/**\n * Generates a random integer with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const uint53 = (gen, min, max) => math.abs(int53(gen, min, max))\n\n/**\n * Generates a random integer with 32 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const int32 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min)\n\n/**\n * Generates a random integer with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive).\n * @return {Number} A random integer on [min, max]\n */\nexport const uint32 = (gen, min, max) => int32(gen, min, max) >>> 0\n\n/**\n * @deprecated\n * Optimized version of prng.int32. It has the same precision as prng.int32, but should be preferred when\n * openaring on smaller ranges.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Number} min The lower bound of the allowed return values (inclusive).\n * @param {Number} max The upper bound of the allowed return values (inclusive). The max inclusive number is `binary.BITS31-1`\n * @return {Number} A random integer on [min, max]\n */\nexport const int31 = (gen, min, max) => int32(gen, min, max)\n\n/**\n * Generates a random real on [0, 1) with 53 bit resolution.\n *\n * @param {PRNG} gen A random number generator.\n * @return {Number} A random real number on [0, 1).\n */\nexport const real53 = gen => gen.next() // (((gen.next() >>> 5) * binary.BIT26) + (gen.next() >>> 6)) / MAX_SAFE_INTEGER\n\n/**\n * Generates a random character from char code 32 - 126. I.e. Characters, Numbers, special characters, and Space:\n *\n * @param {PRNG} gen A random number generator.\n * @return {string}\n *\n * (Space)!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~\n */\nexport const char = gen => fromCharCode(int31(gen, 32, 126))\n\n/**\n * @param {PRNG} gen\n * @return {string} A single letter (a-z)\n */\nexport const letter = gen => fromCharCode(int31(gen, 97, 122))\n\n/**\n * @param {PRNG} gen\n * @param {number} [minLen=0]\n * @param {number} [maxLen=20]\n * @return {string} A random word (0-20 characters) without spaces consisting of letters (a-z)\n */\nexport const word = (gen, minLen = 0, maxLen = 20) => {\n const len = int31(gen, minLen, maxLen)\n let str = ''\n for (let i = 0; i < len; i++) {\n str += letter(gen)\n }\n return str\n}\n\n/**\n * TODO: this function produces invalid runes. Does not cover all of utf16!!\n *\n * @param {PRNG} gen\n * @return {string}\n */\nexport const utf16Rune = gen => {\n const codepoint = int31(gen, 0, 256)\n return fromCodePoint(codepoint)\n}\n\n/**\n * @param {PRNG} gen\n * @param {number} [maxlen = 20]\n */\nexport const utf16String = (gen, maxlen = 20) => {\n const len = int31(gen, 0, maxlen)\n let str = ''\n for (let i = 0; i < len; i++) {\n str += utf16Rune(gen)\n }\n return str\n}\n\n/**\n * Returns one element of a given array.\n *\n * @param {PRNG} gen A random number generator.\n * @param {Array} array Non empty Array of possible values.\n * @return {T} One of the values of the supplied Array.\n * @template T\n */\nexport const oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)]\n\n/**\n * @param {PRNG} gen\n * @param {number} len\n * @return {Uint8Array}\n */\nexport const uint8Array = (gen, len) => {\n const buf = buffer.createUint8ArrayFromLen(len)\n for (let i = 0; i < buf.length; i++) {\n buf[i] = int32(gen, 0, binary.BITS8)\n }\n return buf\n}\n\n/* c8 ignore start */\n/**\n * @param {PRNG} gen\n * @param {number} len\n * @return {Uint16Array}\n */\nexport const uint16Array = (gen, len) => new Uint16Array(uint8Array(gen, len * 2).buffer)\n\n/**\n * @param {PRNG} gen\n * @param {number} len\n * @return {Uint32Array}\n */\nexport const uint32Array = (gen, len) => new Uint32Array(uint8Array(gen, len * 4).buffer)\n/* c8 ignore stop */\n"],"names":["binary.BITS32","math.floor","math.abs","fromCharCode","fromCodePoint","buffer.createUint8ArrayFromLen","binary.BITS8"],"mappings":";;;;;;;AAAA;AACA;AACA;AAGA;AACA;AACA;AACA;AACO,MAAM,UAAU,CAAC;AACxB;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE;AACrB,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB;AACA;AACA;AACA,IAAI,IAAI,CAAC,MAAM,GAAG,KAAI;AACtB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,CAAC,GAAG;AACV,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,OAAM;AACvB,IAAI,CAAC,IAAI,CAAC,IAAI,GAAE;AAChB,IAAI,CAAC,IAAI,CAAC,IAAI,GAAE;AAChB,IAAI,CAAC,IAAI,CAAC,IAAI,EAAC;AACf,IAAI,IAAI,CAAC,MAAM,GAAG,EAAC;AACnB,IAAI,OAAO,CAAC,CAAC,KAAK,CAAC,KAAKA,aAAa,GAAG,CAAC,CAAC;AAC1C,GAAG;AACH;;AClCA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAgB,CAAC;AAC9B;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE;AACrB,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB;AACA,IAAI,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,EAAC;AAC3C,IAAI,IAAI,CAAC,KAAK,GA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M,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,KAAK,GAAE;AACpC,MAAM,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,KAAK,GAAE;AACpC,MAAM,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAKA,aAAa,GAAG,CAAC,CAAC,CAAC;AAClE,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,iBAAgB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,IAAI,IAAI,IAAI,WAAW,CAAC,IAAI,EAAC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,GAAG,KAAK,GAAG,CAAC,IAAI,EAAE,IAAI,GAAG,EAAC;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,KAAKC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,EAAC;AACtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,KAAKC,QAAQ,CA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AK,CAAC,GAAG,EAAE,CAAC,EAAEC,YAAY,EAAC;AACxC,GAAG;AACH,EAAE,OAAO,GAAG;AACZ,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,WAAW,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,MAAM,EAAC;AACzF;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,WAAW,CAAC,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,MAAM,EAAC;AACzF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng.cjs b/nodejs/node_modules/lib0/dist/prng.cjs new file mode 100644 index 00000000..1abaaae4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng.cjs @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./binary-ac8e39e2.cjs'); +require('./string-6d104757.cjs'); +require('./math-08e068f9.cjs'); +var prng = require('./prng-e4f28259.cjs'); +require('./buffer-f11b8d4d.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./map-0dabcc55.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./decoding-000d097f.cjs'); +require('./error-8582d695.cjs'); + + + +exports.DefaultPRNG = prng.DefaultPRNG; +exports.bool = prng.bool; +exports.char = prng.char; +exports.create = prng.create; +exports.int31 = prng.int31; +exports.int32 = prng.int32; +exports.int53 = prng.int53; +exports.letter = prng.letter; +exports.oneOf = prng.oneOf; +exports.real53 = prng.real53; +exports.uint16Array = prng.uint16Array; +exports.uint32 = prng.uint32; +exports.uint32Array = prng.uint32Array; +exports.uint53 = prng.uint53; +exports.uint8Array = prng.uint8Array; +exports.utf16Rune = prng.utf16Rune; +exports.utf16String = prng.utf16String; +exports.word = prng.word; +//# sourceMappingURL=prng.cjs.map diff --git a/nodejs/node_modules/lib0/dist/prng.cjs.map b/nodejs/node_modules/lib0/dist/prng.cjs.map new file mode 100644 index 00000000..3dc947d4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"prng.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng.d.ts b/nodejs/node_modules/lib0/dist/prng.d.ts new file mode 100644 index 00000000..af72c2ed --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng.d.ts @@ -0,0 +1,44 @@ +/** + * Description of the function + * @callback generatorNext + * @return {number} A random float in the cange of [0,1) + */ +/** + * A random type generator. + * + * @typedef {Object} PRNG + * @property {generatorNext} next Generate new number + */ +export const DefaultPRNG: typeof Xoroshiro128plus; +export function create(seed: number): PRNG; +export function bool(gen: PRNG): boolean; +export function int53(gen: PRNG, min: number, max: number): number; +export function uint53(gen: PRNG, min: number, max: number): number; +export function int32(gen: PRNG, min: number, max: number): number; +export function uint32(gen: PRNG, min: number, max: number): number; +export function int31(gen: PRNG, min: number, max: number): number; +export function real53(gen: PRNG): number; +export function char(gen: PRNG): string; +export function letter(gen: PRNG): string; +export function word(gen: PRNG, minLen?: number | undefined, maxLen?: number | undefined): string; +export function utf16Rune(gen: PRNG): string; +export function utf16String(gen: PRNG, maxlen?: number | undefined): string; +export function oneOf(gen: PRNG, array: T[]): T; +export function uint8Array(gen: PRNG, len: number): Uint8Array; +export function uint16Array(gen: PRNG, len: number): Uint16Array; +export function uint32Array(gen: PRNG, len: number): Uint32Array; +/** + * Description of the function + */ +export type generatorNext = () => number; +/** + * A random type generator. + */ +export type PRNG = { + /** + * Generate new number + */ + next: generatorNext; +}; +import { Xoroshiro128plus } from './prng/Xoroshiro128plus.js'; +//# sourceMappingURL=prng.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng.d.ts.map b/nodejs/node_modules/lib0/dist/prng.d.ts.map new file mode 100644 index 00000000..b6910f7b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prng.d.ts","sourceRoot":"","sources":["../prng.js"],"names":[],"mappings":"AAeA;;;;GAIG;AAEH;;;;;GAKG;AACH,kDAA2C;AAUpC,6BAHI,MAAM,GACL,IAAI,CAEmC;AAQ5C,0BAHI,IAAI,WAG+B;AAUvC,2BALI,IAAI,oCAKuE;AAU/E,4BALI,IAAI,oCAKwD;AAUhE,2BALI,IAAI,oCAKuE;AAU/E,4BALI,IAAI,oCAKoD;AAY5D,2BALI,IAAI,oCAK6C;AAQrD,4BAHI,IAAI,UAGwB;AAUhC,0BALI,IAAI,GACH,MAAM,CAI0C;AAMrD,4BAHI,IAAI,GACH,MAAM,CAE4C;AAQvD,0BALI,IAAI,6DAGH,MAAM,CASjB;AAQM,+BAHI,IAAI,GACH,MAAM,CAKjB;AAMM,iCAHI,IAAI,uCAUd;AAUM,8BALI,IAAI,iBAK4D;AAOpE,gCAJI,IAAI,OACJ,MAAM,GACL,UAAU,CAQrB;AAQM,iCAJI,IAAI,OACJ,MAAM,GACL,WAAW,CAEkE;AAOlF,iCAJI,IAAI,OACJ,MAAM,GACL,WAAW,CAEkE;;;;kCApL5E,MAAM;;;;;;;;UAOL,aAAa;;iCAbM,4BAA4B"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng.test.d.ts b/nodejs/node_modules/lib0/dist/prng.test.d.ts new file mode 100644 index 00000000..dd69f9a7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng.test.d.ts @@ -0,0 +1,6 @@ +export function testGeneratorXoroshiro128plus(tc: t.TestCase): void; +export function testGeneratorXorshift32(tc: t.TestCase): void; +export function testGeneratorMt19937(tc: t.TestCase): void; +export function testNumberDistributions(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=prng.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng.test.d.ts.map b/nodejs/node_modules/lib0/dist/prng.test.d.ts.map new file mode 100644 index 00000000..91e6a86c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prng.test.d.ts","sourceRoot":"","sources":["../prng.test.js"],"names":[],"mappings":"AA4LO,kDAFI,EAAE,QAAQ,QAE2E;AAKzF,4CAFI,EAAE,QAAQ,QAKpB;AAKM,yCAFI,EAAE,QAAQ,QAKpB;AA2BM,4CAFI,EAAE,QAAQ,QAOpB;mBAxOkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng/Mt19937.d.ts b/nodejs/node_modules/lib0/dist/prng/Mt19937.d.ts new file mode 100644 index 00000000..d644fabf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng/Mt19937.d.ts @@ -0,0 +1,29 @@ +/** + * This is a port of Shawn Cokus's implementation of the original Mersenne Twister algorithm (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/MTARCOK/mt19937ar-cok.c). + * MT has a very high period of 2^19937. Though the authors of xorshift describe that a high period is not + * very relevant (http://vigna.di.unimi.it/xorshift/). It is four times slower than xoroshiro128plus and + * needs to recompute its state after generating 624 numbers. + * + * ```js + * const gen = new Mt19937(new Date().getTime()) + * console.log(gen.next()) + * ``` + * + * @public + */ +export class Mt19937 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor(seed: number); + seed: number; + _state: Uint32Array; + _i: number; + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next(): number; +} +//# sourceMappingURL=Mt19937.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng/Mt19937.d.ts.map b/nodejs/node_modules/lib0/dist/prng/Mt19937.d.ts.map new file mode 100644 index 00000000..32364406 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng/Mt19937.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Mt19937.d.ts","sourceRoot":"","sources":["../../prng/Mt19937.js"],"names":[],"mappings":"AA8BA;;;;;;;;;;;;GAYG;AACH;IACE;;OAEG;IACH,kBAFW,MAAM,EAYhB;IATC,aAAgB;IAMhB,oBAAmB;IACnB,WAAW;IAIb;;;;OAIG;IACH,eAYC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng/Xoroshiro128plus.d.ts b/nodejs/node_modules/lib0/dist/prng/Xoroshiro128plus.d.ts new file mode 100644 index 00000000..1975394f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng/Xoroshiro128plus.d.ts @@ -0,0 +1,27 @@ +/** + * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures. + * + * This implementation follows the idea of the original xoroshiro128plus implementation, + * but is optimized for the JavaScript runtime. I.e. + * * The operations are performed on 32bit integers (the original implementation works with 64bit values). + * * The initial 128bit state is computed based on a 32bit seed and Xorshift32. + * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus. + * Caution: The last addition step works slightly different than in the original implementation - the add carry of the + * first 32bit addition is not carried over to the last 32bit. + * + * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c) + */ +export class Xoroshiro128plus { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor(seed: number); + seed: number; + state: Uint32Array; + _fresh: boolean; + /** + * @return {number} Float/Double in [0,1) + */ + next(): number; +} +//# sourceMappingURL=Xoroshiro128plus.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng/Xoroshiro128plus.d.ts.map b/nodejs/node_modules/lib0/dist/prng/Xoroshiro128plus.d.ts.map new file mode 100644 index 00000000..cb65cdc1 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng/Xoroshiro128plus.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Xoroshiro128plus.d.ts","sourceRoot":"","sources":["../../prng/Xoroshiro128plus.js"],"names":[],"mappings":"AAOA;;;;;;;;;;;;GAYG;AACH;IACE;;OAEG;IACH,kBAFW,MAAM,EAWhB;IARC,aAAgB;IAGhB,mBAA+B;IAI/B,gBAAkB;IAGpB;;OAEG;IACH,QAFY,MAAM,CA4BjB;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng/Xorshift32.d.ts b/nodejs/node_modules/lib0/dist/prng/Xorshift32.d.ts new file mode 100644 index 00000000..436b8bcf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng/Xorshift32.d.ts @@ -0,0 +1,21 @@ +/** + * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`. + */ +export class Xorshift32 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor(seed: number); + seed: number; + /** + * @type {number} + */ + _state: number; + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next(): number; +} +//# sourceMappingURL=Xorshift32.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/prng/Xorshift32.d.ts.map b/nodejs/node_modules/lib0/dist/prng/Xorshift32.d.ts.map new file mode 100644 index 00000000..0bf81994 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/prng/Xorshift32.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Xorshift32.d.ts","sourceRoot":"","sources":["../../prng/Xorshift32.js"],"names":[],"mappings":"AAMA;;GAEG;AACH;IACE;;OAEG;IACH,kBAFW,MAAM,EAQhB;IALC,aAAgB;IAChB;;OAEG;IACH,QAFU,MAAM,CAEE;IAGpB;;;;OAIG;IACH,eAOC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/promise-afe9dfc3.cjs b/nodejs/node_modules/lib0/dist/promise-afe9dfc3.cjs new file mode 100644 index 00000000..e57edb1c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise-afe9dfc3.cjs @@ -0,0 +1,125 @@ +'use strict'; + +var time = require('./time-bc2081b9.cjs'); + +/** + * Utility helpers to work with promises. + * + * @module promise + */ + +/** + * @template T + * @callback PromiseResolve + * @param {T|PromiseLike} [result] + */ + +/** + * @template T + * @param {function(PromiseResolve,function(Error):void):any} f + * @return {Promise} + */ +const create = f => /** @type {Promise} */ (new Promise(f)); + +/** + * @param {function(function():void,function(Error):void):void} f + * @return {Promise} + */ +const createEmpty = f => new Promise(f); + +/** + * `Promise.all` wait for all promises in the array to resolve and return the result + * @template {unknown[] | []} PS + * + * @param {PS} ps + * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>} + */ +const all = Promise.all.bind(Promise); + +/** + * @param {Error} [reason] + * @return {Promise} + */ +const reject = reason => Promise.reject(reason); + +/** + * @template T + * @param {T|void} res + * @return {Promise} + */ +const resolve = res => Promise.resolve(res); + +/** + * @template T + * @param {T} res + * @return {Promise} + */ +const resolveWith = res => Promise.resolve(res); + +/** + * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]] + * + * @param {number} timeout + * @param {function():boolean} check + * @param {number} [intervalResolution] + * @return {Promise} + */ +const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => { + const startTime = time.getUnixTime(); + const hasTimeout = timeout > 0; + const untilInterval = () => { + if (check()) { + clearInterval(intervalHandle); + resolve(); + } else if (hasTimeout) { + /* c8 ignore else */ + if (time.getUnixTime() - startTime > timeout) { + clearInterval(intervalHandle); + reject(new Error('Timeout')); + } + } + }; + const intervalHandle = setInterval(untilInterval, intervalResolution); +}); + +/** + * @param {number} timeout + * @return {Promise} + */ +const wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout)); + +/** + * Checks if an object is a promise using ducktyping. + * + * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this + * library has some insane environment where global Promise objects are overwritten. + * + * @param {any} p + * @return {boolean} + */ +const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally); + +var promise = /*#__PURE__*/Object.freeze({ + __proto__: null, + create: create, + createEmpty: createEmpty, + all: all, + reject: reject, + resolve: resolve, + resolveWith: resolveWith, + until: until, + wait: wait, + isPromise: isPromise +}); + +exports.all = all; +exports.create = create; +exports.createEmpty = createEmpty; +exports.isPromise = isPromise; +exports.promise = promise; +exports.reject = reject; +exports.resolve = resolve; +exports.resolveWith = resolveWith; +exports.until = until; +exports.wait = wait; +//# sourceMappingURL=promise-afe9dfc3.cjs.map diff --git a/nodejs/node_modules/lib0/dist/promise-afe9dfc3.cjs.map b/nodejs/node_modules/lib0/dist/promise-afe9dfc3.cjs.map new file mode 100644 index 00000000..bf7d54b7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise-afe9dfc3.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"promise-afe9dfc3.cjs","sources":["../promise.js"],"sourcesContent":["/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\nimport * as time from './time.js'\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve,function(Error):void):any} f\n * @return {Promise}\n */\nexport const create = f => /** @type {Promise} */ (new Promise(f))\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise}\n */\nexport const createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template {unknown[] | []} PS\n *\n * @param {PS} ps\n * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>}\n */\nexport const all = Promise.all.bind(Promise)\n\n/**\n * @param {Error} [reason]\n * @return {Promise}\n */\nexport const reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise}\n */\nexport const resolve = res => Promise.resolve(res)\n\n/**\n * @template T\n * @param {T} res\n * @return {Promise}\n */\nexport const resolveWith = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise}\n */\nexport const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n const startTime = time.getUnixTime()\n const hasTimeout = timeout > 0\n const untilInterval = () => {\n if (check()) {\n clearInterval(intervalHandle)\n resolve()\n } else if (hasTimeout) {\n /* c8 ignore else */\n if (time.getUnixTime() - startTime > timeout) {\n clearInterval(intervalHandle)\n reject(new Error('Timeout'))\n }\n }\n }\n const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {number} timeout\n * @return {Promise}\n */\nexport const wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nexport const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n"],"names":["time.getUnixTime"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,CAAC,CAAC,EAAC;AACrE;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,IAAI,IAAI,OAAO,CAAC,CAAC,EAAC;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,EAAC;AAC5C;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAC;AACtD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,GAAG,IAAI,OAAO,CAAC,OAA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ib0/dist/promise.cjs b/nodejs/node_modules/lib0/dist/promise.cjs new file mode 100644 index 00000000..0715682d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise.cjs @@ -0,0 +1,21 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./time-bc2081b9.cjs'); +var promise = require('./promise-afe9dfc3.cjs'); +require('./metric.cjs'); +require('./math-08e068f9.cjs'); + + + +exports.all = promise.all; +exports.create = promise.create; +exports.createEmpty = promise.createEmpty; +exports.isPromise = promise.isPromise; +exports.reject = promise.reject; +exports.resolve = promise.resolve; +exports.resolveWith = promise.resolveWith; +exports.until = promise.until; +exports.wait = promise.wait; +//# sourceMappingURL=promise.cjs.map diff --git a/nodejs/node_modules/lib0/dist/promise.cjs.map b/nodejs/node_modules/lib0/dist/promise.cjs.map new file mode 100644 index 00000000..f65009c2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/promise.d.ts b/nodejs/node_modules/lib0/dist/promise.d.ts new file mode 100644 index 00000000..0109982b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise.d.ts @@ -0,0 +1,21 @@ +export function create(f: (arg0: PromiseResolve, arg1: (arg0: Error) => void) => any): Promise; +export function createEmpty(f: (arg0: () => void, arg1: (arg0: Error) => void) => void): Promise; +/** + * `Promise.all` wait for all promises in the array to resolve and return the result + * @template {unknown[] | []} PS + * + * @param {PS} ps + * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>} + */ +export const all: { + (values: Iterable>): Promise[]>; + (values: T_1): Promise<{ -readonly [P in keyof T_1]: Awaited; }>; +}; +export function reject(reason?: Error | undefined): Promise; +export function resolve(res: void | T): Promise; +export function resolveWith(res: T): Promise; +export function until(timeout: number, check: () => boolean, intervalResolution?: number | undefined): Promise; +export function wait(timeout: number): Promise; +export function isPromise(p: any): boolean; +export type PromiseResolve = (result?: T | PromiseLike | undefined) => any; +//# sourceMappingURL=promise.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/promise.d.ts.map b/nodejs/node_modules/lib0/dist/promise.d.ts.map new file mode 100644 index 00000000..4aed1ce0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.d.ts","sourceRoot":"","sources":["../promise.js"],"names":[],"mappings":"AAmBO,oEAHwC,KAAK,KAAE,IAAI,KAAE,GAAG,cAGM;AAM9D,4CAHwB,IAAI,eAAU,KAAK,KAAE,IAAI,KAAE,IAAI,GAClD,QAAQ,IAAI,CAAC,CAEqB;AAE9C;;;;;;GAMG;AACH;;;EAA4C;AAMrC,oDAFK,QAAQ,KAAK,CAAC,CAE4B;AAO/C,6DAA2C;AAO3C,mDAA+C;AAU/C,+BALI,MAAM,eACK,OAAO,4CAEjB,QAAQ,IAAI,CAAC,CAkBvB;AAMK,8BAHI,MAAM,GACL,QAAQ,SAAS,CAAC,CAE0D;AAWjF,6BAHI,GAAG,GACF,OAAO,CAEwE"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/promise.test.d.ts b/nodejs/node_modules/lib0/dist/promise.test.d.ts new file mode 100644 index 00000000..aa230e1b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise.test.d.ts @@ -0,0 +1,5 @@ +export function testRepeatPromise(_tc: t.TestCase): Promise; +export function testispromise(_tc: t.TestCase): void; +export function testTypings(_tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=promise.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/promise.test.d.ts.map b/nodejs/node_modules/lib0/dist/promise.test.d.ts.map new file mode 100644 index 00000000..b819e3b5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/promise.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.test.d.ts","sourceRoot":"","sources":["../promise.test.js"],"names":[],"mappings":"AA6BO,uCAFI,EAAE,QAAQ,iBAgBpB;AAKM,mCAFI,EAAE,QAAQ,QAapB;AAKM,iCAFI,EAAE,QAAQ,iBAapB;mBA1EkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/queue.cjs b/nodejs/node_modules/lib0/dist/queue.cjs new file mode 100644 index 00000000..94392706 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/queue.cjs @@ -0,0 +1,97 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +class QueueNode { + constructor () { + /** + * @type {QueueNode|null} + */ + this.next = null; + } +} + +/** + * @template V + */ +class QueueValue extends QueueNode { + /** + * @param {V} v + */ + constructor (v) { + super(); + this.v = v; + } +} + +/** + * @template {QueueNode} N + */ +class Queue { + constructor () { + /** + * @type {N | null} + */ + this.start = null; + /** + * @type {N | null} + */ + this.end = null; + } +} + +/** + * @note The queue implementation is experimental and unfinished. + * Don't use this in production yet. + * + * @template {QueueNode} N + * @return {Queue} + */ +const create = () => new Queue(); + +/** + * @param {Queue} queue + */ +const isEmpty = queue => queue.start === null; + +/** + * @template {Queue} Q + * @param {Q} queue + * @param {Q extends Queue ? N : never} n + */ +const enqueue = (queue, n) => { + if (queue.end !== null) { + queue.end.next = n; + queue.end = n; + } else { + queue.end = n; + queue.start = n; + } +}; + +/** + * @template {QueueNode} N + * @param {Queue} queue + * @return {N | null} + */ +const dequeue = queue => { + const n = queue.start; + if (n !== null) { + // @ts-ignore + queue.start = n.next; + if (queue.start === null) { + queue.end = null; + } + return n + } + return null +}; + +exports.Queue = Queue; +exports.QueueNode = QueueNode; +exports.QueueValue = QueueValue; +exports.create = create; +exports.dequeue = dequeue; +exports.enqueue = enqueue; +exports.isEmpty = isEmpty; +//# sourceMappingURL=queue.cjs.map diff --git a/nodejs/node_modules/lib0/dist/queue.cjs.map b/nodejs/node_modules/lib0/dist/queue.cjs.map new file mode 100644 index 00000000..b6c47aa3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/queue.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.cjs","sources":["../queue.js"],"sourcesContent":["export class QueueNode {\n constructor () {\n /**\n * @type {QueueNode|null}\n */\n this.next = null\n }\n}\n\n/**\n * @template V\n */\nexport class QueueValue extends QueueNode {\n /**\n * @param {V} v\n */\n constructor (v) {\n super()\n this.v = v\n }\n}\n\n/**\n * @template {QueueNode} N\n */\nexport class Queue {\n constructor () {\n /**\n * @type {N | null}\n */\n this.start = null\n /**\n * @type {N | null}\n */\n this.end = null\n }\n}\n\n/**\n * @note The queue implementation is experimental and unfinished.\n * Don't use this in production yet.\n *\n * @template {QueueNode} N\n * @return {Queue}\n */\nexport const create = () => new Queue()\n\n/**\n * @param {Queue} queue\n */\nexport const isEmpty = queue => queue.start === null\n\n/**\n * @template {Queue} Q\n * @param {Q} queue\n * @param {Q extends Queue ? N : never} n\n */\nexport const enqueue = (queue, n) => {\n if (queue.end !== null) {\n queue.end.next = n\n queue.end = n\n } else {\n queue.end = n\n queue.start = n\n }\n}\n\n/**\n * @template {QueueNode} N\n * @param {Queue} queue\n * @return {N | null}\n */\nexport const dequeue = queue => {\n const n = queue.start\n if (n !== null) {\n // @ts-ignore\n queue.start = n.next\n if (queue.start === null) {\n queue.end = null\n }\n return n\n }\n return null\n}\n"],"names":[],"mappings":";;;;AAAO,MAAM,SAAS,CAAC;AACvB,EAAE,WAAW,CAAC,GAAG;AACjB;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,KAAI;AACpB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACO,MAAM,UAAU,SAAS,SAAS,CAAC;AAC1C;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE;AAClB,IAAI,KAAK,GAAE;AACX,IAAI,IAAI,CAAC,CAAC,GAAG,EAAC;AACd,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACO,MAAM,KAAK,CAAC;AACnB,EAAE,WAAW,CAAC,GAAG;AACjB;AACA;AACA;AACA,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB;AACA;AACA;AACA,IAAI,IAAI,CAAC,GAAG,GAAG,KAAI;AACnB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,IAAI,KAAK,GAAE;AACvC;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,KAAI;AACpD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,CAAC,KAAK,EAAE,CAAC,KAAK;AACrC,EAAE,IAAI,KAAK,CAAC,GAAG,KAAK,IAAI,EAAE;AAC1B,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,GAAG,EAAC;AACtB,IAAI,KAAK,CAAC,GAAG,GAAG,EAAC;AACjB,GAAG,MAAM;AACT,IAAI,KAAK,CAAC,GAAG,GAAG,EAAC;AACjB,IAAI,KAAK,CAAC,KAAK,GAAG,EAAC;AACnB,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,KAAK,IAAI;AAChC,EAAE,MAAM,CAAC,GAAG,KAAK,CAAC,MAAK;AACvB,EAAE,IAAI,CAAC,KAAK,IAAI,EAAE;AAClB;AACA,IAAI,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,KAAI;AACxB,IAAI,IAAI,KAAK,CAAC,KAAK,KAAK,IAAI,EAAE;AAC9B,MAAM,KAAK,CAAC,GAAG,GAAG,KAAI;AACtB,KAAK;AACL,IAAI,OAAO,CAAC;AACZ,GAAG;AACH,EAAE,OAAO,IAAI;AACb;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/queue.d.ts b/nodejs/node_modules/lib0/dist/queue.d.ts new file mode 100644 index 00000000..4ed95974 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/queue.d.ts @@ -0,0 +1,34 @@ +export class QueueNode { + /** + * @type {QueueNode|null} + */ + next: QueueNode | null; +} +/** + * @template V + */ +export class QueueValue extends QueueNode { + /** + * @param {V} v + */ + constructor(v: V); + v: V; +} +/** + * @template {QueueNode} N + */ +export class Queue { + /** + * @type {N | null} + */ + start: N | null; + /** + * @type {N | null} + */ + end: N | null; +} +export function create(): Queue; +export function isEmpty(queue: Queue): boolean; +export function enqueue>(queue: Q, n: Q extends Queue ? N : never): void; +export function dequeue(queue: Queue): N | null; +//# sourceMappingURL=queue.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/queue.d.ts.map b/nodejs/node_modules/lib0/dist/queue.d.ts.map new file mode 100644 index 00000000..4d0da5fe --- /dev/null +++ b/nodejs/node_modules/lib0/dist/queue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["../queue.js"],"names":[],"mappings":"AAAA;IAEI;;OAEG;IACH,MAFU,SAAS,GAAC,IAAI,CAER;CAEnB;AAED;;GAEG;AACH;IACE;;OAEG;IACH,eAFW,CAAC,EAKX;IADC,KAAU;CAEb;AAED;;GAEG;AACH;IAEI;;OAEG;IACH,OAFU,CAAC,GAAG,IAAI,CAED;IACjB;;OAEG;IACH,KAFU,CAAC,GAAG,IAAI,CAEH;CAElB;AASM,wDAAgC;AAKhC,+BAFI,MAAM,GAAG,CAAC,WAE+B;AAO7C,yHAQN;AAOM,wEAWN"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/queue.test.d.ts b/nodejs/node_modules/lib0/dist/queue.test.d.ts new file mode 100644 index 00000000..7caa54d9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/queue.test.d.ts @@ -0,0 +1,3 @@ +export function testEnqueueDequeue(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=queue.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/queue.test.d.ts.map b/nodejs/node_modules/lib0/dist/queue.test.d.ts.map new file mode 100644 index 00000000..da92a489 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/queue.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.test.d.ts","sourceRoot":"","sources":["../queue.test.js"],"names":[],"mappings":"AAMO,wCAFI,EAAE,QAAQ,QA8BpB;mBAlCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/rabin-gf2-polynomial.cjs b/nodejs/node_modules/lib0/dist/rabin-gf2-polynomial.cjs new file mode 100644 index 00000000..77eb2a74 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rabin-gf2-polynomial.cjs @@ -0,0 +1,439 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('./math-08e068f9.cjs'); +var webcrypto = require('lib0/webcrypto'); +var array = require('./array-704ca50e.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); +require('./set-0f209abb.cjs'); +require('./string-6d104757.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./map-0dabcc55.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./decoding-000d097f.cjs'); +require('./error-8582d695.cjs'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var webcrypto__namespace = /*#__PURE__*/_interopNamespace(webcrypto); + +/** + * The idea of the Rabin fingerprint algorithm is to represent the binary as a polynomial in a + * finite field (Galois Field G(2)). The polynomial will then be taken "modulo" by an irreducible + * polynomial of the desired size. + * + * This implementation is inefficient and is solely used to verify the actually performant + * implementation in `./rabin.js`. + * + * @module rabin-gf2-polynomial + */ + +/** + * @param {number} degree + */ +const _degreeToMinByteLength = degree => math.floor(degree / 8) + 1; + +/** + * This is a GF2 Polynomial abstraction that is not meant for production! + * + * It is easy to understand and it's correctness is as obvious as possible. It can be used to verify + * efficient implementations of algorithms on GF2. + */ +class GF2Polynomial { + constructor () { + /** + * @type {Set} + */ + this.degrees = new Set(); + } +} + +/** + * From Uint8Array (MSB). + * + * @param {Uint8Array} bytes + */ +const createFromBytes = bytes => { + const p = new GF2Polynomial(); + for (let bsi = bytes.length - 1, currDegree = 0; bsi >= 0; bsi--) { + const currByte = bytes[bsi]; + for (let i = 0; i < 8; i++) { + if (((currByte >>> i) & 1) === 1) { + p.degrees.add(currDegree); + } + currDegree++; + } + } + return p +}; + +/** + * Transform to Uint8Array (MSB). + * + * @param {GF2Polynomial} p + * @param {number} byteLength + */ +const toUint8Array = (p, byteLength = _degreeToMinByteLength(getHighestDegree(p))) => { + const buf = buffer.createUint8ArrayFromLen(byteLength); + /** + * @param {number} i + */ + const setBit = i => { + const bi = math.floor(i / 8); + buf[buf.length - 1 - bi] |= (1 << (i % 8)); + }; + p.degrees.forEach(setBit); + return buf +}; + +/** + * Create from unsigned integer (max 32bit uint) - read most-significant-byte first. + * + * @param {number} uint + */ +const createFromUint = uint => { + const buf = new Uint8Array(4); + for (let i = 0; i < 4; i++) { + buf[i] = uint >>> 8 * (3 - i); + } + return createFromBytes(buf) +}; + +/** + * Create a random polynomial of a specified degree. + * + * @param {number} degree + */ +const createRandom = degree => { + const bs = new Uint8Array(_degreeToMinByteLength(degree)); + webcrypto__namespace.getRandomValues(bs); + // Get first byte and explicitly set the bit of "degree" to 1 (the result must have the specified + // degree). + const firstByte = bs[0] | 1 << (degree % 8); + // Find out how many bits of the first byte need to be filled with zeros because they are >degree. + const zeros = 7 - (degree % 8); + bs[0] = ((firstByte << zeros) & 0xff) >>> zeros; + return createFromBytes(bs) +}; + +/** + * @param {GF2Polynomial} p + * @return number + */ +const getHighestDegree = p => array.fold(array.from(p.degrees), 0, math.max); + +/** + * Add (+) p2 int the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const addInto = (p1, p2) => { + p2.degrees.forEach(degree => { + if (p1.degrees.has(degree)) { + p1.degrees.delete(degree); + } else { + p1.degrees.add(degree); + } + }); +}; + +/** + * Or (|) p2 into the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const orInto = (p1, p2) => { + p2.degrees.forEach(degree => { + p1.degrees.add(degree); + }); +}; + +/** + * Add (+) p2 to the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const add = (p1, p2) => { + const result = new GF2Polynomial(); + p2.degrees.forEach(degree => { + if (!p1.degrees.has(degree)) { + result.degrees.add(degree); + } + }); + p1.degrees.forEach(degree => { + if (!p2.degrees.has(degree)) { + result.degrees.add(degree); + } + }); + return result +}; + +/** + * Add (+) p2 to the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p + */ +const clone = (p) => { + const result = new GF2Polynomial(); + p.degrees.forEach(d => result.degrees.add(d)); + return result +}; + +/** + * Add (+) p2 to the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p + * @param {number} degree + */ +const addDegreeInto = (p, degree) => { + if (p.degrees.has(degree)) { + p.degrees.delete(degree); + } else { + p.degrees.add(degree); + } +}; + +/** + * Multiply (•) p1 with p2 and store the result in p1. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const multiply = (p1, p2) => { + const result = new GF2Polynomial(); + p1.degrees.forEach(degree1 => { + p2.degrees.forEach(degree2 => { + addDegreeInto(result, degree1 + degree2); + }); + }); + return result +}; + +/** + * Multiply (•) p1 with p2 and store the result in p1. + * + * @param {GF2Polynomial} p + * @param {number} shift + */ +const shiftLeft = (p, shift) => { + const result = new GF2Polynomial(); + p.degrees.forEach(degree => { + const r = degree + shift; + r >= 0 && result.degrees.add(r); + }); + return result +}; + +/** + * Computes p1 % p2. I.e. the remainder of p1/p2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const mod = (p1, p2) => { + const maxDeg1 = getHighestDegree(p1); + const maxDeg2 = getHighestDegree(p2); + const result = clone(p1); + for (let i = maxDeg1 - maxDeg2; i >= 0; i--) { + if (result.degrees.has(maxDeg2 + i)) { + const shifted = shiftLeft(p2, i); + addInto(result, shifted); + } + } + return result +}; + +/** + * Computes (p^e mod m). + * + * http://en.wikipedia.org/wiki/Modular_exponentiation + * + * @param {GF2Polynomial} p + * @param {number} e + * @param {GF2Polynomial} m + */ +const modPow = (p, e, m) => { + let result = ONE; + while (true) { + if ((e & 1) === 1) { + result = mod(multiply(result, p), m); + } + e >>>= 1; + if (e === 0) { + return result + } + p = mod(multiply(p, p), m); + } +}; + +/** + * Find the greatest common divisor using Euclid's Algorithm. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const gcd = (p1, p2) => { + while (p2.degrees.size > 0) { + const modded = mod(p1, p2); + p1 = p2; + p2 = modded; + } + return p1 +}; + +/** + * true iff p1 equals p2 + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +const equals = (p1, p2) => { + if (p1.degrees.size !== p2.degrees.size) return false + for (const d of p1.degrees) { + if (!p2.degrees.has(d)) return false + } + return true +}; + +const X = createFromBytes(new Uint8Array([2])); +const ONE = createFromBytes(new Uint8Array([1])); + +/** + * Computes ( x^(2^p) - x ) mod f + * + * (shamelessly copied from + * https://github.com/opendedup/rabinfingerprint/blob/master/src/org/rabinfingerprint/polynomial/Polynomial.java) + * + * @param {GF2Polynomial} f + * @param {number} p + */ +const reduceExponent = (f, p) => { + // compute (x^q^p mod f) + const q2p = math.pow(2, p); + const x2q2p = modPow(X, q2p, f); + // subtract (x mod f) + return mod(add(x2q2p, X), f) +}; + +/** + * BenOr Reducibility Test + * + * Tests and Constructions of Irreducible Polynomials over Finite Fields + * (1997) Shuhong Gao, Daniel Panario + * + * http://citeseer.ist.psu.edu/cache/papers/cs/27167/http:zSzzSzwww.math.clemson.eduzSzfacultyzSzGaozSzpaperszSzGP97a.pdf/gao97tests.pdf + * + * @param {GF2Polynomial} p + */ +const isIrreducibleBenOr = p => { + const degree = getHighestDegree(p); + for (let i = 1; i < degree / 2; i++) { + const b = reduceExponent(p, i); + const g = gcd(p, b); + if (!equals(g, ONE)) { + return false + } + } + return true +}; + +/** + * @param {number} degree + */ +const createIrreducible = degree => { + while (true) { + const p = createRandom(degree); + if (isIrreducibleBenOr(p)) return p + } +}; + +/** + * Create a fingerprint of buf using the irreducible polynomial m. + * + * @param {Uint8Array} buf + * @param {GF2Polynomial} m + */ +const fingerprint = (buf, m) => toUint8Array(mod(createFromBytes(buf), m), _degreeToMinByteLength(getHighestDegree(m) - 1)); + +class RabinPolynomialEncoder { + /** + * @param {GF2Polynomial} m The irreducible polynomial + */ + constructor (m) { + this.fingerprint = new GF2Polynomial(); + this.m = m; + } + + /** + * @param {number} b + */ + write (b) { + const bp = createFromBytes(new Uint8Array([b])); + const fingerprint = shiftLeft(this.fingerprint, 8); + orInto(fingerprint, bp); + this.fingerprint = mod(fingerprint, this.m); + } + + getFingerprint () { + return toUint8Array(this.fingerprint, _degreeToMinByteLength(getHighestDegree(this.m) - 1)) + } +} + +exports.GF2Polynomial = GF2Polynomial; +exports.RabinPolynomialEncoder = RabinPolynomialEncoder; +exports.add = add; +exports.addDegreeInto = addDegreeInto; +exports.addInto = addInto; +exports.clone = clone; +exports.createFromBytes = createFromBytes; +exports.createFromUint = createFromUint; +exports.createIrreducible = createIrreducible; +exports.createRandom = createRandom; +exports.equals = equals; +exports.fingerprint = fingerprint; +exports.gcd = gcd; +exports.getHighestDegree = getHighestDegree; +exports.isIrreducibleBenOr = isIrreducibleBenOr; +exports.mod = mod; +exports.modPow = modPow; +exports.multiply = multiply; +exports.orInto = orInto; +exports.shiftLeft = shiftLeft; +exports.toUint8Array = toUint8Array; +//# sourceMappingURL=rabin-gf2-polynomial.cjs.map diff --git a/nodejs/node_modules/lib0/dist/rabin-gf2-polynomial.cjs.map b/nodejs/node_modules/lib0/dist/rabin-gf2-polynomial.cjs.map new file mode 100644 index 00000000..b99e7714 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rabin-gf2-polynomial.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin-gf2-polynomial.cjs","sources":["../hash/rabin-gf2-polynomial.js"],"sourcesContent":["/**\n * The idea of the Rabin fingerprint algorithm is to represent the binary as a polynomial in a\n * finite field (Galois Field G(2)). The polynomial will then be taken \"modulo\" by an irreducible\n * polynomial of the desired size.\n *\n * This implementation is inefficient and is solely used to verify the actually performant\n * implementation in `./rabin.js`.\n *\n * @module rabin-gf2-polynomial\n */\n\nimport * as math from '../math.js'\nimport * as webcrypto from 'lib0/webcrypto'\nimport * as array from '../array.js'\nimport * as buffer from '../buffer.js'\n\n/**\n * @param {number} degree\n */\nconst _degreeToMinByteLength = degree => math.floor(degree / 8) + 1\n\n/**\n * This is a GF2 Polynomial abstraction that is not meant for production!\n *\n * It is easy to understand and it's correctness is as obvious as possible. It can be used to verify\n * efficient implementations of algorithms on GF2.\n */\nexport class GF2Polynomial {\n constructor () {\n /**\n * @type {Set}\n */\n this.degrees = new Set()\n }\n}\n\n/**\n * From Uint8Array (MSB).\n *\n * @param {Uint8Array} bytes\n */\nexport const createFromBytes = bytes => {\n const p = new GF2Polynomial()\n for (let bsi = bytes.length - 1, currDegree = 0; bsi >= 0; bsi--) {\n const currByte = bytes[bsi]\n for (let i = 0; i < 8; i++) {\n if (((currByte >>> i) & 1) === 1) {\n p.degrees.add(currDegree)\n }\n currDegree++\n }\n }\n return p\n}\n\n/**\n * Transform to Uint8Array (MSB).\n *\n * @param {GF2Polynomial} p\n * @param {number} byteLength\n */\nexport const toUint8Array = (p, byteLength = _degreeToMinByteLength(getHighestDegree(p))) => {\n const buf = buffer.createUint8ArrayFromLen(byteLength)\n /**\n * @param {number} i\n */\n const setBit = i => {\n const bi = math.floor(i / 8)\n buf[buf.length - 1 - bi] |= (1 << (i % 8))\n }\n p.degrees.forEach(setBit)\n return buf\n}\n\n/**\n * Create from unsigned integer (max 32bit uint) - read most-significant-byte first.\n *\n * @param {number} uint\n */\nexport const createFromUint = uint => {\n const buf = new Uint8Array(4)\n for (let i = 0; i < 4; i++) {\n buf[i] = uint >>> 8 * (3 - i)\n }\n return createFromBytes(buf)\n}\n\n/**\n * Create a random polynomial of a specified degree.\n *\n * @param {number} degree\n */\nexport const createRandom = degree => {\n const bs = new Uint8Array(_degreeToMinByteLength(degree))\n webcrypto.getRandomValues(bs)\n // Get first byte and explicitly set the bit of \"degree\" to 1 (the result must have the specified\n // degree).\n const firstByte = bs[0] | 1 << (degree % 8)\n // Find out how many bits of the first byte need to be filled with zeros because they are >degree.\n const zeros = 7 - (degree % 8)\n bs[0] = ((firstByte << zeros) & 0xff) >>> zeros\n return createFromBytes(bs)\n}\n\n/**\n * @param {GF2Polynomial} p\n * @return number\n */\nexport const getHighestDegree = p => array.fold(array.from(p.degrees), 0, math.max)\n\n/**\n * Add (+) p2 int the p1 polynomial.\n *\n * Addition is defined as xor in F2. Substraction is equivalent to addition in F2.\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const addInto = (p1, p2) => {\n p2.degrees.forEach(degree => {\n if (p1.degrees.has(degree)) {\n p1.degrees.delete(degree)\n } else {\n p1.degrees.add(degree)\n }\n })\n}\n\n/**\n * Or (|) p2 into the p1 polynomial.\n *\n * Addition is defined as xor in F2. Substraction is equivalent to addition in F2.\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const orInto = (p1, p2) => {\n p2.degrees.forEach(degree => {\n p1.degrees.add(degree)\n })\n}\n\n/**\n * Add (+) p2 to the p1 polynomial.\n *\n * Addition is defined as xor in F2. Substraction is equivalent to addition in F2.\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const add = (p1, p2) => {\n const result = new GF2Polynomial()\n p2.degrees.forEach(degree => {\n if (!p1.degrees.has(degree)) {\n result.degrees.add(degree)\n }\n })\n p1.degrees.forEach(degree => {\n if (!p2.degrees.has(degree)) {\n result.degrees.add(degree)\n }\n })\n return result\n}\n\n/**\n * Add (+) p2 to the p1 polynomial.\n *\n * Addition is defined as xor in F2. Substraction is equivalent to addition in F2.\n *\n * @param {GF2Polynomial} p\n */\nexport const clone = (p) => {\n const result = new GF2Polynomial()\n p.degrees.forEach(d => result.degrees.add(d))\n return result\n}\n\n/**\n * Add (+) p2 to the p1 polynomial.\n *\n * Addition is defined as xor in F2. Substraction is equivalent to addition in F2.\n *\n * @param {GF2Polynomial} p\n * @param {number} degree\n */\nexport const addDegreeInto = (p, degree) => {\n if (p.degrees.has(degree)) {\n p.degrees.delete(degree)\n } else {\n p.degrees.add(degree)\n }\n}\n\n/**\n * Multiply (•) p1 with p2 and store the result in p1.\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const multiply = (p1, p2) => {\n const result = new GF2Polynomial()\n p1.degrees.forEach(degree1 => {\n p2.degrees.forEach(degree2 => {\n addDegreeInto(result, degree1 + degree2)\n })\n })\n return result\n}\n\n/**\n * Multiply (•) p1 with p2 and store the result in p1.\n *\n * @param {GF2Polynomial} p\n * @param {number} shift\n */\nexport const shiftLeft = (p, shift) => {\n const result = new GF2Polynomial()\n p.degrees.forEach(degree => {\n const r = degree + shift\n r >= 0 && result.degrees.add(r)\n })\n return result\n}\n\n/**\n * Computes p1 % p2. I.e. the remainder of p1/p2.\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const mod = (p1, p2) => {\n const maxDeg1 = getHighestDegree(p1)\n const maxDeg2 = getHighestDegree(p2)\n const result = clone(p1)\n for (let i = maxDeg1 - maxDeg2; i >= 0; i--) {\n if (result.degrees.has(maxDeg2 + i)) {\n const shifted = shiftLeft(p2, i)\n addInto(result, shifted)\n }\n }\n return result\n}\n\n/**\n * Computes (p^e mod m).\n *\n * http://en.wikipedia.org/wiki/Modular_exponentiation\n *\n * @param {GF2Polynomial} p\n * @param {number} e\n * @param {GF2Polynomial} m\n */\nexport const modPow = (p, e, m) => {\n let result = ONE\n while (true) {\n if ((e & 1) === 1) {\n result = mod(multiply(result, p), m)\n }\n e >>>= 1\n if (e === 0) {\n return result\n }\n p = mod(multiply(p, p), m)\n }\n}\n\n/**\n * Find the greatest common divisor using Euclid's Algorithm.\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const gcd = (p1, p2) => {\n while (p2.degrees.size > 0) {\n const modded = mod(p1, p2)\n p1 = p2\n p2 = modded\n }\n return p1\n}\n\n/**\n * true iff p1 equals p2\n *\n * @param {GF2Polynomial} p1\n * @param {GF2Polynomial} p2\n */\nexport const equals = (p1, p2) => {\n if (p1.degrees.size !== p2.degrees.size) return false\n for (const d of p1.degrees) {\n if (!p2.degrees.has(d)) return false\n }\n return true\n}\n\nconst X = createFromBytes(new Uint8Array([2]))\nconst ONE = createFromBytes(new Uint8Array([1]))\n\n/**\n * Computes ( x^(2^p) - x ) mod f\n *\n * (shamelessly copied from\n * https://github.com/opendedup/rabinfingerprint/blob/master/src/org/rabinfingerprint/polynomial/Polynomial.java)\n *\n * @param {GF2Polynomial} f\n * @param {number} p\n */\nconst reduceExponent = (f, p) => {\n // compute (x^q^p mod f)\n const q2p = math.pow(2, p)\n const x2q2p = modPow(X, q2p, f)\n // subtract (x mod f)\n return mod(add(x2q2p, X), f)\n}\n\n/**\n * BenOr Reducibility Test\n *\n * Tests and Constructions of Irreducible Polynomials over Finite Fields\n * (1997) Shuhong Gao, Daniel Panario\n *\n * http://citeseer.ist.psu.edu/cache/papers/cs/27167/http:zSzzSzwww.math.clemson.eduzSzfacultyzSzGaozSzpaperszSzGP97a.pdf/gao97tests.pdf\n *\n * @param {GF2Polynomial} p\n */\nexport const isIrreducibleBenOr = p => {\n const degree = getHighestDegree(p)\n for (let i = 1; i < degree / 2; i++) {\n const b = reduceExponent(p, i)\n const g = gcd(p, b)\n if (!equals(g, ONE)) {\n return false\n }\n }\n return true\n}\n\n/**\n * @param {number} degree\n */\nexport const createIrreducible = degree => {\n while (true) {\n const p = createRandom(degree)\n if (isIrreducibleBenOr(p)) return p\n }\n}\n\n/**\n * Create a fingerprint of buf using the irreducible polynomial m.\n *\n * @param {Uint8Array} buf\n * @param {GF2Polynomial} m\n */\nexport const fingerprint = (buf, m) => toUint8Array(mod(createFromBytes(buf), m), _degreeToMinByteLength(getHighestDegree(m) - 1))\n\nexport class RabinPolynomialEncoder {\n /**\n * @param {GF2Polynomial} m The irreducible polynomial\n */\n constructor (m) {\n this.fingerprint = new GF2Polynomial()\n this.m = m\n }\n\n /**\n * @param {number} b\n */\n write (b) {\n const bp = createFromBytes(new Uint8Array([b]))\n const fingerprint = shiftLeft(this.fingerprint, 8)\n orInto(fingerprint, bp)\n this.fingerprint = mod(fingerprint, this.m)\n }\n\n getFingerprint () {\n return toUint8Array(this.fingerprint, _degreeToMinByteLength(getHighestDegree(this.m) - 1))\n }\n}\n"],"names":["math.floor","buffer.createUint8ArrayFromLen","webcrypto","array.fold","array.from","math.max","math.pow"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAMA;AACA;AACA;AACA;AACA,MAAM,sBAAsB,GAAG,MAAM,IAAIA,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,EAAC;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,aAAa,CAAC;AAC3B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;AACA;AACA;AACA;AACA,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE;AACZ,IAAI,MAAM,EAAE,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,EAAC;AACnD,IAAI,MAAM,WAAW,GAAG,SAAS,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,EAAC;AACtD,IAAI,MAAM,CAAC,WAAW,EAAE,EAAE,EAAC;AAC3B,IAAI,IAAI,CAAC,WAAW,GAAG,GAAG,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,EAAC;AAC/C,GAAG;AACH;AACA,EAAE,cAAc,CAAC,GAAG;AACpB,IAAI,OAAO,YAAY,CAAC,IAAI,CAAC,WAAW,EAAE,sBAAsB,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAC/F,GAAG;AACH;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/rabin-uncached.cjs b/nodejs/node_modules/lib0/dist/rabin-uncached.cjs new file mode 100644 index 00000000..5e244044 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rabin-uncached.cjs @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('./math-08e068f9.cjs'); +var buffer = require('./buffer-f11b8d4d.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./map-0dabcc55.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./decoding-000d097f.cjs'); +require('./error-8582d695.cjs'); + +/** + * It is not recommended to use this package. This is the uncached implementation of the rabin + * fingerprint algorithm. However, it can be used to verify the `rabin.js` implementation. + * + * @module rabin-uncached + */ + +class RabinUncachedEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor (m) { + this.m = m; + this.blen = m.byteLength; + this.bs = new Uint8Array(this.blen); + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + this.bpos = 0; + } + + /** + * Add/Xor/Substract bytes. + * + * Discards bytes that are out of range. + * @todo put this in function or inline + * + * @param {Uint8Array} cs + */ + add (cs) { + const copyLen = math.min(this.blen, cs.byteLength); + // copy from right to left until max is reached + for (let i = 0; i < copyLen; i++) { + this.bs[(this.bpos + this.blen - i - 1) % this.blen] ^= cs[cs.byteLength - i - 1]; + } + } + + /** + * @param {number} byte + */ + write (byte) { + // [0,m1,m2,b] + // x <- bpos + // Shift one byte to the left, add b + this.bs[this.bpos] = byte; + this.bpos = (this.bpos + 1) % this.blen; + // mod + for (let i = 7; i >= 0; i--) { + if (((this.bs[this.bpos] >>> i) & 1) === 1) { + this.add(buffer.shiftNBitsLeft(this.m, i)); + } + } + // if (this.bs[this.bpos] !== 0) { error.unexpectedCase() } + // assert(this.bs[this.bpos] === 0) + } + + getFingerprint () { + const result = new Uint8Array(this.blen - 1); + for (let i = 0; i < result.byteLength; i++) { + result[i] = this.bs[(this.bpos + i + 1) % this.blen]; + } + return result + } +} + +exports.RabinUncachedEncoder = RabinUncachedEncoder; +//# sourceMappingURL=rabin-uncached.cjs.map diff --git a/nodejs/node_modules/lib0/dist/rabin-uncached.cjs.map b/nodejs/node_modules/lib0/dist/rabin-uncached.cjs.map new file mode 100644 index 00000000..a38cdbd7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rabin-uncached.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin-uncached.cjs","sources":["../hash/rabin-uncached.js"],"sourcesContent":["/**\n * It is not recommended to use this package. This is the uncached implementation of the rabin\n * fingerprint algorithm. However, it can be used to verify the `rabin.js` implementation.\n *\n * @module rabin-uncached\n */\n\nimport * as math from '../math.js'\nimport * as buffer from '../buffer.js'\n\nexport class RabinUncachedEncoder {\n /**\n * @param {Uint8Array} m assert(m[0] === 1)\n */\n constructor (m) {\n this.m = m\n this.blen = m.byteLength\n this.bs = new Uint8Array(this.blen)\n /**\n * This describes the position of the most significant byte (starts with 0 and increases with\n * shift)\n */\n this.bpos = 0\n }\n\n /**\n * Add/Xor/Substract bytes.\n *\n * Discards bytes that are out of range.\n * @todo put this in function or inline\n *\n * @param {Uint8Array} cs\n */\n add (cs) {\n const copyLen = math.min(this.blen, cs.byteLength)\n // copy from right to left until max is reached\n for (let i = 0; i < copyLen; i++) {\n this.bs[(this.bpos + this.blen - i - 1) % this.blen] ^= cs[cs.byteLength - i - 1]\n }\n }\n\n /**\n * @param {number} byte\n */\n write (byte) {\n // [0,m1,m2,b]\n // x <- bpos\n // Shift one byte to the left, add b\n this.bs[this.bpos] = byte\n this.bpos = (this.bpos + 1) % this.blen\n // mod\n for (let i = 7; i >= 0; i--) {\n if (((this.bs[this.bpos] >>> i) & 1) === 1) {\n this.add(buffer.shiftNBitsLeft(this.m, i))\n }\n }\n // if (this.bs[this.bpos] !== 0) { error.unexpectedCase() }\n // assert(this.bs[this.bpos] === 0)\n }\n\n getFingerprint () {\n const result = new Uint8Array(this.blen - 1)\n for (let i = 0; i < result.byteLength; i++) {\n result[i] = this.bs[(this.bpos + i + 1) % this.blen]\n }\n return result\n }\n}\n"],"names":["math.min","buffer.shiftNBitsLeft"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AAIA;AACO,MAAM,oBAAoB,CAAC;AAClC;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE;AAClB,IAAI,IAAI,CAAC,CAAC,GAAG,EAAC;AACd,IAAI,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,WAAU;AAC5B,IAAI,IAAI,CAAC,EAAE,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,EAAC;AACvC;AACA;AACA;AACA;AACA,I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AC,IAAI,GAAG,CAAC,EAAC;AAChD,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;AAChD,MAAM,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,EAAC;AAC1D,KAAK;AACL,IAAI,OAAO,MAAM;AACjB,GAAG;AACH;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/rabin.cjs b/nodejs/node_modules/lib0/dist/rabin.cjs new file mode 100644 index 00000000..19207546 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rabin.cjs @@ -0,0 +1,127 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var buffer = require('./buffer-f11b8d4d.cjs'); +var map = require('./map-0dabcc55.cjs'); +require('./string-6d104757.cjs'); +require('./array-704ca50e.cjs'); +require('./set-0f209abb.cjs'); +require('./environment-f4d7c3e5.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./function-314fdc56.cjs'); +require('./object-fecf6a7b.cjs'); +require('./math-08e068f9.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./binary-ac8e39e2.cjs'); +require('./decoding-000d097f.cjs'); +require('./error-8582d695.cjs'); + +/** + * @module rabin + * + * Very efficient & versatile fingerprint/hashing algorithm. However, it is not cryptographically + * secure. Well suited for fingerprinting. + */ + +const StandardIrreducible8 = new Uint8Array([1, 221]); +const StandardIrreducible16 = new Uint8Array([1, 244, 157]); +const StandardIrreducible32 = new Uint8Array([1, 149, 183, 205, 191]); +const StandardIrreducible64 = new Uint8Array([1, 133, 250, 114, 193, 250, 28, 193, 231]); +const StandardIrreducible128 = new Uint8Array([1, 94, 109, 166, 228, 6, 222, 102, 239, 27, 128, 184, 13, 50, 112, 169, 199]); + +/** + * Maps from a modulo to the precomputed values. + * + * @type {Map} + */ +const _precomputedFingerprintCache = new Map(); + +/** + * @param {Uint8Array} m + */ +const ensureCache = m => map.setIfUndefined(_precomputedFingerprintCache, buffer.toBase64(m), () => { + const byteLen = m.byteLength; + const cache = new Uint8Array(256 * byteLen); + // Use dynamic computing to compute the cached results. + // Starting values: cache(0) = 0; cache(1) = m + cache.set(m, byteLen); + for (let bit = 1; bit < 8; bit++) { + const mBitShifted = buffer.shiftNBitsLeft(m, bit); + const bitShifted = 1 << bit; + for (let j = 0; j < bitShifted; j++) { + // apply the shifted result (reducing the degree of the polynomial) + const msb = bitShifted | j; + const rest = msb ^ mBitShifted[0]; + for (let i = 0; i < byteLen; i++) { + // rest is already precomputed in the cache + cache[msb * byteLen + i] = cache[rest * byteLen + i] ^ mBitShifted[i]; + } + // if (cache[(bitShifted | j) * byteLen] !== (bitShifted | j)) { error.unexpectedCase() } + } + } + return cache +}); + +class RabinEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor (m) { + this.m = m; + this.blen = m.byteLength; + this.bs = new Uint8Array(this.blen); + this.cache = ensureCache(m); + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + this.bpos = 0; + } + + /** + * @param {number} byte + */ + write (byte) { + // assert(this.bs[0] === 0) + // Shift one byte to the left, add b + this.bs[this.bpos] = byte; + this.bpos = (this.bpos + 1) % this.blen; + const msb = this.bs[this.bpos]; + for (let i = 0; i < this.blen; i++) { + this.bs[(this.bpos + i) % this.blen] ^= this.cache[msb * this.blen + i]; + } + // assert(this.bs[this.bpos] === 0) + } + + getFingerprint () { + const result = new Uint8Array(this.blen - 1); + for (let i = 0; i < result.byteLength; i++) { + result[i] = this.bs[(this.bpos + i + 1) % this.blen]; + } + return result + } +} + +/** + * @param {Uint8Array} irreducible + * @param {Uint8Array} data + */ +const fingerprint = (irreducible, data) => { + const encoder = new RabinEncoder(irreducible); + for (let i = 0; i < data.length; i++) { + encoder.write(data[i]); + } + return encoder.getFingerprint() +}; + +exports.RabinEncoder = RabinEncoder; +exports.StandardIrreducible128 = StandardIrreducible128; +exports.StandardIrreducible16 = StandardIrreducible16; +exports.StandardIrreducible32 = StandardIrreducible32; +exports.StandardIrreducible64 = StandardIrreducible64; +exports.StandardIrreducible8 = StandardIrreducible8; +exports.fingerprint = fingerprint; +//# sourceMappingURL=rabin.cjs.map diff --git a/nodejs/node_modules/lib0/dist/rabin.cjs.map b/nodejs/node_modules/lib0/dist/rabin.cjs.map new file mode 100644 index 00000000..975b8388 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rabin.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin.cjs","sources":["../hash/rabin.js"],"sourcesContent":["/**\n * @module rabin\n *\n * Very efficient & versatile fingerprint/hashing algorithm. However, it is not cryptographically\n * secure. Well suited for fingerprinting.\n */\n\nimport * as buffer from '../buffer.js'\nimport * as map from '../map.js'\n\nexport const StandardIrreducible8 = new Uint8Array([1, 221])\nexport const StandardIrreducible16 = new Uint8Array([1, 244, 157])\nexport const StandardIrreducible32 = new Uint8Array([1, 149, 183, 205, 191])\nexport const StandardIrreducible64 = new Uint8Array([1, 133, 250, 114, 193, 250, 28, 193, 231])\nexport const StandardIrreducible128 = new Uint8Array([1, 94, 109, 166, 228, 6, 222, 102, 239, 27, 128, 184, 13, 50, 112, 169, 199])\n\n/**\n * Maps from a modulo to the precomputed values.\n *\n * @type {Map}\n */\nconst _precomputedFingerprintCache = new Map()\n\n/**\n * @param {Uint8Array} m\n */\nconst ensureCache = m => map.setIfUndefined(_precomputedFingerprintCache, buffer.toBase64(m), () => {\n const byteLen = m.byteLength\n const cache = new Uint8Array(256 * byteLen)\n // Use dynamic computing to compute the cached results.\n // Starting values: cache(0) = 0; cache(1) = m\n cache.set(m, byteLen)\n for (let bit = 1; bit < 8; bit++) {\n const mBitShifted = buffer.shiftNBitsLeft(m, bit)\n const bitShifted = 1 << bit\n for (let j = 0; j < bitShifted; j++) {\n // apply the shifted result (reducing the degree of the polynomial)\n const msb = bitShifted | j\n const rest = msb ^ mBitShifted[0]\n for (let i = 0; i < byteLen; i++) {\n // rest is already precomputed in the cache\n cache[msb * byteLen + i] = cache[rest * byteLen + i] ^ mBitShifted[i]\n }\n // if (cache[(bitShifted | j) * byteLen] !== (bitShifted | j)) { error.unexpectedCase() }\n }\n }\n return cache\n})\n\nexport class RabinEncoder {\n /**\n * @param {Uint8Array} m assert(m[0] === 1)\n */\n constructor (m) {\n this.m = m\n this.blen = m.byteLength\n this.bs = new Uint8Array(this.blen)\n this.cache = ensureCache(m)\n /**\n * This describes the position of the most significant byte (starts with 0 and increases with\n * shift)\n */\n this.bpos = 0\n }\n\n /**\n * @param {number} byte\n */\n write (byte) {\n // assert(this.bs[0] === 0)\n // Shift one byte to the left, add b\n this.bs[this.bpos] = byte\n this.bpos = (this.bpos + 1) % this.blen\n const msb = this.bs[this.bpos]\n for (let i = 0; i < this.blen; i++) {\n this.bs[(this.bpos + i) % this.blen] ^= this.cache[msb * this.blen + i]\n }\n // assert(this.bs[this.bpos] === 0)\n }\n\n getFingerprint () {\n const result = new Uint8Array(this.blen - 1)\n for (let i = 0; i < result.byteLength; i++) {\n result[i] = this.bs[(this.bpos + i + 1) % this.blen]\n }\n return result\n }\n}\n\n/**\n * @param {Uint8Array} irreducible\n * @param {Uint8Array} data\n */\nexport const fingerprint = (irreducible, data) => {\n const encoder = new RabinEncoder(irreducible)\n for (let i = 0; i < data.length; i++) {\n encoder.write(data[i])\n }\n return encoder.getFingerprint()\n}\n"],"names":["map.setIfUndefined","buffer.toBase64","buffer.shiftNBitsLeft"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AAIA;AACY,MAAC,oBAAoB,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAC;AAChD,MAAC,qBAAqB,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAA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IAAI,EAAE,CAAC,EAAE,EAAE;AACxC,MAAM,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,EAAC;AAC7E,KAAK;AACL;AACA,GAAG;AACH;AACA,EAAE,cAAc,CAAC,GAAG;AACpB,IAAI,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,EAAC;AAChD,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;AAChD,MAAM,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,EAAC;AAC1D,KAAK;AACL,IAAI,OAAO,MAAM;AACjB,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,CAAC,WAAW,EAAE,IAAI,KAAK;AAClD,EAAE,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,WAAW,EAAC;AAC/C,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAC;AAC1B,GAAG;AACH,EAAE,OAAO,OAAO,CAAC,cAAc,EAAE;AACjC;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/random.cjs b/nodejs/node_modules/lib0/dist/random.cjs new file mode 100644 index 00000000..9d5ef31d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/random.cjs @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var math = require('./math-08e068f9.cjs'); +var binary = require('./binary-ac8e39e2.cjs'); +var webcrypto = require('lib0/webcrypto'); + +/** + * Isomorphic module for true random numbers / buffers / uuids. + * + * Attention: falls back to Math.random if the browser does not support crypto. + * + * @module random + */ + +const rand = Math.random; + +const uint32 = () => webcrypto.getRandomValues(new Uint32Array(1))[0]; + +const uint53 = () => { + const arr = webcrypto.getRandomValues(new Uint32Array(8)); + return (arr[0] & binary.BITS21) * (binary.BITS32 + 1) + (arr[1] >>> 0) +}; + +/** + * @template T + * @param {Array} arr + * @return {T} + */ +const oneOf = arr => arr[math.floor(rand() * arr.length)]; + +// @ts-ignore +const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11; + +/** + * @return {string} + */ +const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c => + (c ^ uint32() & 15 >> c / 4).toString(16) +); + +exports.oneOf = oneOf; +exports.rand = rand; +exports.uint32 = uint32; +exports.uint53 = uint53; +exports.uuidv4 = uuidv4; +//# sourceMappingURL=random.cjs.map diff --git a/nodejs/node_modules/lib0/dist/random.cjs.map b/nodejs/node_modules/lib0/dist/random.cjs.map new file mode 100644 index 00000000..b3ca9229 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/random.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"random.cjs","sources":["../random.js"],"sourcesContent":["/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\nimport * as math from './math.js'\nimport * as binary from './binary.js'\nimport { getRandomValues } from 'lib0/webcrypto'\n\nexport const rand = Math.random\n\nexport const uint32 = () => getRandomValues(new Uint32Array(1))[0]\n\nexport const uint53 = () => {\n const arr = getRandomValues(new Uint32Array(8))\n return (arr[0] & binary.BITS21) * (binary.BITS32 + 1) + (arr[1] >>> 0)\n}\n\n/**\n * @template T\n * @param {Array} arr\n * @return {T}\n */\nexport const oneOf = arr => arr[math.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\n\n/**\n * @return {string}\n */\nexport const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n"],"names":["getRandomValues","binary.BITS21","binary.BITS32","math.floor"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAKA;AACY,MAAC,IAAI,GAAG,IAAI,CAAC,OAAM;AAC/B;AACY,MAAC,MAAM,GAAG,MAAMA,yBAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAC;AAClE;AACY,MAAC,MAAM,GAAG,MAAM;AAC5B,EAAE,MAAM,GAAG,GAAGA,yBAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,EAAC;AACjD,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,GAAGC,aAAa,KAAKC,aAAa,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACxE,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,GAAG,IAAI,GAAG,CAACC,UAAU,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,EAAC;AAChE;AACA;AACA,MAAM,cAAc,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,KAAI;AACzD;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,cAAc,CAAC,OAAO,CAAC,QAAQ,2BAA2B,CAAC;AACvF,EAAE,CAAC,CAAC,GAAG,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC;AAC3C;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/random.d.ts b/nodejs/node_modules/lib0/dist/random.d.ts new file mode 100644 index 00000000..3fe9ebfb --- /dev/null +++ b/nodejs/node_modules/lib0/dist/random.d.ts @@ -0,0 +1,6 @@ +export const rand: () => number; +export function uint32(): number; +export function uint53(): number; +export function oneOf(arr: T[]): T; +export function uuidv4(): string; +//# sourceMappingURL=random.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/random.d.ts.map b/nodejs/node_modules/lib0/dist/random.d.ts.map new file mode 100644 index 00000000..a2a720c6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/random.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.d.ts","sourceRoot":"","sources":["../random.js"],"names":[],"mappings":"AAYA,gCAA+B;AAExB,iCAA2D;AAE3D,iCAGN;AAOM,sCAAyD;AAQzD,0BAFK,MAAM,CAIjB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/random.test.d.ts b/nodejs/node_modules/lib0/dist/random.test.d.ts new file mode 100644 index 00000000..d3b2523c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/random.test.d.ts @@ -0,0 +1,7 @@ +export function testRandom(tc: t.TestCase): void; +export function testUint32(tc: t.TestCase): void; +export function testUint53(tc: t.TestCase): void; +export function testUuidv4(tc: t.TestCase): void; +export function testUuidv4Overlaps(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=random.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/random.test.d.ts.map b/nodejs/node_modules/lib0/dist/random.test.d.ts.map new file mode 100644 index 00000000..6b1c7f39 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/random.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.test.d.ts","sourceRoot":"","sources":["../random.test.js"],"names":[],"mappings":"AASO,+BAFI,EAAE,QAAQ,QAKpB;AAKM,+BAFI,EAAE,QAAQ,QA0BpB;AAKM,+BAFI,EAAE,QAAQ,QAyBpB;AAKM,+BAFI,EAAE,QAAQ,QAIpB;AAKM,uCAFI,EAAE,QAAQ,QAkBpB;mBAhGkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/rollup.config.d.ts b/nodejs/node_modules/lib0/dist/rollup.config.d.ts new file mode 100644 index 00000000..7192ab2c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rollup.config.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + input: string[]; + output: { + dir: string; + format: string; + sourcemap: boolean; + entryFileNames: string; + chunkFileNames: string; + }; + external: string[]; +}[]; +export default _default; +//# sourceMappingURL=rollup.config.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/rollup.config.d.ts.map b/nodejs/node_modules/lib0/dist/rollup.config.d.ts.map new file mode 100644 index 00000000..8ea43ed0 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rollup.config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rollup.config.d.ts","sourceRoot":"","sources":["../rollup.config.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/rsa-oaep.cjs b/nodejs/node_modules/lib0/dist/rsa-oaep.cjs new file mode 100644 index 00000000..9369f14b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rsa-oaep.cjs @@ -0,0 +1,112 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var webcrypto = require('lib0/webcrypto'); +var common = require('./common.cjs'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var webcrypto__namespace = /*#__PURE__*/_interopNamespace(webcrypto); + +/** + * RSA-OAEP is an asymmetric keypair used for encryption + */ + +/** + * @typedef {Array<'encrypt'|'decrypt'>} Usages + */ + +/** + * @type {Usages} + */ +const defaultUsages = ['encrypt', 'decrypt']; + +/** + * Note that the max data size is limited by the size of the RSA key. + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} + */ +const encrypt = (key, data) => + webcrypto__namespace.subtle.encrypt( + { + name: 'RSA-OAEP' + }, + key, + data + ).then(buf => new Uint8Array(buf)); + +/** + * @experimental The API is not final! + * + * Decrypt some data using AES-GCM method. + * + * @param {CryptoKey} key + * @param {Uint8Array} data + * @return {PromiseLike} decrypted buffer + */ +const decrypt = (key, data) => + webcrypto__namespace.subtle.decrypt( + { + name: 'RSA-OAEP' + }, + key, + data + ).then(data => new Uint8Array(data)); + +/** + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + * @return {Promise} + */ +const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) => + webcrypto__namespace.subtle.generateKey( + { + name: 'RSA-OAEP', + modulusLength: 4096, + publicExponent: new Uint8Array([1, 0, 1]), + hash: 'SHA-256' + }, + extractable, + usages + ); + +/** + * @param {any} jwk + * @param {Object} opts + * @param {boolean} [opts.extractable] + * @param {Usages} [opts.usages] + */ +const importKeyJwk = (jwk, { extractable = false, usages } = {}) => { + if (usages == null) { + /* c8 ignore next */ + usages = jwk.key_ops || defaultUsages; + } + return webcrypto__namespace.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, extractable, /** @type {Usages} */ (usages)) +}; + +exports.exportKeyJwk = common.exportKeyJwk; +exports.decrypt = decrypt; +exports.encrypt = encrypt; +exports.generateKeyPair = generateKeyPair; +exports.importKeyJwk = importKeyJwk; +//# sourceMappingURL=rsa-oaep.cjs.map diff --git a/nodejs/node_modules/lib0/dist/rsa-oaep.cjs.map b/nodejs/node_modules/lib0/dist/rsa-oaep.cjs.map new file mode 100644 index 00000000..99eae139 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/rsa-oaep.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"rsa-oaep.cjs","sources":["../crypto/rsa-oaep.js"],"sourcesContent":["/**\n * RSA-OAEP is an asymmetric keypair used for encryption\n */\n\nimport * as webcrypto from 'lib0/webcrypto'\nexport { exportKeyJwk } from './common.js'\n\n/**\n * @typedef {Array<'encrypt'|'decrypt'>} Usages\n */\n\n/**\n * @type {Usages}\n */\nconst defaultUsages = ['encrypt', 'decrypt']\n\n/**\n * Note that the max data size is limited by the size of the RSA key.\n *\n * @param {CryptoKey} key\n * @param {Uint8Array} data\n * @return {PromiseLike}\n */\nexport const encrypt = (key, data) =>\n webcrypto.subtle.encrypt(\n {\n name: 'RSA-OAEP'\n },\n key,\n data\n ).then(buf => new Uint8Array(buf))\n\n/**\n * @experimental The API is not final!\n *\n * Decrypt some data using AES-GCM method.\n *\n * @param {CryptoKey} key\n * @param {Uint8Array} data\n * @return {PromiseLike} decrypted buffer\n */\nexport const decrypt = (key, data) =>\n webcrypto.subtle.decrypt(\n {\n name: 'RSA-OAEP'\n },\n key,\n data\n ).then(data => new Uint8Array(data))\n\n/**\n * @param {Object} opts\n * @param {boolean} [opts.extractable]\n * @param {Usages} [opts.usages]\n * @return {Promise}\n */\nexport const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) =>\n webcrypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 4096,\n publicExponent: new Uint8Array([1, 0, 1]),\n hash: 'SHA-256'\n },\n extractable,\n usages\n )\n\n/**\n * @param {any} jwk\n * @param {Object} opts\n * @param {boolean} [opts.extractable]\n * @param {Usages} [opts.usages]\n */\nexport const importKeyJwk = (jwk, { extractable = false, usages } = {}) => {\n if (usages == null) {\n /* c8 ignore next */\n usages = jwk.key_ops || defaultUsages\n }\n return webcrypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, extractable, /** @type {Usages} */ (usages))\n}\n"],"names":["webcrypto"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AAC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,EAAE,IAAI,MAAM,IAAI,IAAI,EAAE;AACtB;AACA,IAAI,MAAM,GAAG,GAAG,CAAC,OAAO,IAAI,cAAa;AACzC,GAAG;AACH,EAAE,OAAOA,oBAAS,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,WAAW,yBAAyB,MAAM,EAAE;AACnI;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/set-0f209abb.cjs b/nodejs/node_modules/lib0/dist/set-0f209abb.cjs new file mode 100644 index 00000000..f32a821e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set-0f209abb.cjs @@ -0,0 +1,46 @@ +'use strict'; + +/** + * Utility module to work with sets. + * + * @module set + */ + +const create = () => new Set(); + +/** + * @template T + * @param {Set} set + * @return {Array} + */ +const toArray = set => Array.from(set); + +/** + * @template T + * @param {Set} set + * @return {T} + */ +const first = set => + set.values().next().value || undefined; + +/** + * @template T + * @param {Iterable} entries + * @return {Set} + */ +const from = entries => new Set(entries); + +var set = /*#__PURE__*/Object.freeze({ + __proto__: null, + create: create, + toArray: toArray, + first: first, + from: from +}); + +exports.create = create; +exports.first = first; +exports.from = from; +exports.set = set; +exports.toArray = toArray; +//# sourceMappingURL=set-0f209abb.cjs.map diff --git a/nodejs/node_modules/lib0/dist/set-0f209abb.cjs.map b/nodejs/node_modules/lib0/dist/set-0f209abb.cjs.map new file mode 100644 index 00000000..7f3421bf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set-0f209abb.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set-0f209abb.cjs","sources":["../set.js"],"sourcesContent":["/**\n * Utility module to work with sets.\n *\n * @module set\n */\n\nexport const create = () => new Set()\n\n/**\n * @template T\n * @param {Set} set\n * @return {Array}\n */\nexport const toArray = set => Array.from(set)\n\n/**\n * @template T\n * @param {Set} set\n * @return {T}\n */\nexport const first = set =>\n set.values().next().value || undefined\n\n/**\n * @template T\n * @param {Iterable} entries\n * @return {Set}\n */\nexport const from = entries => new Set(entries)\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,IAAI,GAAG,GAAE;AACrC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,EAAC;AAC7C;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,KAAK,GAAG,GAAG;AACxB,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,UAAS;AACxC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,OAAO,IAAI,IAAI,GAAG,CAAC,OAAO;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/set.cjs b/nodejs/node_modules/lib0/dist/set.cjs new file mode 100644 index 00000000..a660fe0f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set.cjs @@ -0,0 +1,13 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var set = require('./set-0f209abb.cjs'); + + + +exports.create = set.create; +exports.first = set.first; +exports.from = set.from; +exports.toArray = set.toArray; +//# sourceMappingURL=set.cjs.map diff --git a/nodejs/node_modules/lib0/dist/set.cjs.map b/nodejs/node_modules/lib0/dist/set.cjs.map new file mode 100644 index 00000000..ce54f1af --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/set.d.ts b/nodejs/node_modules/lib0/dist/set.d.ts new file mode 100644 index 00000000..b2c1a6bd --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set.d.ts @@ -0,0 +1,5 @@ +export function create(): Set; +export function toArray(set: Set): T[]; +export function first(set: Set): T; +export function from(entries: Iterable): Set; +//# sourceMappingURL=set.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/set.d.ts.map b/nodejs/node_modules/lib0/dist/set.d.ts.map new file mode 100644 index 00000000..a6c2c3b9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../set.js"],"names":[],"mappings":"AAMO,mCAA8B;AAO9B,6CAAsC;AAOtC,yCACiC;AAOjC,sDAAwC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/set.test.d.ts b/nodejs/node_modules/lib0/dist/set.test.d.ts new file mode 100644 index 00000000..075f0d1e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set.test.d.ts @@ -0,0 +1,3 @@ +export function testFirst(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=set.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/set.test.d.ts.map b/nodejs/node_modules/lib0/dist/set.test.d.ts.map new file mode 100644 index 00000000..59833079 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/set.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.test.d.ts","sourceRoot":"","sources":["../set.test.js"],"names":[],"mappings":"AAMO,+BAFI,EAAE,QAAQ,QAUpB;mBAdkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sha256.cjs b/nodejs/node_modules/lib0/dist/sha256.cjs new file mode 100644 index 00000000..75a13cba --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sha256.cjs @@ -0,0 +1,179 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var binary = require('./binary-ac8e39e2.cjs'); + +/** + * @module sha256 + * Spec: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf + * Resources: + * - https://web.archive.org/web/20150315061807/http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf + */ + +/** + * @param {number} w - a 32bit uint + * @param {number} shift + */ +const rotr = (w, shift) => (w >>> shift) | (w << (32 - shift)); + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sum0to256 = x => rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22); + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sum1to256 = x => rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25); + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sigma0to256 = x => rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3; + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sigma1to256 = x => rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10; + +// @todo don't init these variables globally + +/** + * See 4.2.2: Constant for sha256 & sha224 + * These words represent the first thirty-two bits of the fractional parts of + * the cube roots of the first sixty-four prime numbers. In hex, these constant words are (from left to + * right) + */ +const K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +/** + * See 5.3.3. Initial hash value. + * + * These words were obtained by taking the first thirty-two bits of the fractional parts of the + * square roots of the first eight prime numbers. + * + * @todo shouldn't be a global variable + */ +const HINIT = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); + +// time to beat: (large value < 4.35s) + +class Hasher { + constructor () { + const buf = new ArrayBuffer(64 + 64 * 4); + // Init working variables using a single arraybuffer + this._H = new Uint32Array(buf, 0, 8); + this._H.set(HINIT); + // "Message schedule" - a working variable + this._W = new Uint32Array(buf, 64, 64); + } + + _updateHash () { + const H = this._H; + const W = this._W; + for (let t = 16; t < 64; t++) { + W[t] = sigma1to256(W[t - 2]) + W[t - 7] + sigma0to256(W[t - 15]) + W[t - 16]; + } + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + let f = H[5]; + let g = H[6]; + let h = H[7]; + for (let tt = 0, T1, T2; tt < 64; tt++) { + T1 = (h + sum1to256(e) + ((e & f) ^ (~e & g)) + K[tt] + W[tt]) >>> 0; + T2 = (sum0to256(a) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0; + h = g; + g = f; + f = e; + e = (d + T1) >>> 0; + d = c; + c = b; + b = a; + a = (T1 + T2) >>> 0; + } + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + H[5] += f; + H[6] += g; + H[7] += h; + } + + /** + * @param {Uint8Array} data + */ + digest (data) { + let i = 0; + for (; i + 56 <= data.length;) { + // write data in big endianess + let j = 0; + for (; j < 16 && i + 3 < data.length; j++) { + this._W[j] = data[i++] << 24 | data[i++] << 16 | data[i++] << 8 | data[i++]; + } + if (i % 64 !== 0) { // there is still room to write partial content and the ending bit. + this._W.fill(0, j, 16); + while (i < data.length) { + this._W[j] |= data[i] << ((3 - (i % 4)) * 8); + i++; + } + this._W[j] |= binary.BIT8 << ((3 - (i % 4)) * 8); + } + this._updateHash(); + } + // same check as earlier - the ending bit has been written + const isPaddedWith1 = i % 64 !== 0; + this._W.fill(0, 0, 16); + let j = 0; + for (; i < data.length; j++) { + for (let ci = 3; ci >= 0 && i < data.length; ci--) { + this._W[j] |= data[i++] << (ci * 8); + } + } + // Write padding of the message. See 5.1.2. + if (!isPaddedWith1) { + this._W[j - (i % 4 === 0 ? 0 : 1)] |= binary.BIT8 << ((3 - (i % 4)) * 8); + } + // write length of message (size in bits) as 64 bit uint + // @todo test that this works correctly + this._W[14] = data.byteLength / binary.BIT30; // same as data.byteLength >>> 30 - but works on floats + this._W[15] = data.byteLength * 8; + this._updateHash(); + // correct H endianness to use big endiannes and return a Uint8Array + const dv = new Uint8Array(32); + for (let i = 0; i < this._H.length; i++) { + for (let ci = 0; ci < 4; ci++) { + dv[i * 4 + ci] = this._H[i] >>> (3 - ci) * 8; + } + } + return dv + } +} + +/** + * @param {Uint8Array} data + */ +const digest = data => new Hasher().digest(data); + +exports.digest = digest; +//# sourceMappingURL=sha256.cjs.map diff --git a/nodejs/node_modules/lib0/dist/sha256.cjs.map b/nodejs/node_modules/lib0/dist/sha256.cjs.map new file mode 100644 index 00000000..d7819c83 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sha256.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.cjs","sources":["../hash/sha256.js"],"sourcesContent":["/**\n * @module sha256\n * Spec: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\n * Resources:\n * - https://web.archive.org/web/20150315061807/http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf\n */\n\nimport * as binary from '../binary.js'\n\n/**\n * @param {number} w - a 32bit uint\n * @param {number} shift\n */\nconst rotr = (w, shift) => (w >>> shift) | (w << (32 - shift))\n\n/**\n * Helper for SHA-224 & SHA-256. See 4.1.2.\n * @param {number} x\n */\nconst sum0to256 = x => rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22)\n\n/**\n * Helper for SHA-224 & SHA-256. See 4.1.2.\n * @param {number} x\n */\nconst sum1to256 = x => rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25)\n\n/**\n * Helper for SHA-224 & SHA-256. See 4.1.2.\n * @param {number} x\n */\nconst sigma0to256 = x => rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3\n\n/**\n * Helper for SHA-224 & SHA-256. See 4.1.2.\n * @param {number} x\n */\nconst sigma1to256 = x => rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10\n\n// @todo don't init these variables globally\n\n/**\n * See 4.2.2: Constant for sha256 & sha224\n * These words represent the first thirty-two bits of the fractional parts of\n * the cube roots of the first sixty-four prime numbers. In hex, these constant words are (from left to\n * right)\n */\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n])\n\n/**\n * See 5.3.3. Initial hash value.\n *\n * These words were obtained by taking the first thirty-two bits of the fractional parts of the\n * square roots of the first eight prime numbers.\n *\n * @todo shouldn't be a global variable\n */\nconst HINIT = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n])\n\n// time to beat: (large value < 4.35s)\n\nclass Hasher {\n constructor () {\n const buf = new ArrayBuffer(64 + 64 * 4)\n // Init working variables using a single arraybuffer\n this._H = new Uint32Array(buf, 0, 8)\n this._H.set(HINIT)\n // \"Message schedule\" - a working variable\n this._W = new Uint32Array(buf, 64, 64)\n }\n\n _updateHash () {\n const H = this._H\n const W = this._W\n for (let t = 16; t < 64; t++) {\n W[t] = sigma1to256(W[t - 2]) + W[t - 7] + sigma0to256(W[t - 15]) + W[t - 16]\n }\n let a = H[0]\n let b = H[1]\n let c = H[2]\n let d = H[3]\n let e = H[4]\n let f = H[5]\n let g = H[6]\n let h = H[7]\n for (let tt = 0, T1, T2; tt < 64; tt++) {\n T1 = (h + sum1to256(e) + ((e & f) ^ (~e & g)) + K[tt] + W[tt]) >>> 0\n T2 = (sum0to256(a) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0\n h = g\n g = f\n f = e\n e = (d + T1) >>> 0\n d = c\n c = b\n b = a\n a = (T1 + T2) >>> 0\n }\n H[0] += a\n H[1] += b\n H[2] += c\n H[3] += d\n H[4] += e\n H[5] += f\n H[6] += g\n H[7] += h\n }\n\n /**\n * @param {Uint8Array} data\n */\n digest (data) {\n let i = 0\n for (; i + 56 <= data.length;) {\n // write data in big endianess\n let j = 0\n for (; j < 16 && i + 3 < data.length; j++) {\n this._W[j] = data[i++] << 24 | data[i++] << 16 | data[i++] << 8 | data[i++]\n }\n if (i % 64 !== 0) { // there is still room to write partial content and the ending bit.\n this._W.fill(0, j, 16)\n while (i < data.length) {\n this._W[j] |= data[i] << ((3 - (i % 4)) * 8)\n i++\n }\n this._W[j] |= binary.BIT8 << ((3 - (i % 4)) * 8)\n }\n this._updateHash()\n }\n // same check as earlier - the ending bit has been written\n const isPaddedWith1 = i % 64 !== 0\n this._W.fill(0, 0, 16)\n let j = 0\n for (; i < data.length; j++) {\n for (let ci = 3; ci >= 0 && i < data.length; ci--) {\n this._W[j] |= data[i++] << (ci * 8)\n }\n }\n // Write padding of the message. See 5.1.2.\n if (!isPaddedWith1) {\n this._W[j - (i % 4 === 0 ? 0 : 1)] |= binary.BIT8 << ((3 - (i % 4)) * 8)\n }\n // write length of message (size in bits) as 64 bit uint\n // @todo test that this works correctly\n this._W[14] = data.byteLength / binary.BIT30 // same as data.byteLength >>> 30 - but works on floats\n this._W[15] = data.byteLength * 8\n this._updateHash()\n // correct H endianness to use big endiannes and return a Uint8Array\n const dv = new Uint8Array(32)\n for (let i = 0; i < this._H.length; i++) {\n for (let ci = 0; ci < 4; ci++) {\n dv[i * 4 + ci] = this._H[i] >>> (3 - ci) * 8\n }\n }\n return dv\n }\n}\n\n/**\n * @param {Uint8Array} data\n */\nexport const digest = data => new Hasher().digest(data)\n"],"names":["binary.BIT8","binary.BIT30"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,CAAC,EAAC;AAC9D;AACA;AACA;AACA;AACA;AACA,MAAM,SAAS,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,EAAE,EAAC;AA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,GAAG,IAAI,CAAC,UAAU,GAAG,EAAC;AACrC,IAAI,IAAI,CAAC,WAAW,GAAE;AACtB;AACA,IAAI,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,EAAE,EAAC;AACjC,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC7C,MAAM,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE;AACrC,QAAQ,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,IAAI,EAAC;AACpD,OAAO;AACP,KAAK;AACL,IAAI,OAAO,EAAE;AACb,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,IAAI,IAAI,IAAI,MAAM,EAAE,CAAC,MAAM,CAAC,IAAI;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sha256.node.cjs b/nodejs/node_modules/lib0/dist/sha256.node.cjs new file mode 100644 index 00000000..be0b3e61 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sha256.node.cjs @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var node_crypto = require('node:crypto'); + +/** + * @param {Uint8Array} data + */ +const digest = data => { + const hasher = node_crypto.createHash('sha256'); + hasher.update(data); + return hasher.digest() +}; + +exports.digest = digest; +//# sourceMappingURL=sha256.node.cjs.map diff --git a/nodejs/node_modules/lib0/dist/sha256.node.cjs.map b/nodejs/node_modules/lib0/dist/sha256.node.cjs.map new file mode 100644 index 00000000..222e5636 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sha256.node.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.node.cjs","sources":["../hash/sha256.node.js"],"sourcesContent":["import { createHash } from 'node:crypto'\n\n/**\n * @param {Uint8Array} data\n */\nexport const digest = data => {\n const hasher = createHash('sha256')\n hasher.update(data)\n return hasher.digest()\n}\n"],"names":["createHash"],"mappings":";;;;;;AAEA;AACA;AACA;AACY,MAAC,MAAM,GAAG,IAAI,IAAI;AAC9B,EAAE,MAAM,MAAM,GAAGA,sBAAU,CAAC,QAAQ,EAAC;AACrC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAC;AACrB,EAAE,OAAO,MAAM,CAAC,MAAM,EAAE;AACxB;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sort-b8702761.cjs b/nodejs/node_modules/lib0/dist/sort-b8702761.cjs new file mode 100644 index 00000000..6f0dd60a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort-b8702761.cjs @@ -0,0 +1,103 @@ +'use strict'; + +var math = require('./math-08e068f9.cjs'); + +/** + * Efficient sort implementations. + * + * Note: These sort implementations were created to compare different sorting algorithms in JavaScript. + * Don't use them if you don't know what you are doing. Native Array.sort is almost always a better choice. + * + * @module sort + */ + +/** + * @template T + * @param {Array} arr + * @param {number} lo + * @param {number} hi + * @param {function(T,T):number} compare + */ +const _insertionSort = (arr, lo, hi, compare) => { + for (let i = lo + 1; i <= hi; i++) { + for (let j = i; j > 0 && compare(arr[j - 1], arr[j]) > 0; j--) { + const tmp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = tmp; + } + } +}; + +/** + * @template T + * @param {Array} arr + * @param {function(T,T):number} compare + * @return {void} + */ +const insertionSort = (arr, compare) => { + _insertionSort(arr, 0, arr.length - 1, compare); +}; + +/** + * @template T + * @param {Array} arr + * @param {number} lo + * @param {number} hi + * @param {function(T,T):number} compare + */ +const _quickSort = (arr, lo, hi, compare) => { + if (hi - lo < 42) { + _insertionSort(arr, lo, hi, compare); + } else { + const pivot = arr[math.floor((lo + hi) / 2)]; + let i = lo; + let j = hi; + while (true) { + while (compare(pivot, arr[i]) > 0) { + i++; + } + while (compare(arr[j], pivot) > 0) { + j--; + } + if (i >= j) { + break + } + // swap arr[i] with arr[j] + // and increment i and j + const arri = arr[i]; + arr[i++] = arr[j]; + arr[j--] = arri; + } + _quickSort(arr, lo, j, compare); + _quickSort(arr, j + 1, hi, compare); + } +}; + +/** + * This algorithm beats Array.prototype.sort in Chrome only with arrays with 10 million entries. + * In most cases [].sort will do just fine. Make sure to performance test your use-case before you + * integrate this algorithm. + * + * Note that Chrome's sort is now a stable algorithm (Timsort). Quicksort is not stable. + * + * @template T + * @param {Array} arr + * @param {function(T,T):number} compare + * @return {void} + */ +const quicksort = (arr, compare) => { + _quickSort(arr, 0, arr.length - 1, compare); +}; + +var sort = /*#__PURE__*/Object.freeze({ + __proto__: null, + _insertionSort: _insertionSort, + insertionSort: insertionSort, + quicksort: quicksort +}); + +exports._insertionSort = _insertionSort; +exports.insertionSort = insertionSort; +exports.quicksort = quicksort; +exports.sort = sort; +//# sourceMappingURL=sort-b8702761.cjs.map diff --git a/nodejs/node_modules/lib0/dist/sort-b8702761.cjs.map b/nodejs/node_modules/lib0/dist/sort-b8702761.cjs.map new file mode 100644 index 00000000..28fbf83c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort-b8702761.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sort-b8702761.cjs","sources":["../sort.js"],"sourcesContent":["/**\n * Efficient sort implementations.\n *\n * Note: These sort implementations were created to compare different sorting algorithms in JavaScript.\n * Don't use them if you don't know what you are doing. Native Array.sort is almost always a better choice.\n *\n * @module sort\n */\n\nimport * as math from './math.js'\n\n/**\n * @template T\n * @param {Array} arr\n * @param {number} lo\n * @param {number} hi\n * @param {function(T,T):number} compare\n */\nexport const _insertionSort = (arr, lo, hi, compare) => {\n for (let i = lo + 1; i <= hi; i++) {\n for (let j = i; j > 0 && compare(arr[j - 1], arr[j]) > 0; j--) {\n const tmp = arr[j]\n arr[j] = arr[j - 1]\n arr[j - 1] = tmp\n }\n }\n}\n\n/**\n * @template T\n * @param {Array} arr\n * @param {function(T,T):number} compare\n * @return {void}\n */\nexport const insertionSort = (arr, compare) => {\n _insertionSort(arr, 0, arr.length - 1, compare)\n}\n\n/**\n * @template T\n * @param {Array} arr\n * @param {number} lo\n * @param {number} hi\n * @param {function(T,T):number} compare\n */\nconst _quickSort = (arr, lo, hi, compare) => {\n if (hi - lo < 42) {\n _insertionSort(arr, lo, hi, compare)\n } else {\n const pivot = arr[math.floor((lo + hi) / 2)]\n let i = lo\n let j = hi\n while (true) {\n while (compare(pivot, arr[i]) > 0) {\n i++\n }\n while (compare(arr[j], pivot) > 0) {\n j--\n }\n if (i >= j) {\n break\n }\n // swap arr[i] with arr[j]\n // and increment i and j\n const arri = arr[i]\n arr[i++] = arr[j]\n arr[j--] = arri\n }\n _quickSort(arr, lo, j, compare)\n _quickSort(arr, j + 1, hi, compare)\n }\n}\n\n/**\n * This algorithm beats Array.prototype.sort in Chrome only with arrays with 10 million entries.\n * In most cases [].sort will do just fine. Make sure to performance test your use-case before you\n * integrate this algorithm.\n *\n * Note that Chrome's sort is now a stable algorithm (Timsort). Quicksort is not stable.\n *\n * @template T\n * @param {Array} arr\n * @param {function(T,T):number} compare\n * @return {void}\n */\nexport const quicksort = (arr, compare) => {\n _quickSort(arr, 0, arr.length - 1, compare)\n}\n"],"names":["math.floor"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,OAAO,KAAK;AACxD,EAAE,KAAK,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE;AACrC,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,C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ClB,QAAQ,KAAK;AACb,OAAO;AACP;AACA;AACA,MAAM,MAAM,IAAI,GAAG,GAAG,CAAC,CAAC,EAAC;AACzB,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,EAAC;AACvB,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,KAAI;AACrB,KAAK;AACL,IAAI,UAAU,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE,OAAO,EAAC;AACnC,IAAI,UAAU,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,OAAO,EAAC;AACvC,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK;AAC3C,EAAE,UAAU,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,OAAO,EAAC;AAC7C;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sort.cjs b/nodejs/node_modules/lib0/dist/sort.cjs new file mode 100644 index 00000000..9cbc1ea9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort.cjs @@ -0,0 +1,13 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./math-08e068f9.cjs'); +var sort = require('./sort-b8702761.cjs'); + + + +exports._insertionSort = sort._insertionSort; +exports.insertionSort = sort.insertionSort; +exports.quicksort = sort.quicksort; +//# sourceMappingURL=sort.cjs.map diff --git a/nodejs/node_modules/lib0/dist/sort.cjs.map b/nodejs/node_modules/lib0/dist/sort.cjs.map new file mode 100644 index 00000000..d8561ec7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sort.d.ts b/nodejs/node_modules/lib0/dist/sort.d.ts new file mode 100644 index 00000000..f80cece4 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort.d.ts @@ -0,0 +1,4 @@ +export function _insertionSort(arr: T[], lo: number, hi: number, compare: (arg0: T, arg1: T) => number): void; +export function insertionSort(arr: T[], compare: (arg0: T, arg1: T) => number): void; +export function quicksort(arr: T[], compare: (arg0: T, arg1: T) => number): void; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sort.d.ts.map b/nodejs/node_modules/lib0/dist/sort.d.ts.map new file mode 100644 index 00000000..18c2a24c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../sort.js"],"names":[],"mappings":"AAkBO,gDAJI,MAAM,MACN,MAAM,iCACQ,MAAM,QAU9B;AAQM,0EAHkB,MAAM,GACnB,IAAI,CAIf;AAiDM,sEAHkB,MAAM,GACnB,IAAI,CAIf"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sort.test.d.ts b/nodejs/node_modules/lib0/dist/sort.test.d.ts new file mode 100644 index 00000000..11344b1d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort.test.d.ts @@ -0,0 +1,7 @@ +export function testSortUint8(tc: t.TestCase): void; +export function testSortUint32(tc: t.TestCase): void; +export function testSortUint16(tc: t.TestCase): void; +export function testSortObjectUint32(tc: t.TestCase): void; +export function testListVsArrayPerformance(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=sort.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/sort.test.d.ts.map b/nodejs/node_modules/lib0/dist/sort.test.d.ts.map new file mode 100644 index 00000000..7921d86b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/sort.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.test.d.ts","sourceRoot":"","sources":["../sort.test.js"],"names":[],"mappings":"AAoEO,kCAFI,EAAE,QAAQ,QAqBpB;AAKM,mCAFI,EAAE,QAAQ,QAqBpB;AAKM,mCAFI,EAAE,QAAQ,QAqBpB;AAKM,yCAFI,EAAE,QAAQ,QAoBpB;AAKM,+CAFI,EAAE,QAAQ,QA4BpB;mBA5LkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/statistics-c2316dca.cjs b/nodejs/node_modules/lib0/dist/statistics-c2316dca.cjs new file mode 100644 index 00000000..45378079 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics-c2316dca.cjs @@ -0,0 +1,32 @@ +'use strict'; + +var math = require('./math-08e068f9.cjs'); + +/** + * Utility helpers for generating statistics. + * + * @module statistics + */ + +/** + * @param {Array} arr Array of values + * @return {number} Returns null if the array is empty + */ +const median = arr => arr.length === 0 ? NaN : (arr.length % 2 === 1 ? arr[(arr.length - 1) / 2] : (arr[math.floor((arr.length - 1) / 2)] + arr[math.ceil((arr.length - 1) / 2)]) / 2); + +/** + * @param {Array} arr + * @return {number} + */ +const average = arr => arr.reduce(math.add, 0) / arr.length; + +var statistics = /*#__PURE__*/Object.freeze({ + __proto__: null, + median: median, + average: average +}); + +exports.average = average; +exports.median = median; +exports.statistics = statistics; +//# sourceMappingURL=statistics-c2316dca.cjs.map diff --git a/nodejs/node_modules/lib0/dist/statistics-c2316dca.cjs.map b/nodejs/node_modules/lib0/dist/statistics-c2316dca.cjs.map new file mode 100644 index 00000000..b6312ead --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics-c2316dca.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"statistics-c2316dca.cjs","sources":["../statistics.js"],"sourcesContent":["/**\n * Utility helpers for generating statistics.\n *\n * @module statistics\n */\n\nimport * as math from './math.js'\n\n/**\n * @param {Array} arr Array of values\n * @return {number} Returns null if the array is empty\n */\nexport const median = arr => arr.length === 0 ? NaN : (arr.length % 2 === 1 ? arr[(arr.length - 1) / 2] : (arr[math.floor((arr.length - 1) / 2)] + arr[math.ceil((arr.length - 1) / 2)]) / 2)\n\n/**\n * @param {Array} arr\n * @return {number}\n */\nexport const average = arr => arr.reduce(math.add, 0) / arr.length\n"],"names":["math.floor","math.ceil","math.add"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAACA,UAAU,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAACC,SAAS,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,EAAC;AAC7L;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAACC,QAAQ,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/statistics.cjs b/nodejs/node_modules/lib0/dist/statistics.cjs new file mode 100644 index 00000000..42f5388b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics.cjs @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./math-08e068f9.cjs'); +var statistics = require('./statistics-c2316dca.cjs'); + + + +exports.average = statistics.average; +exports.median = statistics.median; +//# sourceMappingURL=statistics.cjs.map diff --git a/nodejs/node_modules/lib0/dist/statistics.cjs.map b/nodejs/node_modules/lib0/dist/statistics.cjs.map new file mode 100644 index 00000000..01cbd80c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"statistics.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/statistics.d.ts b/nodejs/node_modules/lib0/dist/statistics.d.ts new file mode 100644 index 00000000..3033ab67 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics.d.ts @@ -0,0 +1,3 @@ +export function median(arr: Array): number; +export function average(arr: Array): number; +//# sourceMappingURL=statistics.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/statistics.d.ts.map b/nodejs/node_modules/lib0/dist/statistics.d.ts.map new file mode 100644 index 00000000..02bbc3a2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"statistics.d.ts","sourceRoot":"","sources":["../statistics.js"],"names":[],"mappings":"AAYO,4BAHI,MAAM,MAAM,CAAC,GACZ,MAAM,CAE2K;AAMtL,6BAHI,MAAM,MAAM,CAAC,GACZ,MAAM,CAEgD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/statistics.test.d.ts b/nodejs/node_modules/lib0/dist/statistics.test.d.ts new file mode 100644 index 00000000..22230d67 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics.test.d.ts @@ -0,0 +1,3 @@ +export function testMedian(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=statistics.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/statistics.test.d.ts.map b/nodejs/node_modules/lib0/dist/statistics.test.d.ts.map new file mode 100644 index 00000000..f41fec2b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/statistics.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"statistics.test.d.ts","sourceRoot":"","sources":["../statistics.test.js"],"names":[],"mappings":"AAOO,+BAFI,EAAE,QAAQ,QASpB;mBAbkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/storage.cjs b/nodejs/node_modules/lib0/dist/storage.cjs new file mode 100644 index 00000000..bed67809 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/storage.cjs @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/* eslint-env browser */ + +/** + * Isomorphic variable storage. + * + * Uses LocalStorage in the browser and falls back to in-memory storage. + * + * @module storage + */ + +/* c8 ignore start */ +class VarStoragePolyfill { + constructor () { + this.map = new Map(); + } + + /** + * @param {string} key + * @param {any} newValue + */ + setItem (key, newValue) { + this.map.set(key, newValue); + } + + /** + * @param {string} key + */ + getItem (key) { + return this.map.get(key) + } +} +/* c8 ignore stop */ + +/** + * @type {any} + */ +let _localStorage = new VarStoragePolyfill(); +let usePolyfill = true; + +/* c8 ignore start */ +try { + // if the same-origin rule is violated, accessing localStorage might thrown an error + if (typeof localStorage !== 'undefined' && localStorage) { + _localStorage = localStorage; + usePolyfill = false; + } +} catch (e) { } +/* c8 ignore stop */ + +/** + * This is basically localStorage in browser, or a polyfill in nodejs + */ +/* c8 ignore next */ +const varStorage = _localStorage; + +/** + * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used. + * + * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler + * @function + */ +/* c8 ignore next */ +const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler)); + +/** + * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used. + * + * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler + * @function + */ +/* c8 ignore next */ +const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler)); + +exports.offChange = offChange; +exports.onChange = onChange; +exports.varStorage = varStorage; +//# sourceMappingURL=storage.cjs.map diff --git a/nodejs/node_modules/lib0/dist/storage.cjs.map b/nodejs/node_modules/lib0/dist/storage.cjs.map new file mode 100644 index 00000000..c2adf94a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/storage.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.cjs","sources":["../storage.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Isomorphic variable storage.\n *\n * Uses LocalStorage in the browser and falls back to in-memory storage.\n *\n * @module storage\n */\n\n/* c8 ignore start */\nclass VarStoragePolyfill {\n constructor () {\n this.map = new Map()\n }\n\n /**\n * @param {string} key\n * @param {any} newValue\n */\n setItem (key, newValue) {\n this.map.set(key, newValue)\n }\n\n /**\n * @param {string} key\n */\n getItem (key) {\n return this.map.get(key)\n }\n}\n/* c8 ignore stop */\n\n/**\n * @type {any}\n */\nlet _localStorage = new VarStoragePolyfill()\nlet usePolyfill = true\n\n/* c8 ignore start */\ntry {\n // if the same-origin rule is violated, accessing localStorage might thrown an error\n if (typeof localStorage !== 'undefined' && localStorage) {\n _localStorage = localStorage\n usePolyfill = false\n }\n} catch (e) { }\n/* c8 ignore stop */\n\n/**\n * This is basically localStorage in browser, or a polyfill in nodejs\n */\n/* c8 ignore next */\nexport const varStorage = _localStorage\n\n/**\n * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler))\n\n/**\n * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.\n *\n * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler\n * @function\n */\n/* c8 ignore next */\nexport const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler))\n"],"names":[],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,kBAAkB,CAAC;AACzB,EAAE,WAAW,CAAC,GAAG;AACjB,IAAI,IAAI,CAAC,GAAG,GAAG,IAAI,GAAG,GAAE;AACxB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,CAAC,CAAC,GAAG,EAAE,QAAQ,EAAE;AAC1B,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,EAAC;AAC/B,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE,OAAO,CAAC,CAAC,GAAG,EAAE;AAChB,IAAI,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC;AAC5B,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA,IAAI,aAAa,GAAG,IAAI,kBAAkB,GAAE;AAC5C,IAAI,WAAW,GAAG,KAAI;AACtB;AACA;AACA,IAAI;AACJ;AACA,EAAE,IAAI,OAAO,YAAY,KAAK,WAAW,IAAI,YAAY,EAAE;AAC3D,IAAI,aAAa,GAAG,aAAY;AAChC,IAAI,WAAW,GAAG,MAAK;AACvB,GAAG;AACH,CAAC,CAAC,OAAO,CAAC,EAAE,GAAG;AACf;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,UAAU,GAAG,cAAa;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,YAAY,IAAI,WAAW,IAAI,gBAAgB,CAAC,SAAS,sBAAsB,YAAY,GAAE;AACrH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,SAAS,GAAG,YAAY,IAAI,WAAW,IAAI,mBAAmB,CAAC,SAAS,sBAAsB,YAAY;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/storage.d.ts b/nodejs/node_modules/lib0/dist/storage.d.ts new file mode 100644 index 00000000..6c69f2e2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/storage.d.ts @@ -0,0 +1,15 @@ +/** + * This is basically localStorage in browser, or a polyfill in nodejs + */ +export const varStorage: any; +export function onChange(eventHandler: (arg0: { + key: string; + newValue: string; + oldValue: string; +}) => void): true | void; +export function offChange(eventHandler: (arg0: { + key: string; + newValue: string; + oldValue: string; +}) => void): true | void; +//# sourceMappingURL=storage.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/storage.d.ts.map b/nodejs/node_modules/lib0/dist/storage.d.ts.map new file mode 100644 index 00000000..77933f14 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../storage.js"],"names":[],"mappings":"AAiDA;;GAEG;AAEH,6BAAuC;AAShC,8CAJa;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,KAAG,IAAI,eAIuC;AAS9G,+CAJa;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,KAAG,IAAI,eAI2C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/storage.test.d.ts b/nodejs/node_modules/lib0/dist/storage.test.d.ts new file mode 100644 index 00000000..d87bfa9c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/storage.test.d.ts @@ -0,0 +1,3 @@ +export function testStorageModule(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=storage.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/storage.test.d.ts.map b/nodejs/node_modules/lib0/dist/storage.test.d.ts.map new file mode 100644 index 00000000..15fa30b8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/storage.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.test.d.ts","sourceRoot":"","sources":["../storage.test.js"],"names":[],"mappings":"AAMO,sCAFI,EAAE,QAAQ,QAapB;mBAhBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/string-6d104757.cjs b/nodejs/node_modules/lib0/dist/string-6d104757.cjs new file mode 100644 index 00000000..a96b5fe8 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string-6d104757.cjs @@ -0,0 +1,177 @@ +'use strict'; + +var array = require('./array-704ca50e.cjs'); + +/** + * Utility module to work with strings. + * + * @module string + */ + +const fromCharCode = String.fromCharCode; +const fromCodePoint = String.fromCodePoint; + +/** + * The largest utf16 character. + * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8) + */ +const MAX_UTF16_CHARACTER = fromCharCode(65535); + +/** + * @param {string} s + * @return {string} + */ +const toLowerCase = s => s.toLowerCase(); + +const trimLeftRegex = /^\s*/g; + +/** + * @param {string} s + * @return {string} + */ +const trimLeft = s => s.replace(trimLeftRegex, ''); + +const fromCamelCaseRegex = /([A-Z])/g; + +/** + * @param {string} s + * @param {string} separator + * @return {string} + */ +const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`)); + +/** + * Compute the utf8ByteLength + * @param {string} str + * @return {number} + */ +const utf8ByteLength = str => unescape(encodeURIComponent(str)).length; + +/** + * @param {string} str + * @return {Uint8Array} + */ +const _encodeUtf8Polyfill = str => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + const buf = new Uint8Array(len); + for (let i = 0; i < len; i++) { + buf[i] = /** @type {number} */ (encodedString.codePointAt(i)); + } + return buf +}; + +/* c8 ignore next */ +const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null); + +/** + * @param {string} str + * @return {Uint8Array} + */ +const _encodeUtf8Native = str => utf8TextEncoder.encode(str); + +/** + * @param {string} str + * @return {Uint8Array} + */ +/* c8 ignore next */ +const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; + +/** + * @param {Uint8Array} buf + * @return {string} + */ +const _decodeUtf8Polyfill = buf => { + let remainingLen = buf.length; + let encodedString = ''; + let bufPos = 0; + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000; + const bytes = buf.subarray(bufPos, bufPos + nextLen); + bufPos += nextLen; + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)); + remainingLen -= nextLen; + } + return decodeURIComponent(escape(encodedString)) +}; + +/* c8 ignore next */ +exports.utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +/* c8 ignore start */ +if (exports.utf8TextDecoder && exports.utf8TextDecoder.decode(new Uint8Array()).length === 1) { + // Safari doesn't handle BOM correctly. + // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called. + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call + // Another issue is that from then on no BOM chars are recognized anymore + /* c8 ignore next */ + exports.utf8TextDecoder = null; +} +/* c8 ignore stop */ + +/** + * @param {Uint8Array} buf + * @return {string} + */ +const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (exports.utf8TextDecoder).decode(buf); + +/** + * @param {Uint8Array} buf + * @return {string} + */ +/* c8 ignore next */ +const decodeUtf8 = exports.utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill; + +/** + * @param {string} str The initial string + * @param {number} index Starting position + * @param {number} remove Number of characters to remove + * @param {string} insert New content to insert + */ +const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove); + +/** + * @param {string} source + * @param {number} n + */ +const repeat = (source, n) => array.unfold(n, () => source).join(''); + +var string = /*#__PURE__*/Object.freeze({ + __proto__: null, + fromCharCode: fromCharCode, + fromCodePoint: fromCodePoint, + MAX_UTF16_CHARACTER: MAX_UTF16_CHARACTER, + trimLeft: trimLeft, + fromCamelCase: fromCamelCase, + utf8ByteLength: utf8ByteLength, + _encodeUtf8Polyfill: _encodeUtf8Polyfill, + utf8TextEncoder: utf8TextEncoder, + _encodeUtf8Native: _encodeUtf8Native, + encodeUtf8: encodeUtf8, + _decodeUtf8Polyfill: _decodeUtf8Polyfill, + get utf8TextDecoder () { return exports.utf8TextDecoder; }, + _decodeUtf8Native: _decodeUtf8Native, + decodeUtf8: decodeUtf8, + splice: splice, + repeat: repeat +}); + +exports.MAX_UTF16_CHARACTER = MAX_UTF16_CHARACTER; +exports._decodeUtf8Native = _decodeUtf8Native; +exports._decodeUtf8Polyfill = _decodeUtf8Polyfill; +exports._encodeUtf8Native = _encodeUtf8Native; +exports._encodeUtf8Polyfill = _encodeUtf8Polyfill; +exports.decodeUtf8 = decodeUtf8; +exports.encodeUtf8 = encodeUtf8; +exports.fromCamelCase = fromCamelCase; +exports.fromCharCode = fromCharCode; +exports.fromCodePoint = fromCodePoint; +exports.repeat = repeat; +exports.splice = splice; +exports.string = string; +exports.trimLeft = trimLeft; +exports.utf8ByteLength = utf8ByteLength; +exports.utf8TextEncoder = utf8TextEncoder; +//# sourceMappingURL=string-6d104757.cjs.map diff --git a/nodejs/node_modules/lib0/dist/string-6d104757.cjs.map b/nodejs/node_modules/lib0/dist/string-6d104757.cjs.map new file mode 100644 index 00000000..827b87e9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string-6d104757.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"string-6d104757.cjs","sources":["../string.js"],"sourcesContent":["import * as array from './array.js'\n\n/**\n * Utility module to work with strings.\n *\n * @module string\n */\n\nexport const fromCharCode = String.fromCharCode\nexport const fromCodePoint = String.fromCodePoint\n\n/**\n * The largest utf16 character.\n * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)\n */\nexport const MAX_UTF16_CHARACTER = fromCharCode(65535)\n\n/**\n * @param {string} s\n * @return {string}\n */\nconst toLowerCase = s => s.toLowerCase()\n\nconst trimLeftRegex = /^\\s*/g\n\n/**\n * @param {string} s\n * @return {string}\n */\nexport const trimLeft = s => s.replace(trimLeftRegex, '')\n\nconst fromCamelCaseRegex = /([A-Z])/g\n\n/**\n * @param {string} s\n * @param {string} separator\n * @return {string}\n */\nexport const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`))\n\n/**\n * Compute the utf8ByteLength\n * @param {string} str\n * @return {number}\n */\nexport const utf8ByteLength = str => unescape(encodeURIComponent(str)).length\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Polyfill = str => {\n const encodedString = unescape(encodeURIComponent(str))\n const len = encodedString.length\n const buf = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n buf[i] = /** @type {number} */ (encodedString.codePointAt(i))\n }\n return buf\n}\n\n/* c8 ignore next */\nexport const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\nexport const _encodeUtf8Native = str => utf8TextEncoder.encode(str)\n\n/**\n * @param {string} str\n * @return {Uint8Array}\n */\n/* c8 ignore next */\nexport const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Polyfill = buf => {\n let remainingLen = buf.length\n let encodedString = ''\n let bufPos = 0\n while (remainingLen > 0) {\n const nextLen = remainingLen < 10000 ? remainingLen : 10000\n const bytes = buf.subarray(bufPos, bufPos + nextLen)\n bufPos += nextLen\n // Starting with ES5.1 we can supply a generic array-like object as arguments\n encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes))\n remainingLen -= nextLen\n }\n return decodeURIComponent(escape(encodedString))\n}\n\n/* c8 ignore next */\nexport let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\n/* c8 ignore start */\nif (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {\n // Safari doesn't handle BOM correctly.\n // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and\n // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call\n // Another issue is that from then on no BOM chars are recognized anymore\n /* c8 ignore next */\n utf8TextDecoder = null\n}\n/* c8 ignore stop */\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\nexport const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf)\n\n/**\n * @param {Uint8Array} buf\n * @return {string}\n */\n/* c8 ignore next */\nexport const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill\n\n/**\n * @param {string} str The initial string\n * @param {number} index Starting position\n * @param {number} remove Number of characters to remove\n * @param {string} insert New content to insert\n */\nexport const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove)\n\n/**\n * @param {string} source\n * @param {number} n\n */\nexport const repeat = (source, n) => array.unfold(n, () => source).join('')\n"],"names":["utf8TextDecoder","array.unfold"],"mappings":";;;;AAEA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,YAAY,GAAG,MAAM,CAAC,aAAY;AACnC,MAAC,aAAa,GAAG,MAAM,CAAC,cAAa;AACjD;AACA;AACA;AACA;AACA;AACY,MAAC,mBAAmB,GAAG,YAAY,CAAC,KAAK,EAAC;AACtD;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,GAAE;AACxC;AACA,MAAM,aAAa,GAAG,QAAO;AAC7B;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,EAAC;AACzD;AACA,MAAM,kBAAkB,GAAG,WAAU;AACrC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,aAAa,GAAG,CAAC,CAAC,EAAE,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,KAAK,IAAI,CAAC,EAAE,SAAS,CAAC,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAC;AACpI;AACA;AACA;AACA;AAC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;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/string.cjs b/nodejs/node_modules/lib0/dist/string.cjs new file mode 100644 index 00000000..860cb941 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string.cjs @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./array-704ca50e.cjs'); +var string = require('./string-6d104757.cjs'); +require('./set-0f209abb.cjs'); + + + +exports.MAX_UTF16_CHARACTER = string.MAX_UTF16_CHARACTER; +exports._decodeUtf8Native = string._decodeUtf8Native; +exports._decodeUtf8Polyfill = string._decodeUtf8Polyfill; +exports._encodeUtf8Native = string._encodeUtf8Native; +exports._encodeUtf8Polyfill = string._encodeUtf8Polyfill; +exports.decodeUtf8 = string.decodeUtf8; +exports.encodeUtf8 = string.encodeUtf8; +exports.fromCamelCase = string.fromCamelCase; +exports.fromCharCode = string.fromCharCode; +exports.fromCodePoint = string.fromCodePoint; +exports.repeat = string.repeat; +exports.splice = string.splice; +exports.trimLeft = string.trimLeft; +exports.utf8ByteLength = string.utf8ByteLength; +Object.defineProperty(exports, 'utf8TextDecoder', { + enumerable: true, + get: function () { return string.utf8TextDecoder; } +}); +exports.utf8TextEncoder = string.utf8TextEncoder; +//# sourceMappingURL=string.cjs.map diff --git a/nodejs/node_modules/lib0/dist/string.cjs.map b/nodejs/node_modules/lib0/dist/string.cjs.map new file mode 100644 index 00000000..7aa4f31a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"string.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/string.d.ts b/nodejs/node_modules/lib0/dist/string.d.ts new file mode 100644 index 00000000..2d1d9e29 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string.d.ts @@ -0,0 +1,26 @@ +/** + * Utility module to work with strings. + * + * @module string + */ +export const fromCharCode: (...codes: number[]) => string; +export const fromCodePoint: (...codePoints: number[]) => string; +/** + * The largest utf16 character. + * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8) + */ +export const MAX_UTF16_CHARACTER: string; +export function trimLeft(s: string): string; +export function fromCamelCase(s: string, separator: string): string; +export function utf8ByteLength(str: string): number; +export function _encodeUtf8Polyfill(str: string): Uint8Array; +export const utf8TextEncoder: TextEncoder; +export function _encodeUtf8Native(str: string): Uint8Array; +export function encodeUtf8(str: string): Uint8Array; +export function _decodeUtf8Polyfill(buf: Uint8Array): string; +export let utf8TextDecoder: TextDecoder | null; +export function _decodeUtf8Native(buf: Uint8Array): string; +export function decodeUtf8(buf: Uint8Array): string; +export function splice(str: string, index: number, remove: number, insert?: string): string; +export function repeat(source: string, n: number): string; +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/string.d.ts.map b/nodejs/node_modules/lib0/dist/string.d.ts.map new file mode 100644 index 00000000..b08704df --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../string.js"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,0DAA+C;AAC/C,gEAAiD;AAEjD;;;GAGG;AACH,yCAAsD;AAc/C,4BAHI,MAAM,GACL,MAAM,CAEuC;AASlD,iCAJI,MAAM,aACN,MAAM,GACL,MAAM,CAEkH;AAO7H,oCAHI,MAAM,GACL,MAAM,CAE2D;AAMtE,yCAHI,MAAM,GACL,UAAU,CAUrB;AAGD,0CAAyH;AAMlH,uCAHI,MAAM,GACL,UAAU,CAE6C;AAjB5D,gCAHI,MAAM,GACL,UAAU,CAUrB;AAsBM,yCAHI,UAAU,GACT,MAAM,CAejB;AAGD,+CAAmI;AAkB5H,uCAHI,UAAU,GACT,MAAM,CAE8E;AAlCzF,gCAHI,UAAU,GACT,MAAM,CAejB;AAoCM,4BALI,MAAM,SACN,MAAM,UACN,MAAM,WACN,MAAM,UAEkG;AAM5G,+BAHI,MAAM,KACN,MAAM,UAE0D"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/string.test.d.ts b/nodejs/node_modules/lib0/dist/string.test.d.ts new file mode 100644 index 00000000..af14fca6 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string.test.d.ts @@ -0,0 +1,8 @@ +export function testUtilities(tc: t.TestCase): void; +export function testLowercaseTransformation(tc: t.TestCase): void; +export function testRepeatStringUtf8Encoding(tc: t.TestCase): void; +export function testRepeatStringUtf8Decoding(tc: t.TestCase): void; +export function testBomEncodingDecoding(tc: t.TestCase): void; +export function testSplice(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=string.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/string.test.d.ts.map b/nodejs/node_modules/lib0/dist/string.test.d.ts.map new file mode 100644 index 00000000..c872eb1b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/string.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.test.d.ts","sourceRoot":"","sources":["../string.test.js"],"names":[],"mappings":"AAOO,kCAFI,EAAE,QAAQ,QAMpB;AAKM,gDAFI,EAAE,QAAQ,QAOpB;AAKM,iDAFI,EAAE,QAAQ,QAapB;AAKM,iDAFI,EAAE,QAAQ,QAapB;AAKM,4CAFI,EAAE,QAAQ,QAYpB;AAKM,+BAFI,EAAE,QAAQ,QAMpB;mBA3EkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/symbol-c5caa724.cjs b/nodejs/node_modules/lib0/dist/symbol-c5caa724.cjs new file mode 100644 index 00000000..140c2ab5 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol-c5caa724.cjs @@ -0,0 +1,31 @@ +'use strict'; + +/** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ + +/** + * Return fresh symbol. + * + * @return {Symbol} + */ +const create = Symbol; + +/** + * @param {any} s + * @return {boolean} + */ +const isSymbol = s => typeof s === 'symbol'; + +var symbol = /*#__PURE__*/Object.freeze({ + __proto__: null, + create: create, + isSymbol: isSymbol +}); + +exports.create = create; +exports.isSymbol = isSymbol; +exports.symbol = symbol; +//# sourceMappingURL=symbol-c5caa724.cjs.map diff --git a/nodejs/node_modules/lib0/dist/symbol-c5caa724.cjs.map b/nodejs/node_modules/lib0/dist/symbol-c5caa724.cjs.map new file mode 100644 index 00000000..9ce6a57a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol-c5caa724.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol-c5caa724.cjs","sources":["../symbol.js"],"sourcesContent":["/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nexport const create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nexport const isSymbol = s => typeof s === 'symbol'\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,MAAM,GAAG,OAAM;AAC5B;AACA;AACA;AACA;AACA;AACY,MAAC,QAAQ,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/symbol.cjs b/nodejs/node_modules/lib0/dist/symbol.cjs new file mode 100644 index 00000000..72d92b06 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol.cjs @@ -0,0 +1,11 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var symbol = require('./symbol-c5caa724.cjs'); + + + +exports.create = symbol.create; +exports.isSymbol = symbol.isSymbol; +//# sourceMappingURL=symbol.cjs.map diff --git a/nodejs/node_modules/lib0/dist/symbol.cjs.map b/nodejs/node_modules/lib0/dist/symbol.cjs.map new file mode 100644 index 00000000..5e1c70ed --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/symbol.d.ts b/nodejs/node_modules/lib0/dist/symbol.d.ts new file mode 100644 index 00000000..d8de71b3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol.d.ts @@ -0,0 +1,13 @@ +/** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ +/** + * Return fresh symbol. + * + * @return {Symbol} + */ +export const create: SymbolConstructor; +export function isSymbol(s: any): boolean; +//# sourceMappingURL=symbol.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/symbol.d.ts.map b/nodejs/node_modules/lib0/dist/symbol.d.ts.map new file mode 100644 index 00000000..1a7bd2d7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.d.ts","sourceRoot":"","sources":["../symbol.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,uCAA4B;AAMrB,4BAHI,GAAG,GACF,OAAO,CAE+B"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/symbol.test.d.ts b/nodejs/node_modules/lib0/dist/symbol.test.d.ts new file mode 100644 index 00000000..3a29f019 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol.test.d.ts @@ -0,0 +1,3 @@ +export function testBasicSymbolFeatures(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=symbol.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/symbol.test.d.ts.map b/nodejs/node_modules/lib0/dist/symbol.test.d.ts.map new file mode 100644 index 00000000..5893db0c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/symbol.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.test.d.ts","sourceRoot":"","sources":["../symbol.test.js"],"names":[],"mappings":"AAMO,6CAFI,EAAE,QAAQ,QAQpB;mBAZkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/testing.cjs b/nodejs/node_modules/lib0/dist/testing.cjs new file mode 100644 index 00000000..277f0b25 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/testing.cjs @@ -0,0 +1,701 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var log = require('lib0/logging'); +var diff = require('./diff-fbaa426b.cjs'); +var object = require('./object-fecf6a7b.cjs'); +var string = require('./string-6d104757.cjs'); +var math = require('./math-08e068f9.cjs'); +var random = require('./random.cjs'); +var prng = require('./prng-e4f28259.cjs'); +var statistics = require('./statistics-c2316dca.cjs'); +var array = require('./array-704ca50e.cjs'); +var environment = require('./environment-f4d7c3e5.cjs'); +var json = require('./json-092190a1.cjs'); +var time = require('./time-bc2081b9.cjs'); +var promise = require('./promise-afe9dfc3.cjs'); +var performance = require('lib0/performance'); +require('./function-314fdc56.cjs'); +require('./binary-ac8e39e2.cjs'); +require('lib0/webcrypto'); +require('./buffer-f11b8d4d.cjs'); +require('./encoding-882cb136.cjs'); +require('./number-466d8922.cjs'); +require('./decoding-000d097f.cjs'); +require('./error-8582d695.cjs'); +require('./set-0f209abb.cjs'); +require('./map-0dabcc55.cjs'); +require('./conditions-f5c0c102.cjs'); +require('./storage.cjs'); +require('./metric.cjs'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var log__namespace = /*#__PURE__*/_interopNamespace(log); +var performance__namespace = /*#__PURE__*/_interopNamespace(performance); + +/** + * Testing framework with support for generating tests. + * + * ```js + * // test.js template for creating a test executable + * import { runTests } from 'lib0/testing' + * import * as log from 'lib0/logging' + * import * as mod1 from './mod1.test.js' + * import * as mod2 from './mod2.test.js' + + * import { isBrowser, isNode } from 'lib0/environment.js' + * + * if (isBrowser) { + * // optional: if this is ran in the browser, attach a virtual console to the dom + * log.createVConsole(document.body) + * } + * + * runTests({ + * mod1, + * mod2, + * }).then(success => { + * if (isNode) { + * process.exit(success ? 0 : 1) + * } + * }) + * ``` + * + * ```js + * // mod1.test.js + * /** + * * runTests automatically tests all exported functions that start with "test". + * * The name of the function should be in camelCase and is used for the logging output. + * * + * * @param {t.TestCase} tc + * *\/ + * export const testMyFirstTest = tc => { + * t.compare({ a: 4 }, { a: 4 }, 'objects are equal') + * } + * ``` + * + * Now you can simply run `node test.js` to run your test or run test.js in the browser. + * + * @module testing + */ + +const extensive = environment.hasConf('extensive'); + +/* c8 ignore next */ +const envSeed = environment.hasParam('--seed') ? Number.parseInt(environment.getParam('--seed', '0')) : null; + +class TestCase { + /** + * @param {string} moduleName + * @param {string} testName + */ + constructor (moduleName, testName) { + /** + * @type {string} + */ + this.moduleName = moduleName; + /** + * @type {string} + */ + this.testName = testName; + /** + * This type can store custom information related to the TestCase + * + * @type {Map} + */ + this.meta = new Map(); + this._seed = null; + this._prng = null; + } + + resetSeed () { + this._seed = null; + this._prng = null; + } + + /** + * @type {number} + */ + /* c8 ignore next */ + get seed () { + /* c8 ignore else */ + if (this._seed === null) { + /* c8 ignore next */ + this._seed = envSeed === null ? random.uint32() : envSeed; + } + return this._seed + } + + /** + * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible. + * + * @type {prng.PRNG} + */ + get prng () { + /* c8 ignore else */ + if (this._prng === null) { + this._prng = prng.create(this.seed); + } + return this._prng + } +} + +const repetitionTime = Number(environment.getParam('--repetition-time', '50')); +/* c8 ignore next */ +const testFilter = environment.hasParam('--filter') ? environment.getParam('--filter', '') : null; + +/* c8 ignore next */ +const testFilterRegExp = testFilter !== null ? new RegExp(testFilter) : /.*/; + +const repeatTestRegex = /^(repeat|repeating)\s/; + +/** + * @param {string} moduleName + * @param {string} name + * @param {function(TestCase):void|Promise} f + * @param {number} i + * @param {number} numberOfTests + */ +const run = async (moduleName, name, f, i, numberOfTests) => { + const uncamelized = string.fromCamelCase(name.slice(4), ' '); + const filtered = !testFilterRegExp.test(`[${i + 1}/${numberOfTests}] ${moduleName}: ${uncamelized}`); + /* c8 ignore next 3 */ + if (filtered) { + return true + } + const tc = new TestCase(moduleName, name); + const repeat = repeatTestRegex.test(uncamelized); + const groupArgs = [log__namespace.GREY, `[${i + 1}/${numberOfTests}] `, log__namespace.PURPLE, `${moduleName}: `, log__namespace.BLUE, uncamelized]; + /* c8 ignore next 5 */ + if (testFilter === null) { + log__namespace.groupCollapsed(...groupArgs); + } else { + log__namespace.group(...groupArgs); + } + const times = []; + const start = performance__namespace.now(); + let lastTime = start; + /** + * @type {any} + */ + let err = null; + performance__namespace.mark(`${name}-start`); + do { + try { + const p = f(tc); + if (promise.isPromise(p)) { + await p; + } + } catch (_err) { + err = _err; + } + const currTime = performance__namespace.now(); + times.push(currTime - lastTime); + lastTime = currTime; + if (repeat && err === null && (lastTime - start) < repetitionTime) { + tc.resetSeed(); + } else { + break + } + } while (err === null && (lastTime - start) < repetitionTime) + performance__namespace.mark(`${name}-end`); + /* c8 ignore next 3 */ + if (err !== null && err.constructor !== SkipError) { + log__namespace.printError(err); + } + performance__namespace.measure(name, `${name}-start`, `${name}-end`); + log__namespace.groupEnd(); + const duration = lastTime - start; + let success = true; + times.sort((a, b) => a - b); + /* c8 ignore next 3 */ + const againMessage = environment.isBrowser + ? ` - ${window.location.host + window.location.pathname}?filter=\\[${i + 1}/${tc._seed === null ? '' : `&seed=${tc._seed}`}` + : `\nrepeat: npm run test -- --filter "\\[${i + 1}/" ${tc._seed === null ? '' : `--seed ${tc._seed}`}`; + const timeInfo = (repeat && err === null) + ? ` - ${times.length} repetitions in ${time.humanizeDuration(duration)} (best: ${time.humanizeDuration(times[0])}, worst: ${time.humanizeDuration(array.last(times))}, median: ${time.humanizeDuration(statistics.median(times))}, average: ${time.humanizeDuration(statistics.average(times))})` + : ` in ${time.humanizeDuration(duration)}`; + if (err !== null) { + /* c8 ignore start */ + if (err.constructor === SkipError) { + log__namespace.print(log__namespace.GREY, log__namespace.BOLD, 'Skipped: ', log__namespace.UNBOLD, uncamelized); + } else { + success = false; + log__namespace.print(log__namespace.RED, log__namespace.BOLD, 'Failure: ', log__namespace.UNBOLD, log__namespace.UNCOLOR, uncamelized, log__namespace.GREY, timeInfo, againMessage); + } + /* c8 ignore stop */ + } else { + log__namespace.print(log__namespace.GREEN, log__namespace.BOLD, 'Success: ', log__namespace.UNBOLD, log__namespace.UNCOLOR, uncamelized, log__namespace.GREY, timeInfo, againMessage); + } + return success +}; + +/** + * Describe what you are currently testing. The message will be logged. + * + * ```js + * export const testMyFirstTest = tc => { + * t.describe('crunching numbers', 'already crunched 4 numbers!') // the optional second argument can describe the state. + * } + * ``` + * + * @param {string} description + * @param {string} info + */ +const describe = (description, info = '') => log__namespace.print(log__namespace.BLUE, description, ' ', log__namespace.GREY, info); + +/** + * Describe the state of the current computation. + * ```js + * export const testMyFirstTest = tc => { + * t.info(already crunched 4 numbers!') // the optional second argument can describe the state. + * } + * ``` + * + * @param {string} info + */ +const info = info => describe('', info); + +const printDom = log__namespace.printDom; + +const printCanvas = log__namespace.printCanvas; + +/** + * Group outputs in a collapsible category. + * + * ```js + * export const testMyFirstTest = tc => { + * t.group('subtest 1', () => { + * t.describe('this message is part of a collapsible section') + * }) + * await t.groupAsync('subtest async 2', async () => { + * await someaction() + * t.describe('this message is part of a collapsible section') + * }) + * } + * ``` + * + * @param {string} description + * @param {function(...any):void} f + */ +const group = (description, f) => { + log__namespace.group(log__namespace.BLUE, description); + try { + f(); + } finally { + log__namespace.groupEnd(); + } +}; + +/** + * Group outputs in a collapsible category. + * + * ```js + * export const testMyFirstTest = async tc => { + * t.group('subtest 1', () => { + * t.describe('this message is part of a collapsible section') + * }) + * await t.groupAsync('subtest async 2', async () => { + * await someaction() + * t.describe('this message is part of a collapsible section') + * }) + * } + * ``` + * + * @param {string} description + * @param {function(...any):Promise} f + */ +const groupAsync = async (description, f) => { + log__namespace.group(log__namespace.BLUE, description); + try { + await f(); + } finally { + log__namespace.groupEnd(); + } +}; + +/** + * Measure the time that it takes to calculate something. + * + * ```js + * export const testMyFirstTest = async tc => { + * t.measureTime('measurement', () => { + * heavyCalculation() + * }) + * await t.groupAsync('async measurement', async () => { + * await heavyAsyncCalculation() + * }) + * } + * ``` + * + * @param {string} message + * @param {function(...any):void} f + * @return {number} Returns a promise that resolves the measured duration to apply f + */ +const measureTime = (message, f) => { + let duration; + const start = performance__namespace.now(); + try { + f(); + } finally { + duration = performance__namespace.now() - start; + log__namespace.print(log__namespace.PURPLE, message, log__namespace.GREY, ` ${time.humanizeDuration(duration)}`); + } + return duration +}; + +/** + * Measure the time that it takes to calculate something. + * + * ```js + * export const testMyFirstTest = async tc => { + * t.measureTimeAsync('measurement', async () => { + * await heavyCalculation() + * }) + * await t.groupAsync('async measurement', async () => { + * await heavyAsyncCalculation() + * }) + * } + * ``` + * + * @param {string} message + * @param {function(...any):Promise} f + * @return {Promise} Returns a promise that resolves the measured duration to apply f + */ +const measureTimeAsync = async (message, f) => { + let duration; + const start = performance__namespace.now(); + try { + await f(); + } finally { + duration = performance__namespace.now() - start; + log__namespace.print(log__namespace.PURPLE, message, log__namespace.GREY, ` ${time.humanizeDuration(duration)}`); + } + return duration +}; + +/** + * @template T + * @param {Array} as + * @param {Array} bs + * @param {string} [m] + * @return {boolean} + */ +const compareArrays = (as, bs, m = 'Arrays match') => { + if (as.length !== bs.length) { + fail(m); + } + for (let i = 0; i < as.length; i++) { + if (as[i] !== bs[i]) { + fail(m); + } + } + return true +}; + +/** + * @param {string} a + * @param {string} b + * @param {string} [m] + * @throws {TestError} Throws if tests fails + */ +const compareStrings = (a, b, m = 'Strings match') => { + if (a !== b) { + const diff$1 = diff.simpleDiffString(a, b); + log__namespace.print(log__namespace.GREY, a.slice(0, diff$1.index), log__namespace.RED, a.slice(diff$1.index, diff$1.remove), log__namespace.GREEN, diff$1.insert, log__namespace.GREY, a.slice(diff$1.index + diff$1.remove)); + fail(m); + } +}; + +/** + * @template K,V + * @param {Object} a + * @param {Object} b + * @param {string} [m] + * @throws {TestError} Throws if test fails + */ +const compareObjects = (a, b, m = 'Objects match') => { object.equalFlat(a, b) || fail(m); }; + +/** + * @param {any} _constructor + * @param {any} a + * @param {any} b + * @param {string} path + * @throws {TestError} + */ +const compareValues = (_constructor, a, b, path) => { + if (a !== b) { + fail(`Values ${json.stringify(a)} and ${json.stringify(b)} don't match (${path})`); + } + return true +}; + +/** + * @param {string?} message + * @param {string} reason + * @param {string} path + * @throws {TestError} + */ +const _failMessage = (message, reason, path) => fail( + message === null + ? `${reason} ${path}` + : `${message} (${reason}) ${path}` +); + +/** + * @param {any} a + * @param {any} b + * @param {string} path + * @param {string?} message + * @param {function(any,any,any,string,any):boolean} customCompare + */ +const _compare = (a, b, path, message, customCompare) => { + // we don't use assert here because we want to test all branches (istanbul errors if one branch is not tested) + if (a == null || b == null) { + return compareValues(null, a, b, path) + } + if (a.constructor !== b.constructor) { + _failMessage(message, 'Constructors don\'t match', path); + } + let success = true; + switch (a.constructor) { + case ArrayBuffer: + a = new Uint8Array(a); + b = new Uint8Array(b); + // eslint-disable-next-line no-fallthrough + case Uint8Array: { + if (a.byteLength !== b.byteLength) { + _failMessage(message, 'ArrayBuffer lengths match', path); + } + for (let i = 0; success && i < a.length; i++) { + success = success && a[i] === b[i]; + } + break + } + case Set: { + if (a.size !== b.size) { + _failMessage(message, 'Sets have different number of attributes', path); + } + // @ts-ignore + a.forEach(value => { + if (!b.has(value)) { + _failMessage(message, `b.${path} does have ${value}`, path); + } + }); + break + } + case Map: { + if (a.size !== b.size) { + _failMessage(message, 'Maps have different number of attributes', path); + } + // @ts-ignore + a.forEach((value, key) => { + if (!b.has(key)) { + _failMessage(message, `Property ${path}["${key}"] does not exist on second argument`, path); + } + _compare(value, b.get(key), `${path}["${key}"]`, message, customCompare); + }); + break + } + case Object: + if (object.length(a) !== object.length(b)) { + _failMessage(message, 'Objects have a different number of attributes', path); + } + object.forEach(a, (value, key) => { + if (!object.hasProperty(b, key)) { + _failMessage(message, `Property ${path} does not exist on second argument`, path); + } + _compare(value, b[key], `${path}["${key}"]`, message, customCompare); + }); + break + case Array: + if (a.length !== b.length) { + _failMessage(message, 'Arrays have a different number of attributes', path); + } + // @ts-ignore + a.forEach((value, i) => _compare(value, b[i], `${path}[${i}]`, message, customCompare)); + break + /* c8 ignore next 4 */ + default: + if (!customCompare(a.constructor, a, b, path, compareValues)) { + _failMessage(message, `Values ${json.stringify(a)} and ${json.stringify(b)} don't match`, path); + } + } + assert(success, message); + return true +}; + +/** + * @template T + * @param {T} a + * @param {T} b + * @param {string?} [message] + * @param {function(any,T,T,string,any):boolean} [customCompare] + */ +const compare = (a, b, message = null, customCompare = compareValues) => _compare(a, b, 'obj', message, customCompare); + +/** + * @template T + * @param {T} property + * @param {string?} [message] + * @return {asserts property is NonNullable} + * @throws {TestError} + */ +/* c8 ignore next */ +const assert = (property, message = null) => { property || fail(`Assertion failed${message !== null ? `: ${message}` : ''}`); }; + +/** + * @param {function(...any):Promise} f + */ +const promiseRejected = async f => { + try { + await f(); + } catch (err) { + return + } + fail('Expected promise to fail'); +}; + +/** + * @param {function(...any):void} f + * @throws {TestError} + */ +const fails = f => { + try { + f(); + } catch (_err) { + log__namespace.print(log__namespace.GREEN, '⇖ This Error was expected'); + return + } + fail('Expected this to fail'); +}; + +/** + * @param {function(...any):Promise} f + * @throws {TestError} + */ +const failsAsync = async f => { + try { + await f(); + } catch (_err) { + log__namespace.print(log__namespace.GREEN, '⇖ This Error was expected'); + return + } + fail('Expected this to fail'); +}; + +/** + * @param {Object>>} tests + */ +const runTests = async tests => { + /** + * @param {string} testname + */ + const filterTest = testname => testname.startsWith('test') || testname.startsWith('benchmark'); + const numberOfTests = object.map(tests, mod => object.map(mod, (f, fname) => /* c8 ignore next */ f && filterTest(fname) ? 1 : 0).reduce(math.add, 0)).reduce(math.add, 0); + let successfulTests = 0; + let testnumber = 0; + const start = performance__namespace.now(); + for (const modName in tests) { + const mod = tests[modName]; + for (const fname in mod) { + const f = mod[fname]; + /* c8 ignore else */ + if (f && filterTest(fname)) { + const repeatEachTest = 1; + let success = true; + for (let i = 0; success && i < repeatEachTest; i++) { + success = await run(modName, fname, f, testnumber, numberOfTests); + } + testnumber++; + /* c8 ignore else */ + if (success) { + successfulTests++; + } + } + } + } + const end = performance__namespace.now(); + log__namespace.print(''); + const success = successfulTests === numberOfTests; + /* c8 ignore start */ + if (success) { + log__namespace.print(log__namespace.GREEN, log__namespace.BOLD, 'All tests successful!', log__namespace.GREY, log__namespace.UNBOLD, ` in ${time.humanizeDuration(end - start)}`); + log__namespace.printImgBase64(nyanCatImage, 50); + } else { + const failedTests = numberOfTests - successfulTests; + log__namespace.print(log__namespace.RED, log__namespace.BOLD, `> ${failedTests} test${failedTests > 1 ? 's' : ''} failed`); + } + /* c8 ignore stop */ + return success +}; + +class TestError extends Error {} + +/** + * @param {string} reason + * @throws {TestError} + */ +const fail = reason => { + log__namespace.print(log__namespace.RED, log__namespace.BOLD, 'X ', log__namespace.UNBOLD, reason); + throw new TestError('Test Failed') +}; + +class SkipError extends Error {} + +/** + * @param {boolean} cond If true, this tests will be skipped + * @throws {SkipError} + */ +const skip = (cond = true) => { + if (cond) { + throw new SkipError('skipping..') + } +}; + +// eslint-disable-next-line +const nyanCatImage = 'R0lGODlhjABMAPcAAMiSE0xMTEzMzUKJzjQ0NFsoKPc7//FM/9mH/z9x0HIiIoKCgmBHN+frGSkZLdDQ0LCwsDk71g0KCUzDdrQQEOFz/8yYdelmBdTiHFxcXDU2erR/mLrTHCgoKK5szBQUFNgSCTk6ymfpCB9VZS2Bl+cGBt2N8kWm0uDcGXhZRUvGq94NCFPhDiwsLGVlZTgqIPMDA1g3aEzS5D6xAURERDtG9JmBjJsZGWs2AD1W6Hp6eswyDeJ4CFNTU1LcEoJRmTMzSd14CTg5ser2GmDz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+/RGiV3I99ZdbL332l2/f/fVEVH/962qYf7k76ItOxhEzuABkBhbkr//++aeQyf0ADKDzDBKGArbhgG3wQwEL6AcEtmGBBnQgBMPgQAUusIEInKADHwjBCkIQgwfUoAQ7iEALMtAPa5iEfbTQIT0YgTxGKJAMvfSFDhDoHgT4AgE6hBA/+GEQ2AgiNvy84EMfekGI2BhEEf1QAyQuEYhCJGIRjyhEJRaxiUJ8IhKlaEQkWtGHWAyiFqO4RC/UIIUl2s4H9PAlw+lrBPHQQ4UCtDU7vJEgbsijHvfIxz768Y+ADKQgB0lIQGJjDdvZjkBstJ3EHCSRRLLRHQnCiEoSJAKVrOQcCCKGTDIiApTMpBgIMgdPbnIgncxkQTw5yoGUMpOnFEgqLRnKSrZSIK/U5Ag+kLjEDaSXCQGmQHzJpWIasyV3OaYyl8nMZi7nLsl0ZkagKc1qWvOa2JxLNLPJzW6+ZZvevAhdwrkStJCTI2gZ5zknos51shOc7oynPOdJz3ra857hDAgAOw=='; + +exports.production = environment.production; +exports.TestCase = TestCase; +exports.assert = assert; +exports.compare = compare; +exports.compareArrays = compareArrays; +exports.compareObjects = compareObjects; +exports.compareStrings = compareStrings; +exports.describe = describe; +exports.envSeed = envSeed; +exports.extensive = extensive; +exports.fail = fail; +exports.fails = fails; +exports.failsAsync = failsAsync; +exports.group = group; +exports.groupAsync = groupAsync; +exports.info = info; +exports.measureTime = measureTime; +exports.measureTimeAsync = measureTimeAsync; +exports.printCanvas = printCanvas; +exports.printDom = printDom; +exports.promiseRejected = promiseRejected; +exports.repetitionTime = repetitionTime; +exports.run = run; +exports.runTests = runTests; +exports.skip = skip; +//# sourceMappingURL=testing.cjs.map diff --git a/nodejs/node_modules/lib0/dist/testing.cjs.map b/nodejs/node_modules/lib0/dist/testing.cjs.map new file mode 100644 index 00000000..095eba19 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/testing.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"testing.cjs","sources":["../testing.js"],"sourcesContent":["/**\n * Testing framework with support for generating tests.\n *\n * ```js\n * // test.js template for creating a test executable\n * import { runTests } from 'lib0/testing'\n * import * as log from 'lib0/logging'\n * import * as mod1 from './mod1.test.js'\n * import * as mod2 from './mod2.test.js'\n\n * import { isBrowser, isNode } from 'lib0/environment.js'\n *\n * if (isBrowser) {\n * // optional: if this is ran in the browser, attach a virtual console to the dom\n * log.createVConsole(document.body)\n * }\n *\n * runTests({\n * mod1,\n * mod2,\n * }).then(success => {\n * if (isNode) {\n * process.exit(success ? 0 : 1)\n * }\n * })\n * ```\n *\n * ```js\n * // mod1.test.js\n * /**\n * * runTests automatically tests all exported functions that start with \"test\".\n * * The name of the function should be in camelCase and is used for the logging output.\n * *\n * * @param {t.TestCase} tc\n * *\\/\n * export const testMyFirstTest = tc => {\n * t.compare({ a: 4 }, { a: 4 }, 'objects are equal')\n * }\n * ```\n *\n * Now you can simply run `node test.js` to run your test or run test.js in the browser.\n *\n * @module testing\n */\n\nimport * as log from 'lib0/logging'\nimport { simpleDiffString } from './diff.js'\nimport * as object from './object.js'\nimport * as string from './string.js'\nimport * as math from './math.js'\nimport * as random from './random.js'\nimport * as prng from './prng.js'\nimport * as statistics from './statistics.js'\nimport * as array from './array.js'\nimport * as env from './environment.js'\nimport * as json from './json.js'\nimport * as time from './time.js'\nimport * as promise from './promise.js'\nimport * as performance from 'lib0/performance'\n\nexport { production } from './environment.js'\n\nexport const extensive = env.hasConf('extensive')\n\n/* c8 ignore next */\nexport const envSeed = env.hasParam('--seed') ? Number.parseInt(env.getParam('--seed', '0')) : null\n\nexport class TestCase {\n /**\n * @param {string} moduleName\n * @param {string} testName\n */\n constructor (moduleName, testName) {\n /**\n * @type {string}\n */\n this.moduleName = moduleName\n /**\n * @type {string}\n */\n this.testName = testName\n /**\n * This type can store custom information related to the TestCase\n *\n * @type {Map}\n */\n this.meta = new Map()\n this._seed = null\n this._prng = null\n }\n\n resetSeed () {\n this._seed = null\n this._prng = null\n }\n\n /**\n * @type {number}\n */\n /* c8 ignore next */\n get seed () {\n /* c8 ignore else */\n if (this._seed === null) {\n /* c8 ignore next */\n this._seed = envSeed === null ? random.uint32() : envSeed\n }\n return this._seed\n }\n\n /**\n * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible.\n *\n * @type {prng.PRNG}\n */\n get prng () {\n /* c8 ignore else */\n if (this._prng === null) {\n this._prng = prng.create(this.seed)\n }\n return this._prng\n }\n}\n\nexport const repetitionTime = Number(env.getParam('--repetition-time', '50'))\n/* c8 ignore next */\nconst testFilter = env.hasParam('--filter') ? env.getParam('--filter', '') : null\n\n/* c8 ignore next */\nconst testFilterRegExp = testFilter !== null ? new RegExp(testFilter) : /.*/\n\nconst repeatTestRegex = /^(repeat|repeating)\\s/\n\n/**\n * @param {string} moduleName\n * @param {string} name\n * @param {function(TestCase):void|Promise} f\n * @param {number} i\n * @param {number} numberOfTests\n */\nexport const run = async (moduleName, name, f, i, numberOfTests) => {\n const uncamelized = string.fromCamelCase(name.slice(4), ' ')\n const filtered = !testFilterRegExp.test(`[${i + 1}/${numberOfTests}] ${moduleName}: ${uncamelized}`)\n /* c8 ignore next 3 */\n if (filtered) {\n return true\n }\n const tc = new TestCase(moduleName, name)\n const repeat = repeatTestRegex.test(uncamelized)\n const groupArgs = [log.GREY, `[${i + 1}/${numberOfTests}] `, log.PURPLE, `${moduleName}: `, log.BLUE, uncamelized]\n /* c8 ignore next 5 */\n if (testFilter === null) {\n log.groupCollapsed(...groupArgs)\n } else {\n log.group(...groupArgs)\n }\n const times = []\n const start = performance.now()\n let lastTime = start\n /**\n * @type {any}\n */\n let err = null\n performance.mark(`${name}-start`)\n do {\n try {\n const p = f(tc)\n if (promise.isPromise(p)) {\n await p\n }\n } catch (_err) {\n err = _err\n }\n const currTime = performance.now()\n times.push(currTime - lastTime)\n lastTime = currTime\n if (repeat && err === null && (lastTime - start) < repetitionTime) {\n tc.resetSeed()\n } else {\n break\n }\n } while (err === null && (lastTime - start) < repetitionTime)\n performance.mark(`${name}-end`)\n /* c8 ignore next 3 */\n if (err !== null && err.constructor !== SkipError) {\n log.printError(err)\n }\n performance.measure(name, `${name}-start`, `${name}-end`)\n log.groupEnd()\n const duration = lastTime - start\n let success = true\n times.sort((a, b) => a - b)\n /* c8 ignore next 3 */\n const againMessage = env.isBrowser\n ? ` - ${window.location.host + window.location.pathname}?filter=\\\\[${i + 1}/${tc._seed === null ? '' : `&seed=${tc._seed}`}`\n : `\\nrepeat: npm run test -- --filter \"\\\\[${i + 1}/\" ${tc._seed === null ? '' : `--seed ${tc._seed}`}`\n const timeInfo = (repeat && err === null)\n ? ` - ${times.length} repetitions in ${time.humanizeDuration(duration)} (best: ${time.humanizeDuration(times[0])}, worst: ${time.humanizeDuration(array.last(times))}, median: ${time.humanizeDuration(statistics.median(times))}, average: ${time.humanizeDuration(statistics.average(times))})`\n : ` in ${time.humanizeDuration(duration)}`\n if (err !== null) {\n /* c8 ignore start */\n if (err.constructor === SkipError) {\n log.print(log.GREY, log.BOLD, 'Skipped: ', log.UNBOLD, uncamelized)\n } else {\n success = false\n log.print(log.RED, log.BOLD, 'Failure: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage)\n }\n /* c8 ignore stop */\n } else {\n log.print(log.GREEN, log.BOLD, 'Success: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage)\n }\n return success\n}\n\n/**\n * Describe what you are currently testing. The message will be logged.\n *\n * ```js\n * export const testMyFirstTest = tc => {\n * t.describe('crunching numbers', 'already crunched 4 numbers!') // the optional second argument can describe the state.\n * }\n * ```\n *\n * @param {string} description\n * @param {string} info\n */\nexport const describe = (description, info = '') => log.print(log.BLUE, description, ' ', log.GREY, info)\n\n/**\n * Describe the state of the current computation.\n * ```js\n * export const testMyFirstTest = tc => {\n * t.info(already crunched 4 numbers!') // the optional second argument can describe the state.\n * }\n * ```\n *\n * @param {string} info\n */\nexport const info = info => describe('', info)\n\nexport const printDom = log.printDom\n\nexport const printCanvas = log.printCanvas\n\n/**\n * Group outputs in a collapsible category.\n *\n * ```js\n * export const testMyFirstTest = tc => {\n * t.group('subtest 1', () => {\n * t.describe('this message is part of a collapsible section')\n * })\n * await t.groupAsync('subtest async 2', async () => {\n * await someaction()\n * t.describe('this message is part of a collapsible section')\n * })\n * }\n * ```\n *\n * @param {string} description\n * @param {function(...any):void} f\n */\nexport const group = (description, f) => {\n log.group(log.BLUE, description)\n try {\n f()\n } finally {\n log.groupEnd()\n }\n}\n\n/**\n * Group outputs in a collapsible category.\n *\n * ```js\n * export const testMyFirstTest = async tc => {\n * t.group('subtest 1', () => {\n * t.describe('this message is part of a collapsible section')\n * })\n * await t.groupAsync('subtest async 2', async () => {\n * await someaction()\n * t.describe('this message is part of a collapsible section')\n * })\n * }\n * ```\n *\n * @param {string} description\n * @param {function(...any):Promise} f\n */\nexport const groupAsync = async (description, f) => {\n log.group(log.BLUE, description)\n try {\n await f()\n } finally {\n log.groupEnd()\n }\n}\n\n/**\n * Measure the time that it takes to calculate something.\n *\n * ```js\n * export const testMyFirstTest = async tc => {\n * t.measureTime('measurement', () => {\n * heavyCalculation()\n * })\n * await t.groupAsync('async measurement', async () => {\n * await heavyAsyncCalculation()\n * })\n * }\n * ```\n *\n * @param {string} message\n * @param {function(...any):void} f\n * @return {number} Returns a promise that resolves the measured duration to apply f\n */\nexport const measureTime = (message, f) => {\n let duration\n const start = performance.now()\n try {\n f()\n } finally {\n duration = performance.now() - start\n log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`)\n }\n return duration\n}\n\n/**\n * Measure the time that it takes to calculate something.\n *\n * ```js\n * export const testMyFirstTest = async tc => {\n * t.measureTimeAsync('measurement', async () => {\n * await heavyCalculation()\n * })\n * await t.groupAsync('async measurement', async () => {\n * await heavyAsyncCalculation()\n * })\n * }\n * ```\n *\n * @param {string} message\n * @param {function(...any):Promise} f\n * @return {Promise} Returns a promise that resolves the measured duration to apply f\n */\nexport const measureTimeAsync = async (message, f) => {\n let duration\n const start = performance.now()\n try {\n await f()\n } finally {\n duration = performance.now() - start\n log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`)\n }\n return duration\n}\n\n/**\n * @template T\n * @param {Array} as\n * @param {Array} bs\n * @param {string} [m]\n * @return {boolean}\n */\nexport const compareArrays = (as, bs, m = 'Arrays match') => {\n if (as.length !== bs.length) {\n fail(m)\n }\n for (let i = 0; i < as.length; i++) {\n if (as[i] !== bs[i]) {\n fail(m)\n }\n }\n return true\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @param {string} [m]\n * @throws {TestError} Throws if tests fails\n */\nexport const compareStrings = (a, b, m = 'Strings match') => {\n if (a !== b) {\n const diff = simpleDiffString(a, b)\n log.print(log.GREY, a.slice(0, diff.index), log.RED, a.slice(diff.index, diff.remove), log.GREEN, diff.insert, log.GREY, a.slice(diff.index + diff.remove))\n fail(m)\n }\n}\n\n/**\n * @template K,V\n * @param {Object} a\n * @param {Object} b\n * @param {string} [m]\n * @throws {TestError} Throws if test fails\n */\nexport const compareObjects = (a, b, m = 'Objects match') => { object.equalFlat(a, b) || fail(m) }\n\n/**\n * @param {any} _constructor\n * @param {any} a\n * @param {any} b\n * @param {string} path\n * @throws {TestError}\n */\nconst compareValues = (_constructor, a, b, path) => {\n if (a !== b) {\n fail(`Values ${json.stringify(a)} and ${json.stringify(b)} don't match (${path})`)\n }\n return true\n}\n\n/**\n * @param {string?} message\n * @param {string} reason\n * @param {string} path\n * @throws {TestError}\n */\nconst _failMessage = (message, reason, path) => fail(\n message === null\n ? `${reason} ${path}`\n : `${message} (${reason}) ${path}`\n)\n\n/**\n * @param {any} a\n * @param {any} b\n * @param {string} path\n * @param {string?} message\n * @param {function(any,any,any,string,any):boolean} customCompare\n */\nconst _compare = (a, b, path, message, customCompare) => {\n // we don't use assert here because we want to test all branches (istanbul errors if one branch is not tested)\n if (a == null || b == null) {\n return compareValues(null, a, b, path)\n }\n if (a.constructor !== b.constructor) {\n _failMessage(message, 'Constructors don\\'t match', path)\n }\n let success = true\n switch (a.constructor) {\n case ArrayBuffer:\n a = new Uint8Array(a)\n b = new Uint8Array(b)\n // eslint-disable-next-line no-fallthrough\n case Uint8Array: {\n if (a.byteLength !== b.byteLength) {\n _failMessage(message, 'ArrayBuffer lengths match', path)\n }\n for (let i = 0; success && i < a.length; i++) {\n success = success && a[i] === b[i]\n }\n break\n }\n case Set: {\n if (a.size !== b.size) {\n _failMessage(message, 'Sets have different number of attributes', path)\n }\n // @ts-ignore\n a.forEach(value => {\n if (!b.has(value)) {\n _failMessage(message, `b.${path} does have ${value}`, path)\n }\n })\n break\n }\n case Map: {\n if (a.size !== b.size) {\n _failMessage(message, 'Maps have different number of attributes', path)\n }\n // @ts-ignore\n a.forEach((value, key) => {\n if (!b.has(key)) {\n _failMessage(message, `Property ${path}[\"${key}\"] does not exist on second argument`, path)\n }\n _compare(value, b.get(key), `${path}[\"${key}\"]`, message, customCompare)\n })\n break\n }\n case Object:\n if (object.length(a) !== object.length(b)) {\n _failMessage(message, 'Objects have a different number of attributes', path)\n }\n object.forEach(a, (value, key) => {\n if (!object.hasProperty(b, key)) {\n _failMessage(message, `Property ${path} does not exist on second argument`, path)\n }\n _compare(value, b[key], `${path}[\"${key}\"]`, message, customCompare)\n })\n break\n case Array:\n if (a.length !== b.length) {\n _failMessage(message, 'Arrays have a different number of attributes', path)\n }\n // @ts-ignore\n a.forEach((value, i) => _compare(value, b[i], `${path}[${i}]`, message, customCompare))\n break\n /* c8 ignore next 4 */\n default:\n if (!customCompare(a.constructor, a, b, path, compareValues)) {\n _failMessage(message, `Values ${json.stringify(a)} and ${json.stringify(b)} don't match`, path)\n }\n }\n assert(success, message)\n return true\n}\n\n/**\n * @template T\n * @param {T} a\n * @param {T} b\n * @param {string?} [message]\n * @param {function(any,T,T,string,any):boolean} [customCompare]\n */\nexport const compare = (a, b, message = null, customCompare = compareValues) => _compare(a, b, 'obj', message, customCompare)\n\n/**\n * @template T\n * @param {T} property\n * @param {string?} [message]\n * @return {asserts property is NonNullable}\n * @throws {TestError}\n */\n/* c8 ignore next */\nexport const assert = (property, message = null) => { property || fail(`Assertion failed${message !== null ? `: ${message}` : ''}`) }\n\n/**\n * @param {function(...any):Promise} f\n */\nexport const promiseRejected = async f => {\n try {\n await f()\n } catch (err) {\n return\n }\n fail('Expected promise to fail')\n}\n\n/**\n * @param {function(...any):void} f\n * @throws {TestError}\n */\nexport const fails = f => {\n try {\n f()\n } catch (_err) {\n log.print(log.GREEN, '⇖ This Error was expected')\n return\n }\n fail('Expected this to fail')\n}\n\n/**\n * @param {function(...any):Promise} f\n * @throws {TestError}\n */\nexport const failsAsync = async f => {\n try {\n await f()\n } catch (_err) {\n log.print(log.GREEN, '⇖ This Error was expected')\n return\n }\n fail('Expected this to fail')\n}\n\n/**\n * @param {Object>>} tests\n */\nexport const runTests = async tests => {\n /**\n * @param {string} testname\n */\n const filterTest = testname => testname.startsWith('test') || testname.startsWith('benchmark')\n const numberOfTests = object.map(tests, mod => object.map(mod, (f, fname) => /* c8 ignore next */ f && filterTest(fname) ? 1 : 0).reduce(math.add, 0)).reduce(math.add, 0)\n let successfulTests = 0\n let testnumber = 0\n const start = performance.now()\n for (const modName in tests) {\n const mod = tests[modName]\n for (const fname in mod) {\n const f = mod[fname]\n /* c8 ignore else */\n if (f && filterTest(fname)) {\n const repeatEachTest = 1\n let success = true\n for (let i = 0; success && i < repeatEachTest; i++) {\n success = await run(modName, fname, f, testnumber, numberOfTests)\n }\n testnumber++\n /* c8 ignore else */\n if (success) {\n successfulTests++\n }\n }\n }\n }\n const end = performance.now()\n log.print('')\n const success = successfulTests === numberOfTests\n /* c8 ignore start */\n if (success) {\n log.print(log.GREEN, log.BOLD, 'All tests successful!', log.GREY, log.UNBOLD, ` in ${time.humanizeDuration(end - start)}`)\n log.printImgBase64(nyanCatImage, 50)\n } else {\n const failedTests = numberOfTests - successfulTests\n log.print(log.RED, log.BOLD, `> ${failedTests} test${failedTests > 1 ? 's' : ''} failed`)\n }\n /* c8 ignore stop */\n return success\n}\n\nclass TestError extends Error {}\n\n/**\n * @param {string} reason\n * @throws {TestError}\n */\nexport const fail = reason => {\n log.print(log.RED, log.BOLD, 'X ', log.UNBOLD, reason)\n throw new TestError('Test Failed')\n}\n\nclass SkipError extends Error {}\n\n/**\n * @param {boolean} cond If true, this tests will be skipped\n * @throws {SkipError}\n */\nexport const skip = (cond = true) => {\n if (cond) {\n throw new SkipError('skipping..')\n }\n}\n\n// eslint-disable-next-line\nconst nyanCatImage = 'R0lGODlhjABMAPcAAMiSE0xMTEzMzUKJzjQ0NFsoKPc7//FM/9mH/z9x0HIiIoKCgmBHN+frGSkZLdDQ0LCwsDk71g0KCUzDdrQQEOFz/8yYdelmBdTiHFxcXDU2erR/mLrTHCgoKK5szBQUFNgSCTk6ymfpCB9VZS2Bl+cGBt2N8kWm0uDcGXhZRUvGq94NCFPhDiwsLGVlZTgqIPMDA1g3aEzS5D6xAURERDtG9JmBjJsZGWs2AD1W6Hp6eswyDeJ4CFNTU1LcEoJRmTMzSd14CTg5ser2GmDzBd17/xkZGUzMvoSMDiEhIfKruCwNAJaWlvRzA8kNDXDrCfi0pe1U/+GS6SZrAB4eHpZwVhoabsx9oiYmJt/TGHFxcYyMjOid0+Zl/0rF6j09PeRr/0zU9DxO6j+z0lXtBtp8qJhMAEssLGhoaPL/GVn/AAsWJ/9/AE3Z/zs9/3cAAOlf/+aa2RIyADo85uhh/0i84WtrazQ0UyMlmDMzPwUFBe16BTMmHau0E03X+g8pMEAoS1MBAf++kkzO8pBaqSZoe9uB/zE0BUQ3Sv///4WFheuiyzo880gzNDIyNissBNqF/8RiAOF2qG5ubj0vL1z6Avl5ASsgGkgUSy8vL/8n/z4zJy8lOv96uEssV1csAN5ZCDQ0Wz1a3tbEGHLeDdYKCg4PATE7PiMVFSoqU83eHEi43gUPAOZ8reGogeKU5dBBC8faHEez2lHYF4bQFMukFtl4CzY3kkzBVJfMGZkAAMfSFf27mP0t//g4/9R6Dfsy/1DRIU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zknos51shOc7oynPOdJz3ra857hDAgAOw=='\n"],"names":["env.hasConf","env.hasParam","env.getParam","random.uint32","prng.create","string.fromCamelCase","log","performance","promise.isPromise","env.isBrowser","time.humanizeDuration","array.last","statistics.median","statistics.average","diff","simpleDiffString","object.equalFlat","json.stringify","object.length","object.forEach","object.hasProperty","object.map","math.add"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAkBA;AACY,MAAC,SAAS,GAAGA,mBAAW,CAAC,WAAW,EAAC;AACjD;AACA;AACY,MAAC,OAAO,GAAGC,oBAAY,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,QAAQ,CAACC,oBAAY,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,GAAG,KAAI;AACnG;AACO,MAAM,QAAQ,CAAC;AACtB;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE;AACrC;AACA;AACA;AACA,IAAI,IAAI,CAAC,UAAU,GAAG,WAAU;AAChC;AACA;AACA;AACA,IAAI,IAAI,CAAC,QAAQ,GAAG,SAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,GAAE;AACzB,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB,GAAG;AACH;AACA,EAAE,SAAS,CAAC,GAAG;AACf,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB,GAAG;AACH;AAC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BAAuB,EAAEA,cAAG,CAAC,IAAI,EAAEA,cAAG,CAAC,MAAM,EAAE,CAAC,IAAI,EAAEI,qBAAqB,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,EAAC;AAC9H,IAAIJ,cAAG,CAAC,cAAc,CAAC,YAAY,EAAE,EAAE,EAAC;AACxC,GAAG,MAAM;AACT,IAAI,MAAM,WAAW,GAAG,aAAa,GAAG,gBAAe;AACvD,IAAIA,cAAG,CAAC,KAAK,CAACA,cAAG,CAAC,GAAG,EAAEA,cAAG,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,WAAW,CAAC,KAAK,EAAE,WAAW,GAAG,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,EAAC;AAC7F,GAAG;AACH;AACA,EAAE,OAAO,OAAO;AAChB,EAAC;AACD;AACA,MAAM,SAAS,SAAS,KAAK,CAAC,EAAE;AAChC;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,MAAM,IAAI;AAC9B,EAAEA,cAAG,CAAC,KAAK,CAACA,cAAG,CAAC,GAAG,EAAEA,cAAG,CAAC,IAAI,EAAE,IAAI,EAAEA,cAAG,CAAC,MAAM,EAAE,MAAM,EAAC;AACxD,EAAE,MAAM,IAAI,SAAS,CAAC,aAAa,CAAC;AACpC,EAAC;AACD;AACA,MAAM,SAAS,SAAS,KAAK,CAAC,EAAE;AAChC;AACA;AACA;AACA;AACA;AACY,MAAC,IAAI,GAAG,CAAC,IAAI,GAAG,IAAI,KAAK;AACrC,EAAE,IAAI,IAAI,EAAE;AACZ,IAAI,MAAM,IAAI,SAAS,CAAC,YAAY,CAAC;AACrC,GAAG;AACH,EAAC;AACD;AACA;AACA,MAAM,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/testing.d.ts b/nodejs/node_modules/lib0/dist/testing.d.ts new file mode 100644 index 00000000..bb1d701f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/testing.d.ts @@ -0,0 +1,64 @@ +export { production } from "./environment.js"; +export const extensive: boolean; +export const envSeed: number | null; +export class TestCase { + /** + * @param {string} moduleName + * @param {string} testName + */ + constructor(moduleName: string, testName: string); + /** + * @type {string} + */ + moduleName: string; + /** + * @type {string} + */ + testName: string; + /** + * This type can store custom information related to the TestCase + * + * @type {Map} + */ + meta: Map; + _seed: number | null; + _prng: prng.PRNG | null; + resetSeed(): void; + /** + * @type {number} + */ + get seed(): number; + /** + * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible. + * + * @type {prng.PRNG} + */ + get prng(): prng.PRNG; +} +export const repetitionTime: number; +export function run(moduleName: string, name: string, f: (arg0: TestCase) => void | Promise, i: number, numberOfTests: number): Promise; +export function describe(description: string, info?: string): void; +export function info(info: string): void; +export const printDom: (_createNode: () => Node) => void; +export const printCanvas: (canvas: HTMLCanvasElement, height: number) => void; +export function group(description: string, f: (...args: any[]) => void): void; +export function groupAsync(description: string, f: (...args: any[]) => Promise): Promise; +export function measureTime(message: string, f: (...args: any[]) => void): number; +export function measureTimeAsync(message: string, f: (...args: any[]) => Promise): Promise; +export function compareArrays(as: T[], bs: T[], m?: string | undefined): boolean; +export function compareStrings(a: string, b: string, m?: string | undefined): void; +export function compareObjects(a: any, b: any, m?: string | undefined): void; +export function compare(a: T, b: T, message?: string | null | undefined, customCompare?: ((arg0: any, arg1: T, arg2: T, arg3: string, arg4: any) => boolean) | undefined): boolean; +export function assert(property: T, message?: string | null | undefined): asserts property is NonNullable; +export function promiseRejected(f: (...args: any[]) => Promise): Promise; +export function fails(f: (...args: any[]) => void): void; +export function failsAsync(f: (...args: any[]) => Promise): Promise; +export function runTests(tests: { + [x: string]: { + [x: string]: (arg0: TestCase) => void | Promise; + }; +}): Promise; +export function fail(reason: string): never; +export function skip(cond?: boolean): void; +import * as prng from './prng.js'; +//# sourceMappingURL=testing.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/testing.d.ts.map b/nodejs/node_modules/lib0/dist/testing.d.ts.map new file mode 100644 index 00000000..b29ea7ee --- /dev/null +++ b/nodejs/node_modules/lib0/dist/testing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../testing.js"],"names":[],"mappings":";AA8DA,gCAAiD;AAGjD,oCAAmG;AAEnG;IACE;;;OAGG;IACH,wBAHW,MAAM,YACN,MAAM,EAmBhB;IAhBC;;OAEG;IACH,YAFU,MAAM,CAEY;IAC5B;;OAEG;IACH,UAFU,MAAM,CAEQ;IACxB;;;;OAIG;IACH,MAFU,IAAI,MAAM,EAAC,GAAG,CAAC,CAEJ;IACrB,qBAAiB;IACjB,wBAAiB;IAGnB,kBAGC;IAED;;OAEG;IAEH,mBAOC;IAED;;;;OAIG;IACH,sBAMC;CACF;AAED,oCAA6E;AAgBtE,gCANI,MAAM,QACN,MAAM,YACG,QAAQ,KAAE,IAAI,GAAC,QAAQ,GAAG,CAAC,KACpC,MAAM,iBACN,MAAM,oBA0EhB;AAcM,sCAHI,MAAM,SACN,MAAM,QAEwF;AAYlG,2BAFI,MAAM,QAE6B;AAE9C,yDAAoC;AAEpC,8EAA0C;AAoBnC,mCAHI,MAAM,eACM,GAAG,OAAE,IAAI,QAS/B;AAoBM,wCAHI,MAAM,eACM,GAAG,OAAE,QAAQ,GAAG,CAAC,iBASvC;AAoBM,qCAJI,MAAM,eACM,GAAG,OAAE,IAAI,GACpB,MAAM,CAYjB;AAoBM,0CAJI,MAAM,eACM,GAAG,OAAE,QAAQ,GAAG,CAAC,GAC5B,QAAQ,MAAM,CAAC,CAY1B;AASM,4EAFK,OAAO,CAYlB;AAQM,kCALI,MAAM,KACN,MAAM,gCAUhB;AASM,mFAA2F;AAsH3F,oGAFa,GAAG,0BAAK,MAAM,QAAC,GAAG,KAAE,OAAO,wBAE8E;AAUtH,gHAA8H;AAK9H,6CAFgB,GAAG,OAAE,QAAQ,GAAG,CAAC,iBASvC;AAMM,mCAHgB,GAAG,OAAE,IAAI,QAW/B;AAMM,wCAHgB,GAAG,OAAE,QAAQ,GAAG,CAAC,iBAWvC;AAKM;QAFW,MAAM;YAAS,MAAM,UAAW,QAAQ,KAAE,IAAI,GAAC,QAAQ,GAAG,CAAC;;qBA2C5E;AAQM,6BAHI,MAAM,SAMhB;AAQM,4BAHI,OAAO,QAOjB;sBAvkBqB,WAAW"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/testing.test.d.ts b/nodejs/node_modules/lib0/dist/testing.test.d.ts new file mode 100644 index 00000000..9007956f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/testing.test.d.ts @@ -0,0 +1,9 @@ +export function nottestingNotTested(): void; +export function testAssertTyping(): void; +export function testComparing(_tc: t.TestCase): void; +export function testFailing(): Promise; +export function testSkipping(): void; +export function testAsync(): Promise; +export function testRepeatRepetition(): void; +import * as t from './testing.js'; +//# sourceMappingURL=testing.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/testing.test.d.ts.map b/nodejs/node_modules/lib0/dist/testing.test.d.ts.map new file mode 100644 index 00000000..72394099 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/testing.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"testing.test.d.ts","sourceRoot":"","sources":["../testing.test.js"],"names":[],"mappings":"AAQO,4CAEN;AAEM,yCAMN;AAKM,mCAFI,EAAE,QAAQ,QA+FpB;AAEM,6CAcN;AAEM,qCAMN;AAEM,2CAIN;AAEM,6CAON;mBA3JkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/time-bc2081b9.cjs b/nodejs/node_modules/lib0/dist/time-bc2081b9.cjs new file mode 100644 index 00000000..f3260b35 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time-bc2081b9.cjs @@ -0,0 +1,63 @@ +'use strict'; + +var metric = require('./metric.cjs'); +var math = require('./math-08e068f9.cjs'); + +/** + * Utility module to work with time. + * + * @module time + */ + +/** + * Return current time. + * + * @return {Date} + */ +const getDate = () => new Date(); + +/** + * Return current unix time. + * + * @return {number} + */ +const getUnixTime = Date.now; + +/** + * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs. + * + * @param {number} d duration in milliseconds + * @return {string} humanized approximation of time + */ +const humanizeDuration = d => { + if (d < 60000) { + const p = metric.prefix(d, -1); + return math.round(p.n * 100) / 100 + p.prefix + 's' + } + d = math.floor(d / 1000); + const seconds = d % 60; + const minutes = math.floor(d / 60) % 60; + const hours = math.floor(d / 3600) % 24; + const days = math.floor(d / 86400); + if (days > 0) { + return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '') + } + if (hours > 0) { + /* c8 ignore next */ + return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '') + } + return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '') +}; + +var time = /*#__PURE__*/Object.freeze({ + __proto__: null, + getDate: getDate, + getUnixTime: getUnixTime, + humanizeDuration: humanizeDuration +}); + +exports.getDate = getDate; +exports.getUnixTime = getUnixTime; +exports.humanizeDuration = humanizeDuration; +exports.time = time; +//# sourceMappingURL=time-bc2081b9.cjs.map diff --git a/nodejs/node_modules/lib0/dist/time-bc2081b9.cjs.map b/nodejs/node_modules/lib0/dist/time-bc2081b9.cjs.map new file mode 100644 index 00000000..44bbfa1e --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time-bc2081b9.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"time-bc2081b9.cjs","sources":["../time.js"],"sourcesContent":["/**\n * Utility module to work with time.\n *\n * @module time\n */\n\nimport * as metric from './metric.js'\nimport * as math from './math.js'\n\n/**\n * Return current time.\n *\n * @return {Date}\n */\nexport const getDate = () => new Date()\n\n/**\n * Return current unix time.\n *\n * @return {number}\n */\nexport const getUnixTime = Date.now\n\n/**\n * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs.\n *\n * @param {number} d duration in milliseconds\n * @return {string} humanized approximation of time\n */\nexport const humanizeDuration = d => {\n if (d < 60000) {\n const p = metric.prefix(d, -1)\n return math.round(p.n * 100) / 100 + p.prefix + 's'\n }\n d = math.floor(d / 1000)\n const seconds = d % 60\n const minutes = math.floor(d / 60) % 60\n const hours = math.floor(d / 3600) % 24\n const days = math.floor(d / 86400)\n if (days > 0) {\n return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '')\n }\n if (hours > 0) {\n /* c8 ignore next */\n return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '')\n }\n return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '')\n}\n"],"names":["metric.prefix","math.round","math.floor"],"mappings":";;;;;AAAA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,OAAO,GAAG,MAAM,IAAI,IAAI,GAAE;AACvC;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,WAAW,GAAG,IAAI,CAAC,IAAG;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,gBAAgB,GAAG,CAAC,IAAI;AACrC,EAAE,IAAI,CAAC,GAAG,KAAK,EAAE;AACjB,IAAI,MAAM,CAAC,GAAGA,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,EAAC;AAClC,IAAI,OAAOC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,MAAM,GAAG,GAAG;AACvD,GAAG;AACH,EAAE,CAAC,GAAGC,UAAU,CAAC,CAAC,GAAG,IAAI,EAAC;AAC1B,EAAE,MAAM,OAAO,GAAG,CAAC,GAAG,GAAE;AACxB,EAAE,MAAM,OAAO,GAAGA,UAAU,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,GAAE;AACzC,EAAE,MAAM,KAAK,GAAGA,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,GAAE;AACzC,EAAE,MAAM,IAAI,GAAGA,UAAU,CAAC,CAAC,GAAG,KAAK,EAAC;AACpC,EAAE,IAAI,IAAI,GAAG,CAAC,EAAE;AAChB,IAAI,OAAO,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,OAAO,GAAG,EAAE,IAAI,GAAG,IAAI,OAAO,GAAG,EAAE,GAAG,KAAK,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC;AAC3G,GAAG;AACH,EAAE,IAAI,KAAK,GAAG,CAAC,EAAE;AACjB;AACA,IAAI,OAAO,KAAK,GAAG,GAAG,IAAI,CAAC,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,EAAE,IAAI,GAAG,IAAI,OAAO,GAAG,EAAE,GAAG,OAAO,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,KAAK,GAAG,EAAE,CAAC;AACpH,GAAG;AACH,EAAE,OAAO,OAAO,GAAG,KAAK,IAAI,OAAO,GAAG,CAAC,GAAG,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,EAAE,CAAC;AACnE;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/time.cjs b/nodejs/node_modules/lib0/dist/time.cjs new file mode 100644 index 00000000..9186e694 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time.cjs @@ -0,0 +1,14 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./metric.cjs'); +require('./math-08e068f9.cjs'); +var time = require('./time-bc2081b9.cjs'); + + + +exports.getDate = time.getDate; +exports.getUnixTime = time.getUnixTime; +exports.humanizeDuration = time.humanizeDuration; +//# sourceMappingURL=time.cjs.map diff --git a/nodejs/node_modules/lib0/dist/time.cjs.map b/nodejs/node_modules/lib0/dist/time.cjs.map new file mode 100644 index 00000000..d5d354aa --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"time.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/time.d.ts b/nodejs/node_modules/lib0/dist/time.d.ts new file mode 100644 index 00000000..5ee1371b --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time.d.ts @@ -0,0 +1,9 @@ +export function getDate(): Date; +/** + * Return current unix time. + * + * @return {number} + */ +export const getUnixTime: () => number; +export function humanizeDuration(d: number): string; +//# sourceMappingURL=time.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/time.d.ts.map b/nodejs/node_modules/lib0/dist/time.d.ts.map new file mode 100644 index 00000000..6d259242 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../time.js"],"names":[],"mappings":"AAcO,2BAFK,IAAI,CAEuB;AAEvC;;;;GAIG;AACH,uCAAmC;AAQ5B,oCAHI,MAAM,GACL,MAAM,CAoBjB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/time.test.d.ts b/nodejs/node_modules/lib0/dist/time.test.d.ts new file mode 100644 index 00000000..614187b2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time.test.d.ts @@ -0,0 +1,4 @@ +export function testTime(tc: t.TestCase): void; +export function testHumanDuration(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=time.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/time.test.d.ts.map b/nodejs/node_modules/lib0/dist/time.test.d.ts.map new file mode 100644 index 00000000..2d8bd5fe --- /dev/null +++ b/nodejs/node_modules/lib0/dist/time.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"time.test.d.ts","sourceRoot":"","sources":["../time.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QAMpB;AAKM,sCAFI,EAAE,QAAQ,QAmBpB;mBAhCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/tree-9f3c8837.cjs b/nodejs/node_modules/lib0/dist/tree-9f3c8837.cjs new file mode 100644 index 00000000..5a2cfcca --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree-9f3c8837.cjs @@ -0,0 +1,557 @@ +'use strict'; + +/** + * Red-black-tree implementation. + * + * @module tree + */ +// @ts-nocheck TODO: remove or refactor this file + +const rotate = (tree, parent, newParent, n) => { + if (parent === null) { + tree.root = newParent; + newParent._parent = null; + } else if (parent.left === n) { + parent.left = newParent; + } else if (parent.right === n) { + parent.right = newParent; + } else { + throw new Error('The elements are wrongly connected!') + } +}; + +/** + * @template V + */ +class N { + /** + * A created node is always red! + * + * @param {V} val + */ + constructor (val) { + this.val = val; + this.color = true; + this._left = null; + this._right = null; + this._parent = null; + } + + isRed () { return this.color } + isBlack () { return !this.color } + redden () { this.color = true; return this } + blacken () { this.color = false; return this } + get grandparent () { + return this.parent.parent + } + + get parent () { + return this._parent + } + + get sibling () { + return (this === this.parent.left) + ? this.parent.right + : this.parent.left + } + + get left () { + return this._left + } + + get right () { + return this._right + } + + set left (n) { + if (n !== null) { + n._parent = this; + } + this._left = n; + } + + set right (n) { + if (n !== null) { + n._parent = this; + } + this._right = n; + } + + rotateLeft (tree) { + const parent = this.parent; + const newParent = this.right; + const newRight = this.right.left; + newParent.left = this; + this.right = newRight; + rotate(tree, parent, newParent, this); + } + + next () { + if (this.right !== null) { + // search the most left node in the right tree + let o = this.right; + while (o.left !== null) { + o = o.left; + } + return o + } else { + let p = this; + while (p.parent !== null && p !== p.parent.left) { + p = p.parent; + } + return p.parent + } + } + + prev () { + if (this.left !== null) { + // search the most right node in the left tree + let o = this.left; + while (o.right !== null) { + o = o.right; + } + return o + } else { + let p = this; + while (p.parent !== null && p !== p.parent.right) { + p = p.parent; + } + return p.parent + } + } + + rotateRight (tree) { + const parent = this.parent; + const newParent = this.left; + const newLeft = this.left.right; + newParent.right = this; + this.left = newLeft; + rotate(tree, parent, newParent, this); + } + + getUncle () { + // we can assume that grandparent exists when this is called! + if (this.parent === this.parent.parent.left) { + return this.parent.parent.right + } else { + return this.parent.parent.left + } + } +} + +const isBlack = node => + node !== null ? node.isBlack() : true; + +const isRed = (node) => + node !== null ? node.isRed() : false; + +/** + * This is a Red Black Tree implementation + * + * @template K,V + */ +class Tree { + constructor () { + this.root = null; + this.length = 0; + } + + /** + * @param {K} id + */ + findNext (id) { + const nextID = id.clone(); + nextID.clock += 1; + return this.findWithLowerBound(nextID) + } + + /** + * @param {K} id + */ + findPrev (id) { + const prevID = id.clone(); + prevID.clock -= 1; + return this.findWithUpperBound(prevID) + } + + /** + * @param {K} from + */ + findNodeWithLowerBound (from) { + let o = this.root; + if (o === null) { + return null + } else { + while (true) { + if (from === null || (from.lessThan(o.val._id) && o.left !== null)) { + // o is included in the bound + // try to find an element that is closer to the bound + o = o.left; + } else if (from !== null && o.val._id.lessThan(from)) { + // o is not within the bound, maybe one of the right elements is.. + if (o.right !== null) { + o = o.right; + } else { + // there is no right element. Search for the next bigger element, + // this should be within the bounds + return o.next() + } + } else { + return o + } + } + } + } + + /** + * @param {K} to + */ + findNodeWithUpperBound (to) { + if (to === undefined) { + throw new Error('You must define from!') + } + let o = this.root; + if (o === null) { + return null + } else { + while (true) { + if ((to === null || o.val._id.lessThan(to)) && o.right !== null) { + // o is included in the bound + // try to find an element that is closer to the bound + o = o.right; + } else if (to !== null && to.lessThan(o.val._id)) { + // o is not within the bound, maybe one of the left elements is.. + if (o.left !== null) { + o = o.left; + } else { + // there is no left element. Search for the prev smaller element, + // this should be within the bounds + return o.prev() + } + } else { + return o + } + } + } + } + + /** + * @return {V} + */ + findSmallestNode () { + let o = this.root; + while (o != null && o.left != null) { + o = o.left; + } + return o + } + + /** + * @param {K} from + * @return {V} + */ + findWithLowerBound (from) { + const n = this.findNodeWithLowerBound(from); + return n == null ? null : n.val + } + + /** + * @param {K} to + * @return {V} + */ + findWithUpperBound (to) { + const n = this.findNodeWithUpperBound(to); + return n == null ? null : n.val + } + + /** + * @param {K} from + * @param {V} from + * @param {function(V):void} f + */ + iterate (from, to, f) { + let o; + if (from === null) { + o = this.findSmallestNode(); + } else { + o = this.findNodeWithLowerBound(from); + } + while ( + o !== null && + ( + to === null || // eslint-disable-line no-unmodified-loop-condition + o.val._id.lessThan(to) || + o.val._id.equals(to) + ) + ) { + f(o.val); + o = o.next(); + } + } + + /** + * @param {K} id + * @return {V|null} + */ + find (id) { + const n = this.findNode(id); + if (n !== null) { + return n.val + } else { + return null + } + } + + /** + * @param {K} id + * @return {N|null} + */ + findNode (id) { + let o = this.root; + if (o === null) { + return null + } else { + while (true) { + if (o === null) { + return null + } + if (id.lessThan(o.val._id)) { + o = o.left; + } else if (o.val._id.lessThan(id)) { + o = o.right; + } else { + return o + } + } + } + } + + /** + * @param {K} id + */ + delete (id) { + let d = this.findNode(id); + if (d == null) { + // throw new Error('Element does not exist!') + return + } + this.length--; + if (d.left !== null && d.right !== null) { + // switch d with the greates element in the left subtree. + // o should have at most one child. + let o = d.left; + // find + while (o.right !== null) { + o = o.right; + } + // switch + d.val = o.val; + d = o; + } + // d has at most one child + // let n be the node that replaces d + let isFakeChild; + let child = d.left || d.right; + if (child === null) { + isFakeChild = true; + child = new N(null); + child.blacken(); + d.right = child; + } else { + isFakeChild = false; + } + + if (d.parent === null) { + if (!isFakeChild) { + this.root = child; + child.blacken(); + child._parent = null; + } else { + this.root = null; + } + return + } else if (d.parent.left === d) { + d.parent.left = child; + } else if (d.parent.right === d) { + d.parent.right = child; + } else { + throw new Error('Impossible!') + } + if (d.isBlack()) { + if (child.isRed()) { + child.blacken(); + } else { + this._fixDelete(child); + } + } + this.root.blacken(); + if (isFakeChild) { + if (child.parent.left === child) { + child.parent.left = null; + } else if (child.parent.right === child) { + child.parent.right = null; + } else { + throw new Error('Impossible #3') + } + } + } + + _fixDelete (n) { + if (n.parent === null) { + // this can only be called after the first iteration of fixDelete. + return + } + // d was already replaced by the child + // d is not the root + // d and child are black + let sibling = n.sibling; + if (isRed(sibling)) { + // make sibling the grandfather + n.parent.redden(); + sibling.blacken(); + if (n === n.parent.left) { + n.parent.rotateLeft(this); + } else if (n === n.parent.right) { + n.parent.rotateRight(this); + } else { + throw new Error('Impossible #2') + } + sibling = n.sibling; + } + // parent, sibling, and children of n are black + if (n.parent.isBlack() && + sibling.isBlack() && + isBlack(sibling.left) && + isBlack(sibling.right) + ) { + sibling.redden(); + this._fixDelete(n.parent); + } else if (n.parent.isRed() && + sibling.isBlack() && + isBlack(sibling.left) && + isBlack(sibling.right) + ) { + sibling.redden(); + n.parent.blacken(); + } else { + if (n === n.parent.left && + sibling.isBlack() && + isRed(sibling.left) && + isBlack(sibling.right) + ) { + sibling.redden(); + sibling.left.blacken(); + sibling.rotateRight(this); + sibling = n.sibling; + } else if (n === n.parent.right && + sibling.isBlack() && + isRed(sibling.right) && + isBlack(sibling.left) + ) { + sibling.redden(); + sibling.right.blacken(); + sibling.rotateLeft(this); + sibling = n.sibling; + } + sibling.color = n.parent.color; + n.parent.blacken(); + if (n === n.parent.left) { + sibling.right.blacken(); + n.parent.rotateLeft(this); + } else { + sibling.left.blacken(); + n.parent.rotateRight(this); + } + } + } + + put (v) { + const node = new N(v); + if (this.root !== null) { + let p = this.root; // p abbrev. parent + while (true) { + if (node.val._id.lessThan(p.val._id)) { + if (p.left === null) { + p.left = node; + break + } else { + p = p.left; + } + } else if (p.val._id.lessThan(node.val._id)) { + if (p.right === null) { + p.right = node; + break + } else { + p = p.right; + } + } else { + p.val = node.val; + return p + } + } + this._fixInsert(node); + } else { + this.root = node; + } + this.length++; + this.root.blacken(); + return node + } + + _fixInsert (n) { + if (n.parent === null) { + n.blacken(); + return + } else if (n.parent.isBlack()) { + return + } + const uncle = n.getUncle(); + if (uncle !== null && uncle.isRed()) { + // Note: parent: red, uncle: red + n.parent.blacken(); + uncle.blacken(); + n.grandparent.redden(); + this._fixInsert(n.grandparent); + } else { + // Note: parent: red, uncle: black or null + // Now we transform the tree in such a way that + // either of these holds: + // 1) grandparent.left.isRed + // and grandparent.left.left.isRed + // 2) grandparent.right.isRed + // and grandparent.right.right.isRed + if (n === n.parent.right && n.parent === n.grandparent.left) { + n.parent.rotateLeft(this); + // Since we rotated and want to use the previous + // cases, we need to set n in such a way that + // n.parent.isRed again + n = n.left; + } else if (n === n.parent.left && n.parent === n.grandparent.right) { + n.parent.rotateRight(this); + // see above + n = n.right; + } + // Case 1) or 2) hold from here on. + // Now traverse grandparent, make parent a black node + // on the highest level which holds two red nodes. + n.parent.blacken(); + n.grandparent.redden(); + if (n === n.parent.left) { + // Case 1 + n.grandparent.rotateRight(this); + } else { + // Case 2 + n.grandparent.rotateLeft(this); + } + } + } +} + +var tree = /*#__PURE__*/Object.freeze({ + __proto__: null, + Tree: Tree +}); + +exports.Tree = Tree; +exports.tree = tree; +//# sourceMappingURL=tree-9f3c8837.cjs.map diff --git a/nodejs/node_modules/lib0/dist/tree-9f3c8837.cjs.map b/nodejs/node_modules/lib0/dist/tree-9f3c8837.cjs.map new file mode 100644 index 00000000..04a1538f --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree-9f3c8837.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"tree-9f3c8837.cjs","sources":["../tree.js"],"sourcesContent":["/**\n * Red-black-tree implementation.\n *\n * @module tree\n */\n// @ts-nocheck TODO: remove or refactor this file\n\nconst rotate = (tree, parent, newParent, n) => {\n if (parent === null) {\n tree.root = newParent\n newParent._parent = null\n } else if (parent.left === n) {\n parent.left = newParent\n } else if (parent.right === n) {\n parent.right = newParent\n } else {\n throw new Error('The elements are wrongly connected!')\n }\n}\n\n/**\n * @template V\n */\nclass N {\n /**\n * A created node is always red!\n *\n * @param {V} val\n */\n constructor (val) {\n this.val = val\n this.color = true\n this._left = null\n this._right = null\n this._parent = null\n }\n\n isRed () { return this.color }\n isBlack () { return !this.color }\n redden () { this.color = true; return this }\n blacken () { this.color = false; return this }\n get grandparent () {\n return this.parent.parent\n }\n\n get parent () {\n return this._parent\n }\n\n get sibling () {\n return (this === this.parent.left)\n ? this.parent.right\n : this.parent.left\n }\n\n get left () {\n return this._left\n }\n\n get right () {\n return this._right\n }\n\n set left (n) {\n if (n !== null) {\n n._parent = this\n }\n this._left = n\n }\n\n set right (n) {\n if (n !== null) {\n n._parent = this\n }\n this._right = n\n }\n\n rotateLeft (tree) {\n const parent = this.parent\n const newParent = this.right\n const newRight = this.right.left\n newParent.left = this\n this.right = newRight\n rotate(tree, parent, newParent, this)\n }\n\n next () {\n if (this.right !== null) {\n // search the most left node in the right tree\n let o = this.right\n while (o.left !== null) {\n o = o.left\n }\n return o\n } else {\n let p = this\n while (p.parent !== null && p !== p.parent.left) {\n p = p.parent\n }\n return p.parent\n }\n }\n\n prev () {\n if (this.left !== null) {\n // search the most right node in the left tree\n let o = this.left\n while (o.right !== null) {\n o = o.right\n }\n return o\n } else {\n let p = this\n while (p.parent !== null && p !== p.parent.right) {\n p = p.parent\n }\n return p.parent\n }\n }\n\n rotateRight (tree) {\n const parent = this.parent\n const newParent = this.left\n const newLeft = this.left.right\n newParent.right = this\n this.left = newLeft\n rotate(tree, parent, newParent, this)\n }\n\n getUncle () {\n // we can assume that grandparent exists when this is called!\n if (this.parent === this.parent.parent.left) {\n return this.parent.parent.right\n } else {\n return this.parent.parent.left\n }\n }\n}\n\nconst isBlack = node =>\n node !== null ? node.isBlack() : true\n\nconst isRed = (node) =>\n node !== null ? node.isRed() : false\n\n/**\n * This is a Red Black Tree implementation\n *\n * @template K,V\n */\nexport class Tree {\n constructor () {\n this.root = null\n this.length = 0\n }\n\n /**\n * @param {K} id\n */\n findNext (id) {\n const nextID = id.clone()\n nextID.clock += 1\n return this.findWithLowerBound(nextID)\n }\n\n /**\n * @param {K} id\n */\n findPrev (id) {\n const prevID = id.clone()\n prevID.clock -= 1\n return this.findWithUpperBound(prevID)\n }\n\n /**\n * @param {K} from\n */\n findNodeWithLowerBound (from) {\n let o = this.root\n if (o === null) {\n return null\n } else {\n while (true) {\n if (from === null || (from.lessThan(o.val._id) && o.left !== null)) {\n // o is included in the bound\n // try to find an element that is closer to the bound\n o = o.left\n } else if (from !== null && o.val._id.lessThan(from)) {\n // o is not within the bound, maybe one of the right elements is..\n if (o.right !== null) {\n o = o.right\n } else {\n // there is no right element. Search for the next bigger element,\n // this should be within the bounds\n return o.next()\n }\n } else {\n return o\n }\n }\n }\n }\n\n /**\n * @param {K} to\n */\n findNodeWithUpperBound (to) {\n if (to === undefined) {\n throw new Error('You must define from!')\n }\n let o = this.root\n if (o === null) {\n return null\n } else {\n while (true) {\n if ((to === null || o.val._id.lessThan(to)) && o.right !== null) {\n // o is included in the bound\n // try to find an element that is closer to the bound\n o = o.right\n } else if (to !== null && to.lessThan(o.val._id)) {\n // o is not within the bound, maybe one of the left elements is..\n if (o.left !== null) {\n o = o.left\n } else {\n // there is no left element. Search for the prev smaller element,\n // this should be within the bounds\n return o.prev()\n }\n } else {\n return o\n }\n }\n }\n }\n\n /**\n * @return {V}\n */\n findSmallestNode () {\n let o = this.root\n while (o != null && o.left != null) {\n o = o.left\n }\n return o\n }\n\n /**\n * @param {K} from\n * @return {V}\n */\n findWithLowerBound (from) {\n const n = this.findNodeWithLowerBound(from)\n return n == null ? null : n.val\n }\n\n /**\n * @param {K} to\n * @return {V}\n */\n findWithUpperBound (to) {\n const n = this.findNodeWithUpperBound(to)\n return n == null ? null : n.val\n }\n\n /**\n * @param {K} from\n * @param {V} from\n * @param {function(V):void} f\n */\n iterate (from, to, f) {\n let o\n if (from === null) {\n o = this.findSmallestNode()\n } else {\n o = this.findNodeWithLowerBound(from)\n }\n while (\n o !== null &&\n (\n to === null || // eslint-disable-line no-unmodified-loop-condition\n o.val._id.lessThan(to) ||\n o.val._id.equals(to)\n )\n ) {\n f(o.val)\n o = o.next()\n }\n }\n\n /**\n * @param {K} id\n * @return {V|null}\n */\n find (id) {\n const n = this.findNode(id)\n if (n !== null) {\n return n.val\n } else {\n return null\n }\n }\n\n /**\n * @param {K} id\n * @return {N|null}\n */\n findNode (id) {\n let o = this.root\n if (o === null) {\n return null\n } else {\n while (true) {\n if (o === null) {\n return null\n }\n if (id.lessThan(o.val._id)) {\n o = o.left\n } else if (o.val._id.lessThan(id)) {\n o = o.right\n } else {\n return o\n }\n }\n }\n }\n\n /**\n * @param {K} id\n */\n delete (id) {\n let d = this.findNode(id)\n if (d == null) {\n // throw new Error('Element does not exist!')\n return\n }\n this.length--\n if (d.left !== null && d.right !== null) {\n // switch d with the greates element in the left subtree.\n // o should have at most one child.\n let o = d.left\n // find\n while (o.right !== null) {\n o = o.right\n }\n // switch\n d.val = o.val\n d = o\n }\n // d has at most one child\n // let n be the node that replaces d\n let isFakeChild\n let child = d.left || d.right\n if (child === null) {\n isFakeChild = true\n child = new N(null)\n child.blacken()\n d.right = child\n } else {\n isFakeChild = false\n }\n\n if (d.parent === null) {\n if (!isFakeChild) {\n this.root = child\n child.blacken()\n child._parent = null\n } else {\n this.root = null\n }\n return\n } else if (d.parent.left === d) {\n d.parent.left = child\n } else if (d.parent.right === d) {\n d.parent.right = child\n } else {\n throw new Error('Impossible!')\n }\n if (d.isBlack()) {\n if (child.isRed()) {\n child.blacken()\n } else {\n this._fixDelete(child)\n }\n }\n this.root.blacken()\n if (isFakeChild) {\n if (child.parent.left === child) {\n child.parent.left = null\n } else if (child.parent.right === child) {\n child.parent.right = null\n } else {\n throw new Error('Impossible #3')\n }\n }\n }\n\n _fixDelete (n) {\n if (n.parent === null) {\n // this can only be called after the first iteration of fixDelete.\n return\n }\n // d was already replaced by the child\n // d is not the root\n // d and child are black\n let sibling = n.sibling\n if (isRed(sibling)) {\n // make sibling the grandfather\n n.parent.redden()\n sibling.blacken()\n if (n === n.parent.left) {\n n.parent.rotateLeft(this)\n } else if (n === n.parent.right) {\n n.parent.rotateRight(this)\n } else {\n throw new Error('Impossible #2')\n }\n sibling = n.sibling\n }\n // parent, sibling, and children of n are black\n if (n.parent.isBlack() &&\n sibling.isBlack() &&\n isBlack(sibling.left) &&\n isBlack(sibling.right)\n ) {\n sibling.redden()\n this._fixDelete(n.parent)\n } else if (n.parent.isRed() &&\n sibling.isBlack() &&\n isBlack(sibling.left) &&\n isBlack(sibling.right)\n ) {\n sibling.redden()\n n.parent.blacken()\n } else {\n if (n === n.parent.left &&\n sibling.isBlack() &&\n isRed(sibling.left) &&\n isBlack(sibling.right)\n ) {\n sibling.redden()\n sibling.left.blacken()\n sibling.rotateRight(this)\n sibling = n.sibling\n } else if (n === n.parent.right &&\n sibling.isBlack() &&\n isRed(sibling.right) &&\n isBlack(sibling.left)\n ) {\n sibling.redden()\n sibling.right.blacken()\n sibling.rotateLeft(this)\n sibling = n.sibling\n }\n sibling.color = n.parent.color\n n.parent.blacken()\n if (n === n.parent.left) {\n sibling.right.blacken()\n n.parent.rotateLeft(this)\n } else {\n sibling.left.blacken()\n n.parent.rotateRight(this)\n }\n }\n }\n\n put (v) {\n const node = new N(v)\n if (this.root !== null) {\n let p = this.root // p abbrev. parent\n while (true) {\n if (node.val._id.lessThan(p.val._id)) {\n if (p.left === null) {\n p.left = node\n break\n } else {\n p = p.left\n }\n } else if (p.val._id.lessThan(node.val._id)) {\n if (p.right === null) {\n p.right = node\n break\n } else {\n p = p.right\n }\n } else {\n p.val = node.val\n return p\n }\n }\n this._fixInsert(node)\n } else {\n this.root = node\n }\n this.length++\n this.root.blacken()\n return node\n }\n\n _fixInsert (n) {\n if (n.parent === null) {\n n.blacken()\n return\n } else if (n.parent.isBlack()) {\n return\n }\n const uncle = n.getUncle()\n if (uncle !== null && uncle.isRed()) {\n // Note: parent: red, uncle: red\n n.parent.blacken()\n uncle.blacken()\n n.grandparent.redden()\n this._fixInsert(n.grandparent)\n } else {\n // Note: parent: red, uncle: black or null\n // Now we transform the tree in such a way that\n // either of these holds:\n // 1) grandparent.left.isRed\n // and grandparent.left.left.isRed\n // 2) grandparent.right.isRed\n // and grandparent.right.right.isRed\n if (n === n.parent.right && n.parent === n.grandparent.left) {\n n.parent.rotateLeft(this)\n // Since we rotated and want to use the previous\n // cases, we need to set n in such a way that\n // n.parent.isRed again\n n = n.left\n } else if (n === n.parent.left && n.parent === n.grandparent.right) {\n n.parent.rotateRight(this)\n // see above\n n = n.right\n }\n // Case 1) or 2) hold from here on.\n // Now traverse grandparent, make parent a black node\n // on the highest level which holds two red nodes.\n n.parent.blacken()\n n.grandparent.redden()\n if (n === n.parent.left) {\n // Case 1\n n.grandparent.rotateRight(this)\n } else {\n // Case 2\n n.grandparent.rotateLeft(this)\n }\n }\n }\n}\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,KAAK;AAC/C,EAAE,IAAI,MAAM,KAAK,IAAI,EAAE;AACvB,IAAI,IAAI,CAAC,IAAI,GAAG,UAAS;AACzB,IAAI,SAAS,CAAC,OAAO,GAAG,KAAI;AAC5B,GAAG,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC,EAAE;AAChC,IAAI,MAAM,CAAC,IAAI,GAAG,UAAS;AAC3B,GAAG,MAAM,IAAI,MAAM,CAAC,KAAK,KAAK,CAAC,EAAE;AACjC,IAAI,MAAM,CAAC,KAAK,GAAG,UAAS;AAC5B,GAAG,MAAM;AACT,IAAI,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC;AAC1D,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA,MAAM,CAAC,CAAC;AACR;AACA;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,CAAC,GAAG,EAAE;AACpB,IAAI,IAAI,CAAC,GAAG,GAAG,IAAG;AAClB,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB,IAAI,IAAI,CAAC,KAAK,GAAG,KAAI;AACrB,IAAI,IAAI,CAAC,MAAM,GAAG,KAAI;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tree.cjs new file mode 100644 index 00000000..5483f423 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree.cjs @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var tree = require('./tree-9f3c8837.cjs'); + + + +exports.Tree = tree.Tree; +//# sourceMappingURL=tree.cjs.map diff --git a/nodejs/node_modules/lib0/dist/tree.cjs.map b/nodejs/node_modules/lib0/dist/tree.cjs.map new file mode 100644 index 00000000..d423c900 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"tree.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/tree.d.ts b/nodejs/node_modules/lib0/dist/tree.d.ts new file mode 100644 index 00000000..7d4535cf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree.d.ts @@ -0,0 +1,96 @@ +/** + * This is a Red Black Tree implementation + * + * @template K,V + */ +export class Tree { + root: any; + length: number; + /** + * @param {K} id + */ + findNext(id: K): V; + /** + * @param {K} id + */ + findPrev(id: K): V; + /** + * @param {K} from + */ + findNodeWithLowerBound(from: K): any; + /** + * @param {K} to + */ + findNodeWithUpperBound(to: K): any; + /** + * @return {V} + */ + findSmallestNode(): V; + /** + * @param {K} from + * @return {V} + */ + findWithLowerBound(from: K): V; + /** + * @param {K} to + * @return {V} + */ + findWithUpperBound(to: K): V; + /** + * @param {K} from + * @param {V} from + * @param {function(V):void} f + */ + iterate(from: K, to: any, f: (arg0: V) => void): void; + /** + * @param {K} id + * @return {V|null} + */ + find(id: K): V | null; + /** + * @param {K} id + * @return {N|null} + */ + findNode(id: K): N | null; + /** + * @param {K} id + */ + delete(id: K): void; + _fixDelete(n: any): void; + put(v: any): any; + _fixInsert(n: any): void; +} +/** + * @template V + */ +declare class N { + /** + * A created node is always red! + * + * @param {V} val + */ + constructor(val: V); + val: V; + color: boolean; + _left: any; + _right: any; + _parent: any; + isRed(): boolean; + isBlack(): boolean; + redden(): N; + blacken(): N; + get grandparent(): any; + get parent(): any; + get sibling(): any; + set left(arg: any); + get left(): any; + set right(arg: any); + get right(): any; + rotateLeft(tree: any): void; + next(): any; + prev(): any; + rotateRight(tree: any): void; + getUncle(): any; +} +export {}; +//# sourceMappingURL=tree.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/tree.d.ts.map b/nodejs/node_modules/lib0/dist/tree.d.ts.map new file mode 100644 index 00000000..6aaa8158 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tree.d.ts","sourceRoot":"","sources":["../tree.js"],"names":[],"mappings":"AAiJA;;;;GAIG;AACH;IAEI,UAAgB;IAChB,eAAe;IAGjB;;OAEG;IACH,aAFW,CAAC,KAMX;IAED;;OAEG;IACH,aAFW,CAAC,KAMX;IAED;;OAEG;IACH,6BAFW,CAAC,OA0BX;IAED;;OAEG;IACH,2BAFW,CAAC,OA6BX;IAED;;OAEG;IACH,oBAFY,CAAC,CAQZ;IAED;;;OAGG;IACH,yBAHW,CAAC,GACA,CAAC,CAKZ;IAED;;;OAGG;IACH,uBAHW,CAAC,GACA,CAAC,CAKZ;IAED;;;;OAIG;IACH,cAJW,CAAC,qBAEQ,CAAC,KAAE,IAAI,QAoB1B;IAED;;;OAGG;IACH,SAHW,CAAC,GACA,CAAC,GAAC,IAAI,CASjB;IAED;;;OAGG;IACH,aAHW,CAAC,GACA,EAAE,CAAC,CAAC,GAAC,IAAI,CAoBpB;IAED;;OAEG;IACH,WAFW,CAAC,QAmEX;IAED,yBAmEC;IAED,iBA+BC;IAED,yBA8CC;CACF;AA7gBD;;GAEG;AACH;IACE;;;;OAIG;IACH,iBAFW,CAAC,EAQX;IALC,OAAc;IACd,eAAiB;IACjB,WAAiB;IACjB,YAAkB;IAClB,aAAmB;IAGrB,iBAA8B;IAC9B,mBAAiC;IACjC,eAA4C;IAC5C,gBAA8C;IAC9C,uBAEC;IAED,kBAEC;IAED,mBAIC;IAUD,mBAKC;IAbD,gBAEC;IAaD,oBAKC;IAhBD,iBAEC;IAgBD,4BAOC;IAED,YAeC;IAED,YAeC;IAED,6BAOC;IAED,gBAOC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/tree.test.d.ts b/nodejs/node_modules/lib0/dist/tree.test.d.ts new file mode 100644 index 00000000..54a03d2c --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=tree.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/tree.test.d.ts.map b/nodejs/node_modules/lib0/dist/tree.test.d.ts.map new file mode 100644 index 00000000..193aa868 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/tree.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tree.test.d.ts","sourceRoot":"","sources":["../tree.test.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/url.cjs b/nodejs/node_modules/lib0/dist/url.cjs new file mode 100644 index 00000000..bbf0439d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/url.cjs @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var object = require('./object-fecf6a7b.cjs'); + +/** + * Utility module to work with urls. + * + * @module url + */ + +/** + * Parse query parameters from an url. + * + * @param {string} url + * @return {Object} + */ +const decodeQueryParams = url => { + /** + * @type {Object} + */ + const query = {}; + const urlQuerySplit = url.split('?'); + const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&'); + for (let i = 0; i < pairs.length; i++) { + const item = pairs[i]; + if (item.length > 0) { + const pair = item.split('='); + query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || ''); + } + } + return query +}; + +/** + * @param {Object} params + * @return {string} + */ +const encodeQueryParams = params => + object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&'); + +exports.decodeQueryParams = decodeQueryParams; +exports.encodeQueryParams = encodeQueryParams; +//# sourceMappingURL=url.cjs.map diff --git a/nodejs/node_modules/lib0/dist/url.cjs.map b/nodejs/node_modules/lib0/dist/url.cjs.map new file mode 100644 index 00000000..f8592abf --- /dev/null +++ b/nodejs/node_modules/lib0/dist/url.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"url.cjs","sources":["../url.js"],"sourcesContent":["/**\n * Utility module to work with urls.\n *\n * @module url\n */\n\nimport * as object from './object.js'\n\n/**\n * Parse query parameters from an url.\n *\n * @param {string} url\n * @return {Object}\n */\nexport const decodeQueryParams = url => {\n /**\n * @type {Object}\n */\n const query = {}\n const urlQuerySplit = url.split('?')\n const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')\n for (let i = 0; i < pairs.length; i++) {\n const item = pairs[i]\n if (item.length > 0) {\n const pair = item.split('=')\n query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')\n }\n }\n return query\n}\n\n/**\n * @param {Object} params\n * @return {string}\n */\nexport const encodeQueryParams = params =>\n object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')\n"],"names":["object.map"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,iBAAiB,GAAG,GAAG,IAAI;AACxC;AACA;AACA;AACA,EAAE,MAAM,KAAK,GAAG,GAAE;AAClB,EAAE,MAAM,aAAa,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,EAAC;AACtC,EAAE,MAAM,KAAK,GAAG,aAAa,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAC;AAClE,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACzC,IAAI,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,EAAC;AACzB,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;AACzB,MAAM,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,EAAC;AAClC,MAAM,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,EAAC;AAC5E,KAAK;AACL,GAAG;AACH,EAAE,OAAO,KAAK;AACd,EAAC;AACD;AACA;AACA;AACA;AACA;AACY,MAAC,iBAAiB,GAAG,MAAM;AACvC,EAAEA,UAAU,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,EAAE,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/url.d.ts b/nodejs/node_modules/lib0/dist/url.d.ts new file mode 100644 index 00000000..ed2895c9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/url.d.ts @@ -0,0 +1,7 @@ +export function decodeQueryParams(url: string): { + [x: string]: string; +}; +export function encodeQueryParams(params: { + [x: string]: string; +}): string; +//# sourceMappingURL=url.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/url.d.ts.map b/nodejs/node_modules/lib0/dist/url.d.ts.map new file mode 100644 index 00000000..d96c4ed3 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/url.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../url.js"],"names":[],"mappings":"AAcO,uCAHI,MAAM;QACE,MAAM,GAAC,MAAM;EAiB/B;AAMM;QAHW,MAAM,GAAC,MAAM;IACnB,MAAM,CAGmF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/url.test.d.ts b/nodejs/node_modules/lib0/dist/url.test.d.ts new file mode 100644 index 00000000..027c9ee7 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/url.test.d.ts @@ -0,0 +1,3 @@ +export function testUrlParamQuery(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=url.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/url.test.d.ts.map b/nodejs/node_modules/lib0/dist/url.test.d.ts.map new file mode 100644 index 00000000..7b56be33 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/url.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"url.test.d.ts","sourceRoot":"","sources":["../url.test.js"],"names":[],"mappings":"AAcO,sCAFI,EAAE,QAAQ,QAapB;mBAzBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.cjs b/nodejs/node_modules/lib0/dist/webcrypto.cjs new file mode 100644 index 00000000..ddbfc299 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.cjs @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/* eslint-env browser */ + +const subtle = crypto.subtle; +const getRandomValues = crypto.getRandomValues.bind(crypto); + +exports.getRandomValues = getRandomValues; +exports.subtle = subtle; +//# sourceMappingURL=webcrypto.cjs.map diff --git a/nodejs/node_modules/lib0/dist/webcrypto.cjs.map b/nodejs/node_modules/lib0/dist/webcrypto.cjs.map new file mode 100644 index 00000000..44e20181 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.cjs","sources":["../webcrypto.js"],"sourcesContent":["/* eslint-env browser */\n\nexport const subtle = crypto.subtle\nexport const getRandomValues = crypto.getRandomValues.bind(crypto)\n"],"names":[],"mappings":";;;;AAAA;AACA;AACY,MAAC,MAAM,GAAG,MAAM,CAAC,OAAM;AACvB,MAAC,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,MAAM;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.d.ts b/nodejs/node_modules/lib0/dist/webcrypto.d.ts new file mode 100644 index 00000000..ea1852e9 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.d.ts @@ -0,0 +1,3 @@ +export const subtle: SubtleCrypto; +export const getRandomValues: (array: T) => T; +//# sourceMappingURL=webcrypto.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.d.ts.map b/nodejs/node_modules/lib0/dist/webcrypto.d.ts.map new file mode 100644 index 00000000..a1c20f97 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["../webcrypto.js"],"names":[],"mappings":"AAEA,kCAAmC;AACnC,gFAAkE"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.deno.cjs b/nodejs/node_modules/lib0/dist/webcrypto.deno.cjs new file mode 100644 index 00000000..5934e4ce --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.deno.cjs @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +// eslint-disable-next-line +const subtle = /** @type {any} */ (crypto).subtle; +// eslint-disable-next-line +const getRandomValues = /** @type {any} */ (crypto).getRandomValues.bind(crypto); + +exports.getRandomValues = getRandomValues; +exports.subtle = subtle; +//# sourceMappingURL=webcrypto.deno.cjs.map diff --git a/nodejs/node_modules/lib0/dist/webcrypto.deno.cjs.map b/nodejs/node_modules/lib0/dist/webcrypto.deno.cjs.map new file mode 100644 index 00000000..443ac800 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.deno.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.deno.cjs","sources":["../webcrypto.deno.js"],"sourcesContent":["// eslint-disable-next-line\nexport const subtle = /** @type {any} */ (crypto).subtle\n// eslint-disable-next-line\nexport const getRandomValues = /** @type {any} */ (crypto).getRandomValues.bind(crypto)\n"],"names":[],"mappings":";;;;AAAA;AACY,MAAC,MAAM,sBAAsB,CAAC,MAAM,EAAE,OAAM;AACxD;AACY,MAAC,eAAe,sBAAsB,CAAC,MAAM,EAAE,eAAe,CAAC,IAAI,CAAC,MAAM;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.deno.d.ts b/nodejs/node_modules/lib0/dist/webcrypto.deno.d.ts new file mode 100644 index 00000000..ec6b5e5a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.deno.d.ts @@ -0,0 +1,3 @@ +export const subtle: any; +export const getRandomValues: any; +//# sourceMappingURL=webcrypto.deno.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.deno.d.ts.map b/nodejs/node_modules/lib0/dist/webcrypto.deno.d.ts.map new file mode 100644 index 00000000..264be7fa --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.deno.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.deno.d.ts","sourceRoot":"","sources":["../webcrypto.deno.js"],"names":[],"mappings":"AACA,yBAAwD;AAExD,kCAAuF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.node.cjs b/nodejs/node_modules/lib0/dist/webcrypto.node.cjs new file mode 100644 index 00000000..378e7f54 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.node.cjs @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var node_crypto = require('node:crypto'); + +const subtle = /** @type {any} */ (node_crypto.webcrypto).subtle; +const getRandomValues = /** @type {any} */ (node_crypto.webcrypto).getRandomValues.bind(node_crypto.webcrypto); + +exports.getRandomValues = getRandomValues; +exports.subtle = subtle; +//# sourceMappingURL=webcrypto.node.cjs.map diff --git a/nodejs/node_modules/lib0/dist/webcrypto.node.cjs.map b/nodejs/node_modules/lib0/dist/webcrypto.node.cjs.map new file mode 100644 index 00000000..558afb36 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.node.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.node.cjs","sources":["../webcrypto.node.js"],"sourcesContent":["import { webcrypto } from 'node:crypto'\n\nexport const subtle = /** @type {any} */ (webcrypto).subtle\nexport const getRandomValues = /** @type {any} */ (webcrypto).getRandomValues.bind(webcrypto)\n"],"names":["webcrypto"],"mappings":";;;;;;AAEY,MAAC,MAAM,sBAAsB,CAACA,qBAAS,EAAE,OAAM;AAC/C,MAAC,eAAe,sBAAsB,CAACA,qBAAS,EAAE,eAAe,CAAC,IAAI,CAACA,qBAAS;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.node.d.ts b/nodejs/node_modules/lib0/dist/webcrypto.node.d.ts new file mode 100644 index 00000000..0026211a --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.node.d.ts @@ -0,0 +1,3 @@ +export const subtle: any; +export const getRandomValues: any; +//# sourceMappingURL=webcrypto.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/webcrypto.node.d.ts.map b/nodejs/node_modules/lib0/dist/webcrypto.node.d.ts.map new file mode 100644 index 00000000..847c2b98 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/webcrypto.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.node.d.ts","sourceRoot":"","sources":["../webcrypto.node.js"],"names":[],"mappings":"AAEA,yBAA2D;AAC3D,kCAA6F"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/websocket-d9e16a69.cjs b/nodejs/node_modules/lib0/dist/websocket-d9e16a69.cjs new file mode 100644 index 00000000..5c957585 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/websocket-d9e16a69.cjs @@ -0,0 +1,157 @@ +'use strict'; + +var observable = require('./observable.cjs'); +var time = require('./time-bc2081b9.cjs'); +var math = require('./math-08e068f9.cjs'); + +/* eslint-env browser */ + +const reconnectTimeoutBase = 1200; +const maxReconnectTimeout = 2500; +// @todo - this should depend on awareness.outdatedTime +const messageReconnectTimeout = 30000; + +/** + * @param {WebsocketClient} wsclient + */ +const setupWS = (wsclient) => { + if (wsclient.shouldConnect && wsclient.ws === null) { + const websocket = new WebSocket(wsclient.url); + const binaryType = wsclient.binaryType; + /** + * @type {any} + */ + let pingTimeout = null; + if (binaryType) { + websocket.binaryType = binaryType; + } + wsclient.ws = websocket; + wsclient.connecting = true; + wsclient.connected = false; + websocket.onmessage = event => { + wsclient.lastMessageReceived = time.getUnixTime(); + const data = event.data; + const message = typeof data === 'string' ? JSON.parse(data) : data; + if (message && message.type === 'pong') { + clearTimeout(pingTimeout); + pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2); + } + wsclient.emit('message', [message, wsclient]); + }; + /** + * @param {any} error + */ + const onclose = error => { + if (wsclient.ws !== null) { + wsclient.ws = null; + wsclient.connecting = false; + if (wsclient.connected) { + wsclient.connected = false; + wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient]); + } else { + wsclient.unsuccessfulReconnects++; + } + // Start with no reconnect timeout and increase timeout by + // log10(wsUnsuccessfulReconnects). + // The idea is to increase reconnect timeout slowly and have no reconnect + // timeout at the beginning (log(1) = 0) + setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient); + } + clearTimeout(pingTimeout); + }; + const sendPing = () => { + if (wsclient.ws === websocket) { + wsclient.send({ + type: 'ping' + }); + } + }; + websocket.onclose = () => onclose(null); + websocket.onerror = error => onclose(error); + websocket.onopen = () => { + wsclient.lastMessageReceived = time.getUnixTime(); + wsclient.connecting = false; + wsclient.connected = true; + wsclient.unsuccessfulReconnects = 0; + wsclient.emit('connect', [{ type: 'connect' }, wsclient]); + // set ping + pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2); + }; + } +}; + +/** + * @deprecated + * @extends Observable + */ +class WebsocketClient extends observable.Observable { + /** + * @param {string} url + * @param {object} opts + * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType` + */ + constructor (url, { binaryType } = {}) { + super(); + this.url = url; + /** + * @type {WebSocket?} + */ + this.ws = null; + this.binaryType = binaryType || null; + this.connected = false; + this.connecting = false; + this.unsuccessfulReconnects = 0; + this.lastMessageReceived = 0; + /** + * Whether to connect to other peers or not + * @type {boolean} + */ + this.shouldConnect = true; + this._checkInterval = setInterval(() => { + if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) { + // no message received in a long time - not even your own awareness + // updates (which are updated every 15 seconds) + /** @type {WebSocket} */ (this.ws).close(); + } + }, messageReconnectTimeout / 2); + setupWS(this); + } + + /** + * @param {any} message + */ + send (message) { + if (this.ws) { + this.ws.send(JSON.stringify(message)); + } + } + + destroy () { + clearInterval(this._checkInterval); + this.disconnect(); + super.destroy(); + } + + disconnect () { + this.shouldConnect = false; + if (this.ws !== null) { + this.ws.close(); + } + } + + connect () { + this.shouldConnect = true; + if (!this.connected && this.ws === null) { + setupWS(this); + } + } +} + +var websocket = /*#__PURE__*/Object.freeze({ + __proto__: null, + WebsocketClient: WebsocketClient +}); + +exports.WebsocketClient = WebsocketClient; +exports.websocket = websocket; +//# sourceMappingURL=websocket-d9e16a69.cjs.map diff --git a/nodejs/node_modules/lib0/dist/websocket-d9e16a69.cjs.map b/nodejs/node_modules/lib0/dist/websocket-d9e16a69.cjs.map new file mode 100644 index 00000000..f8fa2eff --- /dev/null +++ b/nodejs/node_modules/lib0/dist/websocket-d9e16a69.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket-d9e16a69.cjs","sources":["../websocket.js"],"sourcesContent":["/* eslint-env browser */\n\n/**\n * Tiny websocket connection handler.\n *\n * Implements exponential backoff reconnects, ping/pong, and a nice event system using [lib0/observable].\n *\n * @module websocket\n */\n\nimport { Observable } from './observable.js'\nimport * as time from './time.js'\nimport * as math from './math.js'\n\nconst reconnectTimeoutBase = 1200\nconst maxReconnectTimeout = 2500\n// @todo - this should depend on awareness.outdatedTime\nconst messageReconnectTimeout = 30000\n\n/**\n * @param {WebsocketClient} wsclient\n */\nconst setupWS = (wsclient) => {\n if (wsclient.shouldConnect && wsclient.ws === null) {\n const websocket = new WebSocket(wsclient.url)\n const binaryType = wsclient.binaryType\n /**\n * @type {any}\n */\n let pingTimeout = null\n if (binaryType) {\n websocket.binaryType = binaryType\n }\n wsclient.ws = websocket\n wsclient.connecting = true\n wsclient.connected = false\n websocket.onmessage = event => {\n wsclient.lastMessageReceived = time.getUnixTime()\n const data = event.data\n const message = typeof data === 'string' ? JSON.parse(data) : data\n if (message && message.type === 'pong') {\n clearTimeout(pingTimeout)\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n wsclient.emit('message', [message, wsclient])\n }\n /**\n * @param {any} error\n */\n const onclose = error => {\n if (wsclient.ws !== null) {\n wsclient.ws = null\n wsclient.connecting = false\n if (wsclient.connected) {\n wsclient.connected = false\n wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient])\n } else {\n wsclient.unsuccessfulReconnects++\n }\n // Start with no reconnect timeout and increase timeout by\n // log10(wsUnsuccessfulReconnects).\n // The idea is to increase reconnect timeout slowly and have no reconnect\n // timeout at the beginning (log(1) = 0)\n setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient)\n }\n clearTimeout(pingTimeout)\n }\n const sendPing = () => {\n if (wsclient.ws === websocket) {\n wsclient.send({\n type: 'ping'\n })\n }\n }\n websocket.onclose = () => onclose(null)\n websocket.onerror = error => onclose(error)\n websocket.onopen = () => {\n wsclient.lastMessageReceived = time.getUnixTime()\n wsclient.connecting = false\n wsclient.connected = true\n wsclient.unsuccessfulReconnects = 0\n wsclient.emit('connect', [{ type: 'connect' }, wsclient])\n // set ping\n pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)\n }\n }\n}\n\n/**\n * @deprecated\n * @extends Observable\n */\nexport class WebsocketClient extends Observable {\n /**\n * @param {string} url\n * @param {object} opts\n * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType`\n */\n constructor (url, { binaryType } = {}) {\n super()\n this.url = url\n /**\n * @type {WebSocket?}\n */\n this.ws = null\n this.binaryType = binaryType || null\n this.connected = false\n this.connecting = false\n this.unsuccessfulReconnects = 0\n this.lastMessageReceived = 0\n /**\n * Whether to connect to other peers or not\n * @type {boolean}\n */\n this.shouldConnect = true\n this._checkInterval = setInterval(() => {\n if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) {\n // no message received in a long time - not even your own awareness\n // updates (which are updated every 15 seconds)\n /** @type {WebSocket} */ (this.ws).close()\n }\n }, messageReconnectTimeout / 2)\n setupWS(this)\n }\n\n /**\n * @param {any} message\n */\n send (message) {\n if (this.ws) {\n this.ws.send(JSON.stringify(message))\n }\n }\n\n destroy () {\n clearInterval(this._checkInterval)\n this.disconnect()\n super.destroy()\n }\n\n disconnect () {\n this.shouldConnect = false\n if (this.ws !== null) {\n this.ws.close()\n }\n }\n\n connect () {\n this.shouldConnect = true\n if (!this.connected && this.ws === null) {\n setupWS(this)\n }\n }\n}\n"],"names":["time.getUnixTime","math.min","math.log10","Observable"],"mappings":";;;;;;AAAA;AAaA;AACA,MAAM,oBAAoB,GAAG,KAAI;AACjC,MAAM,mBAAmB,GAAG,KAAI;AAChC;AACA,MAAM,uBAAuB,GAAG,MAAK;AACrC;AACA;AACA;AACA;AACA,MAAM,OAAO,GAAG,CAAC,QAAQ,KAAK;AAC9B,EAAE,IAAI,QAAQ,CAAC,aAAa,IAAI,QAAQ,CAAC,EAAE,KAAK,IAAI,EAAE;AACtD,IAAI,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAC;AACjD,IAAI,MAAM,UAAU,GAAG,QAAQ,CAAC,WAAU;AAC1C;AACA;AACA;AACA,IAAI,IAAI,WAAW,GAA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E,KAAK,IAAI,EAAE;AAC1B,MAAM,IAAI,CAAC,EAAE,CAAC,KAAK,GAAE;AACrB,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,CAAC,GAAG;AACb,IAAI,IAAI,CAAC,aAAa,GAAG,KAAI;AAC7B,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI,EAAE;AAC7C,MAAM,OAAO,CAAC,IAAI,EAAC;AACnB,KAAK;AACL,GAAG;AACH;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/websocket.cjs b/nodejs/node_modules/lib0/dist/websocket.cjs new file mode 100644 index 00000000..73b751c2 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/websocket.cjs @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./observable.cjs'); +require('./time-bc2081b9.cjs'); +require('./math-08e068f9.cjs'); +var websocket = require('./websocket-d9e16a69.cjs'); +require('./map-0dabcc55.cjs'); +require('./set-0f209abb.cjs'); +require('./array-704ca50e.cjs'); +require('./metric.cjs'); + + + +exports.WebsocketClient = websocket.WebsocketClient; +//# sourceMappingURL=websocket.cjs.map diff --git a/nodejs/node_modules/lib0/dist/websocket.cjs.map b/nodejs/node_modules/lib0/dist/websocket.cjs.map new file mode 100644 index 00000000..e9700655 --- /dev/null +++ b/nodejs/node_modules/lib0/dist/websocket.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/websocket.d.ts b/nodejs/node_modules/lib0/dist/websocket.d.ts new file mode 100644 index 00000000..2990beda --- /dev/null +++ b/nodejs/node_modules/lib0/dist/websocket.d.ts @@ -0,0 +1,38 @@ +/** + * @deprecated + * @extends Observable + */ +export class WebsocketClient extends Observable { + /** + * @param {string} url + * @param {object} opts + * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType` + */ + constructor(url: string, { binaryType }?: { + binaryType?: "arraybuffer" | "blob" | null | undefined; + }); + url: string; + /** + * @type {WebSocket?} + */ + ws: WebSocket | null; + binaryType: "arraybuffer" | "blob" | null; + connected: boolean; + connecting: boolean; + unsuccessfulReconnects: number; + lastMessageReceived: number; + /** + * Whether to connect to other peers or not + * @type {boolean} + */ + shouldConnect: boolean; + _checkInterval: NodeJS.Timer; + /** + * @param {any} message + */ + send(message: any): void; + disconnect(): void; + connect(): void; +} +import { Observable } from './observable.js'; +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dist/websocket.d.ts.map b/nodejs/node_modules/lib0/dist/websocket.d.ts.map new file mode 100644 index 00000000..a2a8c55d --- /dev/null +++ b/nodejs/node_modules/lib0/dist/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../websocket.js"],"names":[],"mappings":"AAwFA;;;GAGG;AACH;IACE;;;;OAIG;IACH,iBAJW,MAAM;QAE+B,UAAU;OA2BzD;IAvBC,YAAc;IACd;;OAEG;IACH,IAFU,SAAS,QAEL;IACd,0CAAoC;IACpC,mBAAsB;IACtB,oBAAuB;IACvB,+BAA+B;IAC/B,4BAA4B;IAC5B;;;OAGG;IACH,eAFU,OAAO,CAEQ;IACzB,6BAM+B;IAIjC;;OAEG;IACH,cAFW,GAAG,QAMb;IAQD,mBAKC;IAED,gBAKC;CACF;2BA/I0B,iBAAiB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dom.d.ts b/nodejs/node_modules/lib0/dom.d.ts new file mode 100644 index 00000000..91701491 --- /dev/null +++ b/nodejs/node_modules/lib0/dom.d.ts @@ -0,0 +1,43 @@ +/** + * @type {Document} + */ +export const doc: Document; +export function createElement(name: string): HTMLElement; +export function createDocumentFragment(): DocumentFragment; +export function createTextNode(text: string): Text; +export const domParser: DOMParser; +export function emitCustomEvent(el: HTMLElement, name: string, opts: Object): boolean; +export function setAttributes(el: Element, attrs: Array>): Element; +export function setAttributesMap(el: Element, attrs: Map): Element; +export function fragment(children: Array | HTMLCollection): DocumentFragment; +export function append(parent: Element, nodes: Array): Element; +export function remove(el: HTMLElement): void; +export function addEventListener(el: EventTarget, name: string, f: EventListener): void; +export function removeEventListener(el: EventTarget, name: string, f: EventListener): void; +export function addEventListeners(node: Node, listeners: Array>): Node; +export function removeEventListeners(node: Node, listeners: Array>): Node; +export function element(name: string, attrs?: Array | pair.Pair>, children?: Array): Element; +export function canvas(width: number, height: number): HTMLCanvasElement; +export function text(text: string): Text; +export function pairToStyleString(pair: pair.Pair): string; +export function pairsToStyleString(pairs: Array>): string; +export function mapToStyleString(m: Map): string; +export function querySelector(el: HTMLElement | ShadowRoot, query: string): HTMLElement | null; +export function querySelectorAll(el: HTMLElement | ShadowRoot, query: string): NodeListOf; +export function getElementById(id: string): HTMLElement; +export function parseFragment(html: string): DocumentFragment; +export function parseElement(html: string): HTMLElement; +export function replaceWith(oldEl: HTMLElement, newEl: HTMLElement | DocumentFragment): void; +export function insertBefore(parent: HTMLElement, el: HTMLElement, ref: Node | null): HTMLElement; +export function appendChild(parent: Node, child: Node): Node; +export const ELEMENT_NODE: 1; +export const TEXT_NODE: 3; +export const CDATA_SECTION_NODE: 4; +export const COMMENT_NODE: 8; +export const DOCUMENT_NODE: 9; +export const DOCUMENT_TYPE_NODE: 10; +export const DOCUMENT_FRAGMENT_NODE: 11; +export function checkNodeType(node: any, type: number): boolean; +export function isParentOf(parent: Node, child: HTMLElement): boolean; +import * as pair from './pair.js'; +//# sourceMappingURL=dom.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dom.d.ts.map b/nodejs/node_modules/lib0/dom.d.ts.map new file mode 100644 index 00000000..596f235c --- /dev/null +++ b/nodejs/node_modules/lib0/dom.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["dom.js"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AC,GAC9B,MAAM,CAE8D;AAMzE,oCAHI,IAAI,MAAM,EAAC,MAAM,CAAC,GACjB,MAAM,CAE0E;AASrF,kCAJI,WAAW,GAAC,UAAU,SACtB,MAAM,GACL,WAAW,GAAG,IAAI,CAEqC;AAO5D,qCAJI,WAAW,GAAC,UAAU,SACtB,MAAM,GACL,WAAW,WAAW,CAAC,CAEsC;AAMlE,mCAHI,MAAM,GACL,WAAW,CAEgE;AAYhF,oCAHI,MAAM,GACL,gBAAgB,CAE+D;AAMpF,mCAHI,MAAM,GACL,WAAW,CAEsE;AAMtF,mCAHI,WAAW,SACX,WAAW,GAAC,gBAAgB,QAE8B;AAQ9D,qCALI,WAAW,MACX,WAAW,OACX,IAAI,GAAC,IAAI,GACR,WAAW,CAEsD;AAOtE,oCAJI,IAAI,SACJ,IAAI,GACH,IAAI,CAEuD;AAEvE,6BAA4C;AAC5C,0BAAsC;AACtC,mCAAwD;AACxD,6BAA4C;AAC5C,8BAA8C;AAC9C,oCAAwD;AACxD,wCAAgE;AAMzD,oCAHI,GAAG,QACH,MAAM,WAEkD;AAM5D,mCAHI,IAAI,SACJ,WAAW,WAQrB;sBA7PqB,WAAW"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/dom.js b/nodejs/node_modules/lib0/dom.js new file mode 100644 index 00000000..d850fbbc --- /dev/null +++ b/nodejs/node_modules/lib0/dom.js @@ -0,0 +1,263 @@ +/* eslint-env browser */ + +/** + * Utility module to work with the DOM. + * + * @module dom + */ + +import * as pair from './pair.js' +import * as map from './map.js' + +/* c8 ignore start */ +/** + * @type {Document} + */ +export const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {}) + +/** + * @param {string} name + * @return {HTMLElement} + */ +export const createElement = name => doc.createElement(name) + +/** + * @return {DocumentFragment} + */ +export const createDocumentFragment = () => doc.createDocumentFragment() + +/** + * @param {string} text + * @return {Text} + */ +export const createTextNode = text => doc.createTextNode(text) + +export const domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null) + +/** + * @param {HTMLElement} el + * @param {string} name + * @param {Object} opts + */ +export const emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts)) + +/** + * @param {Element} el + * @param {Array>} attrs Array of key-value pairs + * @return {Element} + */ +export const setAttributes = (el, attrs) => { + pair.forEach(attrs, (key, value) => { + if (value === false) { + el.removeAttribute(key) + } else if (value === true) { + el.setAttribute(key, '') + } else { + // @ts-ignore + el.setAttribute(key, value) + } + }) + return el +} + +/** + * @param {Element} el + * @param {Map} attrs Array of key-value pairs + * @return {Element} + */ +export const setAttributesMap = (el, attrs) => { + attrs.forEach((value, key) => { el.setAttribute(key, value) }) + return el +} + +/** + * @param {Array|HTMLCollection} children + * @return {DocumentFragment} + */ +export const fragment = children => { + const fragment = createDocumentFragment() + for (let i = 0; i < children.length; i++) { + appendChild(fragment, children[i]) + } + return fragment +} + +/** + * @param {Element} parent + * @param {Array} nodes + * @return {Element} + */ +export const append = (parent, nodes) => { + appendChild(parent, fragment(nodes)) + return parent +} + +/** + * @param {HTMLElement} el + */ +export const remove = el => el.remove() + +/** + * @param {EventTarget} el + * @param {string} name + * @param {EventListener} f + */ +export const addEventListener = (el, name, f) => el.addEventListener(name, f) + +/** + * @param {EventTarget} el + * @param {string} name + * @param {EventListener} f + */ +export const removeEventListener = (el, name, f) => el.removeEventListener(name, f) + +/** + * @param {Node} node + * @param {Array>} listeners + * @return {Node} + */ +export const addEventListeners = (node, listeners) => { + pair.forEach(listeners, (name, f) => addEventListener(node, name, f)) + return node +} + +/** + * @param {Node} node + * @param {Array>} listeners + * @return {Node} + */ +export const removeEventListeners = (node, listeners) => { + pair.forEach(listeners, (name, f) => removeEventListener(node, name, f)) + return node +} + +/** + * @param {string} name + * @param {Array|pair.Pair>} attrs Array of key-value pairs + * @param {Array} children + * @return {Element} + */ +export const element = (name, attrs = [], children = []) => + append(setAttributes(createElement(name), attrs), children) + +/** + * @param {number} width + * @param {number} height + */ +export const canvas = (width, height) => { + const c = /** @type {HTMLCanvasElement} */ (createElement('canvas')) + c.height = height + c.width = width + return c +} + +/** + * @param {string} t + * @return {Text} + */ +export const text = createTextNode + +/** + * @param {pair.Pair} pair + */ +export const pairToStyleString = pair => `${pair.left}:${pair.right};` + +/** + * @param {Array>} pairs + * @return {string} + */ +export const pairsToStyleString = pairs => pairs.map(pairToStyleString).join('') + +/** + * @param {Map} m + * @return {string} + */ +export const mapToStyleString = m => map.map(m, (value, key) => `${key}:${value};`).join('') + +/** + * @todo should always query on a dom element + * + * @param {HTMLElement|ShadowRoot} el + * @param {string} query + * @return {HTMLElement | null} + */ +export const querySelector = (el, query) => el.querySelector(query) + +/** + * @param {HTMLElement|ShadowRoot} el + * @param {string} query + * @return {NodeListOf} + */ +export const querySelectorAll = (el, query) => el.querySelectorAll(query) + +/** + * @param {string} id + * @return {HTMLElement} + */ +export const getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id)) + +/** + * @param {string} html + * @return {HTMLElement} + */ +const _parse = html => domParser.parseFromString(`${html}`, 'text/html').body + +/** + * @param {string} html + * @return {DocumentFragment} + */ +export const parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes)) + +/** + * @param {string} html + * @return {HTMLElement} + */ +export const parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild) + +/** + * @param {HTMLElement} oldEl + * @param {HTMLElement|DocumentFragment} newEl + */ +export const replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl) + +/** + * @param {HTMLElement} parent + * @param {HTMLElement} el + * @param {Node|null} ref + * @return {HTMLElement} + */ +export const insertBefore = (parent, el, ref) => parent.insertBefore(el, ref) + +/** + * @param {Node} parent + * @param {Node} child + * @return {Node} + */ +export const appendChild = (parent, child) => parent.appendChild(child) + +export const ELEMENT_NODE = doc.ELEMENT_NODE +export const TEXT_NODE = doc.TEXT_NODE +export const CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE +export const COMMENT_NODE = doc.COMMENT_NODE +export const DOCUMENT_NODE = doc.DOCUMENT_NODE +export const DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE +export const DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE + +/** + * @param {any} node + * @param {number} type + */ +export const checkNodeType = (node, type) => node.nodeType === type + +/** + * @param {Node} parent + * @param {HTMLElement} child + */ +export const isParentOf = (parent, child) => { + let p = child.parentNode + while (p && p !== parent) { + p = p.parentNode + } + return p === parent +} +/* c8 ignore stop */ diff --git a/nodejs/node_modules/lib0/encoding.d.ts b/nodejs/node_modules/lib0/encoding.d.ts new file mode 100644 index 00000000..fe4568b8 --- /dev/null +++ b/nodejs/node_modules/lib0/encoding.d.ts @@ -0,0 +1,233 @@ +/** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ +export class Encoder { + cpos: number; + cbuf: Uint8Array; + /** + * @type {Array} + */ + bufs: Array; +} +export function createEncoder(): Encoder; +export function encode(f: (arg0: Encoder) => void): Uint8Array; +export function length(encoder: Encoder): number; +export function hasContent(encoder: Encoder): boolean; +export function toUint8Array(encoder: Encoder): Uint8Array; +export function verifyLen(encoder: Encoder, len: number): void; +export function write(encoder: Encoder, num: number): void; +export function set(encoder: Encoder, pos: number, num: number): void; +export function writeUint8(encoder: Encoder, num: number): void; +export function setUint8(encoder: Encoder, pos: number, num: number): void; +export function writeUint16(encoder: Encoder, num: number): void; +export function setUint16(encoder: Encoder, pos: number, num: number): void; +export function writeUint32(encoder: Encoder, num: number): void; +export function writeUint32BigEndian(encoder: Encoder, num: number): void; +export function setUint32(encoder: Encoder, pos: number, num: number): void; +export function writeVarUint(encoder: Encoder, num: number): void; +export function writeVarInt(encoder: Encoder, num: number): void; +export function _writeVarStringNative(encoder: Encoder, str: string): void; +export function _writeVarStringPolyfill(encoder: Encoder, str: string): void; +export function writeVarString(encoder: Encoder, str: string): void; +export function writeTerminatedString(encoder: Encoder, str: string): void; +export function writeTerminatedUint8Array(encoder: Encoder, buf: Uint8Array): void; +export function writeBinaryEncoder(encoder: Encoder, append: Encoder): void; +export function writeUint8Array(encoder: Encoder, uint8Array: Uint8Array): void; +export function writeVarUint8Array(encoder: Encoder, uint8Array: Uint8Array): void; +export function writeOnDataView(encoder: Encoder, len: number): DataView; +export function writeFloat32(encoder: Encoder, num: number): void; +export function writeFloat64(encoder: Encoder, num: number): void; +export function writeBigInt64(encoder: Encoder, num: bigint): any; +export function writeBigUint64(encoder: Encoder, num: bigint): any; +export function writeAny(encoder: Encoder, data: undefined | null | number | bigint | boolean | string | { + [x: string]: any; +} | Array | Uint8Array): void; +/** + * Now come a few stateful encoder that have their own classes. + */ +/** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ +export class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor(writer: (arg0: Encoder, arg1: T) => void); + /** + * The writer + */ + w: (arg0: Encoder, arg1: T) => void; + /** + * Current state + * @type {T|null} + */ + s: T | null; + count: number; + /** + * @param {T} v + */ + write(v: T): void; +} +/** + * Basic diff decoder using variable length encoding. + * + * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt. + */ +export class IntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor(start: number); + /** + * Current state + * @type {number} + */ + s: number; + /** + * @param {number} v + */ + write(v: number): void; +} +/** + * A combination of IntDiffEncoder and RleEncoder. + * + * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding. + * + * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5]) + */ +export class RleIntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor(start: number); + /** + * Current state + * @type {number} + */ + s: number; + count: number; + /** + * @param {number} v + */ + write(v: number): void; +} +/** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ +export class UintOptRleEncoder { + encoder: Encoder; + /** + * @type {number} + */ + s: number; + count: number; + /** + * @param {number} v + */ + write(v: number): void; + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array(): Uint8Array; +} +/** + * Increasing Uint Optimized RLE Encoder + * + * The RLE encoder counts the number of same occurences of the same value. + * The IncUintOptRle encoder counts if the value increases. + * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded + * as [1, 3, 5]. + */ +export class IncUintOptRleEncoder { + encoder: Encoder; + /** + * @type {number} + */ + s: number; + count: number; + /** + * @param {number} v + */ + write(v: number): void; + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array(): Uint8Array; +} +/** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ +export class IntDiffOptRleEncoder { + encoder: Encoder; + /** + * @type {number} + */ + s: number; + count: number; + diff: number; + /** + * @param {number} v + */ + write(v: number): void; + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array(): Uint8Array; +} +/** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ +export class StringEncoder { + /** + * @type {Array} + */ + sarr: Array; + s: string; + lensE: UintOptRleEncoder; + /** + * @param {string} string + */ + write(string: string): void; + toUint8Array(): Uint8Array; +} +//# sourceMappingURL=encoding.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/encoding.d.ts.map b/nodejs/node_modules/lib0/encoding.d.ts.map new file mode 100644 index 00000000..f12d8b32 --- /dev/null +++ b/nodejs/node_modules/lib0/encoding.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["encoding.js"],"names":[],"mappings":"AAkCA;;GAEG;AACH;IAEI,aAAa;IACb,iBAA+B;IAC/B;;OAEG;IACH,MAFU,MAAM,UAAU,CAAC,CAEb;CAEjB;AAMM,iCAFK,OAAO,CAE6B;AAKzC,iCAFa,OAAO,KAAE,IAAI,cAMhC;AASM,gCAHI,OAAO,GACN,MAAM,CAQjB;AASM,oCAHI,OAAO,GACN,OAAO,CAE6D;AASzE,sCAHI,OAAO,GACN,UAAU,CAYrB;AASM,mCAHI,OAAO,OACP,MAAM,QAShB;AASM,+BAHI,OAAO,OACP,MAAM,QAUhB;AAWM,6BAJI,OAAO,OACP,MAAM,OACN,MAAM,QAkBhB;AAnCM,oCAHI,OAAO,OACP,MAAM,QAUhB;AAWM,kCAJI,OAAO,OACP,MAAM,OACN,MAAM,QAkBhB;AA4BM,qCAHI,OAAO,OACP,MAAM,QAKhB;AASM,mCAJI,OAAO,OACP,MAAM,OACN,MAAM,QAKhB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;;;;GAMG;AACH;IACE;;OAEG;IACH,mBAFW,MAAM,EAUhB;IANC;;;OAGG;IACH,GAFU,MAAM,CAEF;IACd,cAAc;IAGhB;;OAEG;IACH,SAFW,MAAM,QAehB;CACF;AAiBD;;;;;;;GAOG;AACH;IAEI,iBAA4B;IAC5B;;OAEG;IACH,GAFU,MAAM,CAEN;IACV,cAAc;IAGhB;;OAEG;IACH,SAFW,MAAM,QAUhB;IAED;;;;OAIG;IACH,2BAGC;CACF;AAED;;;;;;;GAOG;AACH;IAEI,iBAA4B;IAC5B;;OAEG;IACH,GAFU,MAAM,CAEN;IACV,cAAc;IAGhB;;OAEG;IACH,SAFW,MAAM,QAUhB;IAED;;;;OAIG;IACH,2BAGC;CACF;AAoBD;;;;;;;;;;;;;;;;GAgBG;AACH;IAEI,iBAA4B;IAC5B;;OAEG;IACH,GAFU,MAAM,CAEN;IACV,cAAc;IACd,aAAa;IAGf;;OAEG;IACH,SAFW,MAAM,QAYhB;IAED;;;;OAIG;IACH,2BAGC;CACF;AAED;;;;;;;;;GASG;AACH;IAEI;;OAEG;IACH,MAFU,MAAM,MAAM,CAAC,CAET;IACd,UAAW;IACX,yBAAoC;IAGtC;;OAEG;IACH,cAFW,MAAM,QAShB;IAED,2BAOC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/encoding.js b/nodejs/node_modules/lib0/encoding.js new file mode 100644 index 00000000..78ecea70 --- /dev/null +++ b/nodejs/node_modules/lib0/encoding.js @@ -0,0 +1,930 @@ +/** + * Efficient schema-less binary encoding with support for variable length encoding. + * + * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module encoding + */ + +import * as math from './math.js' +import * as number from './number.js' +import * as binary from './binary.js' +import * as string from './string.js' +import * as array from './array.js' + +/** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ +export class Encoder { + constructor () { + this.cpos = 0 + this.cbuf = new Uint8Array(100) + /** + * @type {Array} + */ + this.bufs = [] + } +} + +/** + * @function + * @return {Encoder} + */ +export const createEncoder = () => new Encoder() + +/** + * @param {function(Encoder):void} f + */ +export const encode = (f) => { + const encoder = createEncoder() + f(encoder) + return toUint8Array(encoder) +} + +/** + * The current length of the encoded data. + * + * @function + * @param {Encoder} encoder + * @return {number} + */ +export const length = encoder => { + let len = encoder.cpos + for (let i = 0; i < encoder.bufs.length; i++) { + len += encoder.bufs[i].length + } + return len +} + +/** + * Check whether encoder is empty. + * + * @function + * @param {Encoder} encoder + * @return {boolean} + */ +export const hasContent = encoder => encoder.cpos > 0 || encoder.bufs.length > 0 + +/** + * Transform to Uint8Array. + * + * @function + * @param {Encoder} encoder + * @return {Uint8Array} The created ArrayBuffer. + */ +export const toUint8Array = encoder => { + const uint8arr = new Uint8Array(length(encoder)) + let curPos = 0 + for (let i = 0; i < encoder.bufs.length; i++) { + const d = encoder.bufs[i] + uint8arr.set(d, curPos) + curPos += d.length + } + uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos) + return uint8arr +} + +/** + * Verify that it is possible to write `len` bytes wtihout checking. If + * necessary, a new Buffer with the required length is attached. + * + * @param {Encoder} encoder + * @param {number} len + */ +export const verifyLen = (encoder, len) => { + const bufferLen = encoder.cbuf.length + if (bufferLen - encoder.cpos < len) { + encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos)) + encoder.cbuf = new Uint8Array(math.max(bufferLen, len) * 2) + encoder.cpos = 0 + } +} + +/** + * Write one byte to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {number} num The byte that is to be encoded. + */ +export const write = (encoder, num) => { + const bufferLen = encoder.cbuf.length + if (encoder.cpos === bufferLen) { + encoder.bufs.push(encoder.cbuf) + encoder.cbuf = new Uint8Array(bufferLen * 2) + encoder.cpos = 0 + } + encoder.cbuf[encoder.cpos++] = num +} + +/** + * Write one byte at a specific position. + * Position must already be written (i.e. encoder.length > pos) + * + * @function + * @param {Encoder} encoder + * @param {number} pos Position to which to write data + * @param {number} num Unsigned 8-bit integer + */ +export const set = (encoder, pos, num) => { + let buffer = null + // iterate all buffers and adjust position + for (let i = 0; i < encoder.bufs.length && buffer === null; i++) { + const b = encoder.bufs[i] + if (pos < b.length) { + buffer = b // found buffer + } else { + pos -= b.length + } + } + if (buffer === null) { + // use current buffer + buffer = encoder.cbuf + } + buffer[pos] = num +} + +/** + * Write one byte as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +export const writeUint8 = write + +/** + * Write one byte as an unsigned Integer at a specific location. + * + * @function + * @param {Encoder} encoder + * @param {number} pos The location where the data will be written. + * @param {number} num The number that is to be encoded. + */ +export const setUint8 = set + +/** + * Write two bytes as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +export const writeUint16 = (encoder, num) => { + write(encoder, num & binary.BITS8) + write(encoder, (num >>> 8) & binary.BITS8) +} +/** + * Write two bytes as an unsigned integer at a specific location. + * + * @function + * @param {Encoder} encoder + * @param {number} pos The location where the data will be written. + * @param {number} num The number that is to be encoded. + */ +export const setUint16 = (encoder, pos, num) => { + set(encoder, pos, num & binary.BITS8) + set(encoder, pos + 1, (num >>> 8) & binary.BITS8) +} + +/** + * Write two bytes as an unsigned integer + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +export const writeUint32 = (encoder, num) => { + for (let i = 0; i < 4; i++) { + write(encoder, num & binary.BITS8) + num >>>= 8 + } +} + +/** + * Write two bytes as an unsigned integer in big endian order. + * (most significant byte first) + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +export const writeUint32BigEndian = (encoder, num) => { + for (let i = 3; i >= 0; i--) { + write(encoder, (num >>> (8 * i)) & binary.BITS8) + } +} + +/** + * Write two bytes as an unsigned integer at a specific location. + * + * @function + * @param {Encoder} encoder + * @param {number} pos The location where the data will be written. + * @param {number} num The number that is to be encoded. + */ +export const setUint32 = (encoder, pos, num) => { + for (let i = 0; i < 4; i++) { + set(encoder, pos + i, num & binary.BITS8) + num >>>= 8 + } +} + +/** + * Write a variable length unsigned integer. Max encodable integer is 2^53. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +export const writeVarUint = (encoder, num) => { + while (num > binary.BITS7) { + write(encoder, binary.BIT8 | (binary.BITS7 & num)) + num = math.floor(num / 128) // shift >>> 7 + } + write(encoder, binary.BITS7 & num) +} + +/** + * Write a variable length integer. + * + * We use the 7th bit instead for signaling that this is a negative number. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +export const writeVarInt = (encoder, num) => { + const isNegative = math.isNegativeZero(num) + if (isNegative) { + num = -num + } + // |- whether to continue reading |- whether is negative |- number + write(encoder, (num > binary.BITS6 ? binary.BIT8 : 0) | (isNegative ? binary.BIT7 : 0) | (binary.BITS6 & num)) + num = math.floor(num / 64) // shift >>> 6 + // We don't need to consider the case of num === 0 so we can use a different + // pattern here than above. + while (num > 0) { + write(encoder, (num > binary.BITS7 ? binary.BIT8 : 0) | (binary.BITS7 & num)) + num = math.floor(num / 128) // shift >>> 7 + } +} + +/** + * A cache to store strings temporarily + */ +const _strBuffer = new Uint8Array(30000) +const _maxStrBSize = _strBuffer.length / 3 + +/** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +export const _writeVarStringNative = (encoder, str) => { + if (str.length < _maxStrBSize) { + // We can encode the string into the existing buffer + /* c8 ignore next */ + const written = string.utf8TextEncoder.encodeInto(str, _strBuffer).written || 0 + writeVarUint(encoder, written) + for (let i = 0; i < written; i++) { + write(encoder, _strBuffer[i]) + } + } else { + writeVarUint8Array(encoder, string.encodeUtf8(str)) + } +} + +/** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +export const _writeVarStringPolyfill = (encoder, str) => { + const encodedString = unescape(encodeURIComponent(str)) + const len = encodedString.length + writeVarUint(encoder, len) + for (let i = 0; i < len; i++) { + write(encoder, /** @type {number} */ (encodedString.codePointAt(i))) + } +} + +/** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +/* c8 ignore next */ +export const writeVarString = (string.utf8TextEncoder && /** @type {any} */ (string.utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill + +/** + * Write a string terminated by a special byte sequence. This is not very performant and is + * generally discouraged. However, the resulting byte arrays are lexiographically ordered which + * makes this a nice feature for databases. + * + * The string will be encoded using utf8 and then terminated and escaped using writeTerminatingUint8Array. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ +export const writeTerminatedString = (encoder, str) => + writeTerminatedUint8Array(encoder, string.encodeUtf8(str)) + +/** + * Write a terminating Uint8Array. Note that this is not performant and is generally + * discouraged. There are few situations when this is needed. + * + * We use 0x0 as a terminating character. 0x1 serves as an escape character for 0x0 and 0x1. + * + * Example: [0,1,2] is encoded to [1,0,1,1,2,0]. 0x0, and 0x1 needed to be escaped using 0x1. Then + * the result is terminated using the 0x0 character. + * + * This is basically how many systems implement null terminated strings. However, we use an escape + * character 0x1 to avoid issues and potenial attacks on our database (if this is used as a key + * encoder for NoSql databases). + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} buf The string that is to be encoded. + */ +export const writeTerminatedUint8Array = (encoder, buf) => { + for (let i = 0; i < buf.length; i++) { + const b = buf[i] + if (b === 0 || b === 1) { + write(encoder, 1) + } + write(encoder, buf[i]) + } + write(encoder, 0) +} + +/** + * Write the content of another Encoder. + * + * @TODO: can be improved! + * - Note: Should consider that when appending a lot of small Encoders, we should rather clone than referencing the old structure. + * Encoders start with a rather big initial buffer. + * + * @function + * @param {Encoder} encoder The enUint8Arr + * @param {Encoder} append The BinaryEncoder to be written. + */ +export const writeBinaryEncoder = (encoder, append) => writeUint8Array(encoder, toUint8Array(append)) + +/** + * Append fixed-length Uint8Array to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ +export const writeUint8Array = (encoder, uint8Array) => { + const bufferLen = encoder.cbuf.length + const cpos = encoder.cpos + const leftCopyLen = math.min(bufferLen - cpos, uint8Array.length) + const rightCopyLen = uint8Array.length - leftCopyLen + encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos) + encoder.cpos += leftCopyLen + if (rightCopyLen > 0) { + // Still something to write, write right half.. + // Append new buffer + encoder.bufs.push(encoder.cbuf) + // must have at least size of remaining buffer + encoder.cbuf = new Uint8Array(math.max(bufferLen * 2, rightCopyLen)) + // copy array + encoder.cbuf.set(uint8Array.subarray(leftCopyLen)) + encoder.cpos = rightCopyLen + } +} + +/** + * Append an Uint8Array to Encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ +export const writeVarUint8Array = (encoder, uint8Array) => { + writeVarUint(encoder, uint8Array.byteLength) + writeUint8Array(encoder, uint8Array) +} + +/** + * Create an DataView of the next `len` bytes. Use it to write data after + * calling this function. + * + * ```js + * // write float32 using DataView + * const dv = writeOnDataView(encoder, 4) + * dv.setFloat32(0, 1.1) + * // read float32 using DataView + * const dv = readFromDataView(encoder, 4) + * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result) + * ``` + * + * @param {Encoder} encoder + * @param {number} len + * @return {DataView} + */ +export const writeOnDataView = (encoder, len) => { + verifyLen(encoder, len) + const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len) + encoder.cpos += len + return dview +} + +/** + * @param {Encoder} encoder + * @param {number} num + */ +export const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false) + +/** + * @param {Encoder} encoder + * @param {number} num + */ +export const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false) + +/** + * @param {Encoder} encoder + * @param {bigint} num + */ +export const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false) + +/** + * @param {Encoder} encoder + * @param {bigint} num + */ +export const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false) + +const floatTestBed = new DataView(new ArrayBuffer(4)) +/** + * Check if a number can be encoded as a 32 bit float. + * + * @param {number} num + * @return {boolean} + */ +const isFloat32 = num => { + floatTestBed.setFloat32(0, num) + return floatTestBed.getFloat32(0) === num +} + +/** + * Encode data with efficient binary format. + * + * Differences to JSON: + * • Transforms data to a binary format (not to a string) + * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON) + * • Numbers are efficiently encoded either as a variable length integer, as a + * 32 bit float, as a 64 bit float, or as a 64 bit bigint. + * + * Encoding table: + * + * | Data Type | Prefix | Encoding Method | Comment | + * | ------------------- | -------- | ------------------ | ------- | + * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined | + * | null | 126 | | | + * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers | + * | float32 | 124 | writeFloat32 | | + * | float64 | 123 | writeFloat64 | | + * | bigint | 122 | writeBigInt64 | | + * | boolean (false) | 121 | | True and false are different data types so we save the following byte | + * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false | + * | string | 119 | writeVarString | | + * | object | 118 | custom | Writes {length} then {length} key-value pairs | + * | array | 117 | custom | Writes {length} then {length} json values | + * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data | + * + * Reasons for the decreasing prefix: + * We need the first bit for extendability (later we may want to encode the + * prefix with writeVarUint). The remaining 7 bits are divided as follows: + * [0-30] the beginning of the data range is used for custom purposes + * (defined by the function that uses this library) + * [31-127] the end of the data range is used for data encoding by + * lib0/encoding.js + * + * @param {Encoder} encoder + * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data + */ +export const writeAny = (encoder, data) => { + switch (typeof data) { + case 'string': + // TYPE 119: STRING + write(encoder, 119) + writeVarString(encoder, data) + break + case 'number': + if (number.isInteger(data) && math.abs(data) <= binary.BITS31) { + // TYPE 125: INTEGER + write(encoder, 125) + writeVarInt(encoder, data) + } else if (isFloat32(data)) { + // TYPE 124: FLOAT32 + write(encoder, 124) + writeFloat32(encoder, data) + } else { + // TYPE 123: FLOAT64 + write(encoder, 123) + writeFloat64(encoder, data) + } + break + case 'bigint': + // TYPE 122: BigInt + write(encoder, 122) + writeBigInt64(encoder, data) + break + case 'object': + if (data === null) { + // TYPE 126: null + write(encoder, 126) + } else if (array.isArray(data)) { + // TYPE 117: Array + write(encoder, 117) + writeVarUint(encoder, data.length) + for (let i = 0; i < data.length; i++) { + writeAny(encoder, data[i]) + } + } else if (data instanceof Uint8Array) { + // TYPE 116: ArrayBuffer + write(encoder, 116) + writeVarUint8Array(encoder, data) + } else { + // TYPE 118: Object + write(encoder, 118) + const keys = Object.keys(data) + writeVarUint(encoder, keys.length) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + writeVarString(encoder, key) + writeAny(encoder, data[key]) + } + } + break + case 'boolean': + // TYPE 120/121: boolean (true/false) + write(encoder, data ? 120 : 121) + break + default: + // TYPE 127: undefined + write(encoder, 127) + } +} + +/** + * Now come a few stateful encoder that have their own classes. + */ + +/** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ +export class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor (writer) { + super() + /** + * The writer + */ + this.w = writer + /** + * Current state + * @type {T|null} + */ + this.s = null + this.count = 0 + } + + /** + * @param {T} v + */ + write (v) { + if (this.s === v) { + this.count++ + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1 + // write first value + this.w(this, v) + this.s = v + } + } +} + +/** + * Basic diff decoder using variable length encoding. + * + * Encodes the values [3, 1100, 1101, 1050, 0] to [3, 1097, 1, -51, -1050] using writeVarInt. + */ +export class IntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor (start) { + super() + /** + * Current state + * @type {number} + */ + this.s = start + } + + /** + * @param {number} v + */ + write (v) { + writeVarInt(this, v - this.s) + this.s = v + } +} + +/** + * A combination of IntDiffEncoder and RleEncoder. + * + * Basically first writes the IntDiffEncoder and then counts duplicate diffs using RleEncoding. + * + * Encodes the values [1,1,1,2,3,4,5,6] as [1,1,0,2,1,5] (RLE([1,0,0,1,1,1,1,1]) ⇒ RleIntDiff[1,1,0,2,1,5]) + */ +export class RleIntDiffEncoder extends Encoder { + /** + * @param {number} start + */ + constructor (start) { + super() + /** + * Current state + * @type {number} + */ + this.s = start + this.count = 0 + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v && this.count > 0) { + this.count++ + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1) // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1 + // write first value + writeVarInt(this, v - this.s) + this.s = v + } + } +} + +/** + * @param {UintOptRleEncoder} encoder + */ +const flushUintOptRleEncoder = encoder => { + if (encoder.count > 0) { + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set sign to positive + // case 2: write several values. set sign to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s) + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } +} + +/** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ +export class UintOptRleEncoder { + constructor () { + this.encoder = new Encoder() + /** + * @type {number} + */ + this.s = 0 + this.count = 0 + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v) { + this.count++ + } else { + flushUintOptRleEncoder(this) + this.count = 1 + this.s = v + } + } + + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array () { + flushUintOptRleEncoder(this) + return toUint8Array(this.encoder) + } +} + +/** + * Increasing Uint Optimized RLE Encoder + * + * The RLE encoder counts the number of same occurences of the same value. + * The IncUintOptRle encoder counts if the value increases. + * I.e. 7, 8, 9, 10 will be encoded as [-7, 4]. 1, 3, 5 will be encoded + * as [1, 3, 5]. + */ +export class IncUintOptRleEncoder { + constructor () { + this.encoder = new Encoder() + /** + * @type {number} + */ + this.s = 0 + this.count = 0 + } + + /** + * @param {number} v + */ + write (v) { + if (this.s + this.count === v) { + this.count++ + } else { + flushUintOptRleEncoder(this) + this.count = 1 + this.s = v + } + } + + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array () { + flushUintOptRleEncoder(this) + return toUint8Array(this.encoder) + } +} + +/** + * @param {IntDiffOptRleEncoder} encoder + */ +const flushIntDiffOptRleEncoder = encoder => { + if (encoder.count > 0) { + // 31 bit making up the diff | wether to write the counter + // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1) + const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1) + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set first bit to positive + // case 2: write several values. set first bit to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encodedDiff) + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2) // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } +} + +/** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ +export class IntDiffOptRleEncoder { + constructor () { + this.encoder = new Encoder() + /** + * @type {number} + */ + this.s = 0 + this.count = 0 + this.diff = 0 + } + + /** + * @param {number} v + */ + write (v) { + if (this.diff === v - this.s) { + this.s = v + this.count++ + } else { + flushIntDiffOptRleEncoder(this) + this.count = 1 + this.diff = v - this.s + this.s = v + } + } + + /** + * Flush the encoded state and transform this to a Uint8Array. + * + * Note that this should only be called once. + */ + toUint8Array () { + flushIntDiffOptRleEncoder(this) + return toUint8Array(this.encoder) + } +} + +/** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ +export class StringEncoder { + constructor () { + /** + * @type {Array} + */ + this.sarr = [] + this.s = '' + this.lensE = new UintOptRleEncoder() + } + + /** + * @param {string} string + */ + write (string) { + this.s += string + if (this.s.length > 19) { + this.sarr.push(this.s) + this.s = '' + } + this.lensE.write(string.length) + } + + toUint8Array () { + const encoder = new Encoder() + this.sarr.push(this.s) + this.s = '' + writeVarString(encoder, this.sarr.join('')) + writeUint8Array(encoder, this.lensE.toUint8Array()) + return toUint8Array(encoder) + } +} diff --git a/nodejs/node_modules/lib0/encoding.test.d.ts b/nodejs/node_modules/lib0/encoding.test.d.ts new file mode 100644 index 00000000..83f548f4 --- /dev/null +++ b/nodejs/node_modules/lib0/encoding.test.d.ts @@ -0,0 +1,50 @@ +export function testGolangBinaryEncodingCompatibility(): void; +export function testVerifyLen(): void; +export function testStringEncodingPerformanceNativeVsPolyfill(): void; +export function testDecodingPerformanceNativeVsPolyfill(): void; +export function testStringDecodingPerformance(): void; +export function testAnyEncodeUnknowns(_tc: t.TestCase): void; +export function testAnyEncodeDate(_tc: t.TestCase): void; +export function testEncodeMax32bitUint(_tc: t.TestCase): void; +export function testVarUintEncoding(_tc: t.TestCase): void; +export function testVarIntEncoding(_tc: t.TestCase): void; +export function testRepeatVarUintEncoding(tc: t.TestCase): void; +export function testRepeatVarUintEncoding53bit(tc: t.TestCase): void; +export function testRepeatVarIntEncoding(tc: t.TestCase): void; +export function testRepeatVarIntEncoding53bit(tc: t.TestCase): void; +export function testRepeanntAnyEncoding(tc: t.TestCase): void; +export function testRepeatPeekVarUintEncoding(tc: t.TestCase): void; +export function testRepeatPeekVarIntEncoding(tc: t.TestCase): void; +export function testAnyVsJsonEncoding(tc: t.TestCase): void; +export function testStringEncoding(_tc: t.TestCase): void; +export function testRepeatStringEncoding(tc: t.TestCase): void; +export function testSetMethods(_tc: t.TestCase): void; +export function testRepeatRandomWrites(tc: t.TestCase): void; +export function testWriteUint8ArrayOverflow(_tc: t.TestCase): void; +export function testSetOnOverflow(_tc: t.TestCase): void; +export function testCloneDecoder(_tc: t.TestCase): void; +export function testWriteBinaryEncoder(_tc: t.TestCase): void; +export function testOverflowStringDecoding(tc: t.TestCase): void; +export function testRleEncoder(_tc: t.TestCase): void; +export function testRleIntDiffEncoder(_tc: t.TestCase): void; +export function testUintOptRleEncoder(_tc: t.TestCase): void; +export function testIncUintOptRleEncoder(_tc: t.TestCase): void; +export function testIntDiffRleEncoder(_tc: t.TestCase): void; +export function testIntEncoders(tc: t.TestCase): void; +export function testIntDiffEncoder(_tc: t.TestCase): void; +export function testStringDecoder(tc: t.TestCase): void; +export function testLargeNumberEncoding(tc: t.TestCase): void; +export function testInvalidVarIntEncoding(_tc: t.TestCase): void; +export function testTerminatedEncodering(_tc: t.TestCase): void; +export type EncodingPair = { + read: (arg0: decoding.Decoder) => any; + write: (arg0: encoding.Encoder, arg1: any) => void; + gen: (arg0: prng.PRNG) => any; + compare: (arg0: any, arg1: any) => boolean; + name: string; +}; +import * as t from './testing.js'; +import * as decoding from './decoding.js'; +import * as encoding from './encoding.js'; +import * as prng from './prng.js'; +//# sourceMappingURL=encoding.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/encoding.test.d.ts.map b/nodejs/node_modules/lib0/encoding.test.d.ts.map new file mode 100644 index 00000000..498caabc --- /dev/null +++ b/nodejs/node_modules/lib0/encoding.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encoding.test.d.ts","sourceRoot":"","sources":["encoding.test.js"],"names":[],"mappings":"AA6CO,8DAkCN;AAwCM,sCAQN;AAEM,sEA2CN;AAEM,gEAoDN;AAEM,sDAiDN;AAKM,2CAFI,EAAE,QAAQ,QAYpB;AAKM,uCAFI,EAAE,QAAQ,QAIpB;AAKM,4CAFI,EAAE,QAAQ,QAIpB;AAKM,yCAFI,EAAE,QAAQ,QASpB;AAKM,wCAFI,EAAE,QAAQ,QAUpB;AAKM,8CAFI,EAAE,QAAQ,QAKpB;AAKM,mDAFI,EAAE,QAAQ,QAKpB;AAKM,6CAFI,EAAE,QAAQ,QAKpB;AAKM,kDAFI,EAAE,QAAQ,QAKpB;AAKM,4CAFI,EAAE,QAAQ,QAKpB;AAKM,kDAFI,EAAE,QAAQ,QAKpB;AAKM,iDAFI,EAAE,QAAQ,QAKpB;AAKM,0CAFI,EAAE,QAAQ,QAkBpB;AAKM,wCAFI,EAAE,QAAQ,QAWpB;AAKM,6CAFI,EAAE,QAAQ,QAGqB;AAKnC,oCAFI,EAAE,QAAQ,QAkBpB;AAyCM,2CAFI,EAAE,QAAQ,QAgCpB;AAKM,iDAFI,EAAE,QAAQ,QAiBpB;AAKM,uCAFI,EAAE,QAAQ,QAuBpB;AAKM,sCAFI,EAAE,QAAQ,QAcpB;AAKM,4CAFI,EAAE,QAAQ,QAYpB;AAKM,+CAFI,EAAE,QAAQ,QAapB;AAKM,oCAFI,EAAE,QAAQ,QAkBpB;AAKM,2CAFI,EAAE,QAAQ,QAkBpB;AAKM,2CAFI,EAAE,QAAQ,QAkBpB;AAKM,8CAFI,EAAE,QAAQ,QAkBpB;AAKM,2CAFI,EAAE,QAAQ,QAkBpB;AAKM,oCAFI,EAAE,QAAQ,QAqCpB;AAKM,wCAFI,EAAE,QAAQ,QAYpB;AAKM,sCAFI,EAAE,QAAQ,QAyBpB;AAKM,4CAFI,EAAE,QAAQ,QAyBpB;AAKM,+CAFI,EAAE,QAAQ,QAapB;AAKM,8CAFI,EAAE,QAAQ,QAqBpB;;iBAvZsB,SAAS,OAAO,KAAE,GAAG;kBACrB,SAAS,OAAO,QAAC,GAAG,KAAE,IAAI;gBAC1B,KAAK,IAAI,KAAE,GAAG;oBACd,GAAG,QAAC,GAAG,KAAE,OAAO;UACzB,MAAM;;mBA/cD,cAAc;0BAFP,eAAe;0BADf,eAAe;sBAEnB,WAAW"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/environment.d.ts b/nodejs/node_modules/lib0/environment.d.ts new file mode 100644 index 00000000..d014c146 --- /dev/null +++ b/nodejs/node_modules/lib0/environment.d.ts @@ -0,0 +1,12 @@ +export const isNode: boolean; +export const isBrowser: boolean; +export const isMac: boolean; +export function hasParam(name: string): boolean; +export function getParam(name: string, defaultVal: string): string; +export function getVariable(name: string): string | null; +export function getConf(name: string): string | null; +export function ensureConf(name: string): string; +export function hasConf(name: string): boolean; +export const production: boolean; +export const supportsColor: boolean; +//# sourceMappingURL=environment.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/environment.d.ts.map b/nodejs/node_modules/lib0/environment.d.ts.map new file mode 100644 index 00000000..5fdce41a --- /dev/null +++ b/nodejs/node_modules/lib0/environment.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["environment.js"],"names":[],"mappings":"AAcA,6BAA0N;AAG1N,gCAAoG;AAEpG,4BAES;AAyDF,+BAJI,MAAM,GACL,OAAO,CAGwC;AAQpD,+BALI,MAAM,cACN,MAAM,GACL,MAAM,CAIuB;AAOlC,kCAJI,MAAM,GACL,MAAM,GAAC,IAAI,CAM2C;AAO3D,8BAJI,MAAM,GACL,MAAM,GAAC,IAAI,CAIgC;AAOhD,iCAJI,MAAM,GACL,MAAM,CAOjB;AAOM,8BAJI,MAAM,GACL,OAAO,CAIkC;AAGrD,iCAA+C;AAO/C,oCAKC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/environment.js b/nodejs/node_modules/lib0/environment.js new file mode 100644 index 00000000..94d75e76 --- /dev/null +++ b/nodejs/node_modules/lib0/environment.js @@ -0,0 +1,141 @@ +/** + * Isomorphic module to work access the environment (query params, env variables). + * + * @module map + */ + +import * as map from './map.js' +import * as string from './string.js' +import * as conditions from './conditions.js' +import * as storage from './storage.js' +import * as f from './function.js' + +/* c8 ignore next 2 */ +// @ts-ignore +export const isNode = typeof process !== 'undefined' && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' + +/* c8 ignore next */ +export const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode +/* c8 ignore next 3 */ +export const isMac = typeof navigator !== 'undefined' + ? /Mac/.test(navigator.platform) + : false + +/** + * @type {Map} + */ +let params +const args = [] + +/* c8 ignore start */ +const computeParams = () => { + if (params === undefined) { + if (isNode) { + params = map.create() + const pargs = process.argv + let currParamName = null + for (let i = 0; i < pargs.length; i++) { + const parg = pargs[i] + if (parg[0] === '-') { + if (currParamName !== null) { + params.set(currParamName, '') + } + currParamName = parg + } else { + if (currParamName !== null) { + params.set(currParamName, parg) + currParamName = null + } else { + args.push(parg) + } + } + } + if (currParamName !== null) { + params.set(currParamName, '') + } + // in ReactNative for example this would not be true (unless connected to the Remote Debugger) + } else if (typeof location === 'object') { + params = map.create(); // eslint-disable-next-line no-undef + (location.search || '?').slice(1).split('&').forEach((kv) => { + if (kv.length !== 0) { + const [key, value] = kv.split('=') + params.set(`--${string.fromCamelCase(key, '-')}`, value) + params.set(`-${string.fromCamelCase(key, '-')}`, value) + } + }) + } else { + params = map.create() + } + } + return params +} +/* c8 ignore stop */ + +/** + * @param {string} name + * @return {boolean} + */ +/* c8 ignore next */ +export const hasParam = (name) => computeParams().has(name) + +/** + * @param {string} name + * @param {string} defaultVal + * @return {string} + */ +/* c8 ignore next 2 */ +export const getParam = (name, defaultVal) => + computeParams().get(name) || defaultVal + +/** + * @param {string} name + * @return {string|null} + */ +/* c8 ignore next 4 */ +export const getVariable = (name) => + isNode + ? conditions.undefinedToNull(process.env[name.toUpperCase().replaceAll('-', '_')]) + : conditions.undefinedToNull(storage.varStorage.getItem(name)) + +/** + * @param {string} name + * @return {string|null} + */ +/* c8 ignore next 2 */ +export const getConf = (name) => + computeParams().get('--' + name) || getVariable(name) + +/** + * @param {string} name + * @return {string} + */ +/* c8 ignore next 5 */ +export const ensureConf = (name) => { + const c = getConf(name) + if (c == null) throw new Error(`Expected configuration "${name.toUpperCase().replaceAll('-', '_')}"`) + return c +} + +/** + * @param {string} name + * @return {boolean} + */ +/* c8 ignore next 2 */ +export const hasConf = (name) => + hasParam('--' + name) || getVariable(name) !== null + +/* c8 ignore next */ +export const production = hasConf('production') + +/* c8 ignore next 2 */ +const forceColor = isNode && + f.isOneOf(process.env.FORCE_COLOR, ['true', '1', '2']) + +/* c8 ignore start */ +export const supportsColor = !hasParam('no-colors') && + (!isNode || process.stdout.isTTY || forceColor) && ( + !isNode || hasParam('color') || forceColor || + getVariable('COLORTERM') !== null || + (getVariable('TERM') || '').includes('color') +) +/* c8 ignore stop */ diff --git a/nodejs/node_modules/lib0/error.d.ts b/nodejs/node_modules/lib0/error.d.ts new file mode 100644 index 00000000..9580d419 --- /dev/null +++ b/nodejs/node_modules/lib0/error.d.ts @@ -0,0 +1,4 @@ +export function create(s: string): Error; +export function methodUnimplemented(): never; +export function unexpectedCase(): never; +//# sourceMappingURL=error.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/error.d.ts.map b/nodejs/node_modules/lib0/error.d.ts.map new file mode 100644 index 00000000..8362613f --- /dev/null +++ b/nodejs/node_modules/lib0/error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["error.js"],"names":[],"mappings":"AAWO,0BAJI,MAAM,GACL,KAAK,CAGsB;AAOhC,uCAHK,KAAK,CAKhB;AAOM,kCAHK,KAAK,CAKhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/error.js b/nodejs/node_modules/lib0/error.js new file mode 100644 index 00000000..dedf5a1c --- /dev/null +++ b/nodejs/node_modules/lib0/error.js @@ -0,0 +1,30 @@ +/** + * Error helpers. + * + * @module error + */ + +/** + * @param {string} s + * @return {Error} + */ +/* c8 ignore next */ +export const create = s => new Error(s) + +/** + * @throws {Error} + * @return {never} + */ +/* c8 ignore next 3 */ +export const methodUnimplemented = () => { + throw create('Method unimplemented') +} + +/** + * @throws {Error} + * @return {never} + */ +/* c8 ignore next 3 */ +export const unexpectedCase = () => { + throw create('Unexpected case') +} diff --git a/nodejs/node_modules/lib0/eventloop.d.ts b/nodejs/node_modules/lib0/eventloop.d.ts new file mode 100644 index 00000000..3e704d37 --- /dev/null +++ b/nodejs/node_modules/lib0/eventloop.d.ts @@ -0,0 +1,16 @@ +export function enqueue(f: () => void): void; +export function timeout(timeout: number, callback: Function): TimeoutObject; +export function interval(timeout: number, callback: Function): TimeoutObject; +export const Animation: { + new (timeoutId: number): { + _: number; + destroy(): void; + }; +}; +export function animationFrame(cb: (arg0: number) => void): TimeoutObject; +export function idleCallback(cb: Function): TimeoutObject; +export function createDebouncer(timeout: number): (arg0: () => void) => void; +export type TimeoutObject = { + destroy: Function; +}; +//# sourceMappingURL=eventloop.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/eventloop.d.ts.map b/nodejs/node_modules/lib0/eventloop.d.ts.map new file mode 100644 index 00000000..f85be419 --- /dev/null +++ b/nodejs/node_modules/lib0/eventloop.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eventloop.d.ts","sourceRoot":"","sources":["eventloop.js"],"names":[],"mappings":"AAuBO,iCAFe,IAAI,QAOzB;AA8BM,iCAJI,MAAM,uBAEL,aAAa,CAE+D;AASjF,kCAJI,MAAM,uBAEL,aAAa,CAEkE;AAG3F;oBA9Ba,MAAM;;;;EA8B0G;AAOtH,0CAJa,MAAM,KAAE,IAAI,GACpB,aAAa,CAGmH;AAcrI,4CAJK,aAAa,CAI2G;AAM7H,yCAHI,MAAM,gBACe,IAAI,KAAE,IAAI,CAUzC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/eventloop.js b/nodejs/node_modules/lib0/eventloop.js new file mode 100644 index 00000000..beb9b4a0 --- /dev/null +++ b/nodejs/node_modules/lib0/eventloop.js @@ -0,0 +1,106 @@ +/* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */ + +/** + * Utility module to work with EcmaScript's event loop. + * + * @module eventloop + */ + +/** + * @type {Array} + */ +let queue = [] + +const _runQueue = () => { + for (let i = 0; i < queue.length; i++) { + queue[i]() + } + queue = [] +} + +/** + * @param {function():void} f + */ +export const enqueue = f => { + queue.push(f) + if (queue.length === 1) { + setTimeout(_runQueue, 0) + } +} + +/** + * @typedef {Object} TimeoutObject + * @property {function} TimeoutObject.destroy + */ + +/** + * @param {function(number):void} clearFunction + */ +const createTimeoutClass = clearFunction => class TT { + /** + * @param {number} timeoutId + */ + constructor (timeoutId) { + this._ = timeoutId + } + + destroy () { + clearFunction(this._) + } +} + +const Timeout = createTimeoutClass(clearTimeout) + +/** + * @param {number} timeout + * @param {function} callback + * @return {TimeoutObject} + */ +export const timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout)) + +const Interval = createTimeoutClass(clearInterval) + +/** + * @param {number} timeout + * @param {function} callback + * @return {TimeoutObject} + */ +export const interval = (timeout, callback) => new Interval(setInterval(callback, timeout)) + +/* c8 ignore next */ +export const Animation = createTimeoutClass(arg => typeof requestAnimationFrame !== 'undefined' && cancelAnimationFrame(arg)) + +/** + * @param {function(number):void} cb + * @return {TimeoutObject} + */ +/* c8 ignore next */ +export const animationFrame = cb => typeof requestAnimationFrame === 'undefined' ? timeout(0, cb) : new Animation(requestAnimationFrame(cb)) + +/* c8 ignore next */ +// @ts-ignore +const Idle = createTimeoutClass(arg => typeof cancelIdleCallback !== 'undefined' && cancelIdleCallback(arg)) + +/** + * Note: this is experimental and is probably only useful in browsers. + * + * @param {function} cb + * @return {TimeoutObject} + */ +/* c8 ignore next 2 */ +// @ts-ignore +export const idleCallback = cb => typeof requestIdleCallback !== 'undefined' ? new Idle(requestIdleCallback(cb)) : timeout(1000, cb) + +/** + * @param {number} timeout Timeout of the debounce action + * @return {function(function():void):void} + */ +export const createDebouncer = timeout => { + let timer = -1 + return f => { + clearTimeout(timer) + if (f) { + timer = /** @type {any} */ (setTimeout(f, timeout)) + } + } +} diff --git a/nodejs/node_modules/lib0/eventloop.test.d.ts b/nodejs/node_modules/lib0/eventloop.test.d.ts new file mode 100644 index 00000000..27f4ab96 --- /dev/null +++ b/nodejs/node_modules/lib0/eventloop.test.d.ts @@ -0,0 +1,8 @@ +export function testEventloopOrder(_tc: t.TestCase): Promise<[void, void]>; +export function testTimeout(_tc: t.TestCase): Promise; +export function testInterval(_tc: t.TestCase): Promise; +export function testAnimationFrame(_tc: t.TestCase): Promise; +export function testIdleCallback(_tc: t.TestCase): Promise; +export function testDebouncer(_tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=eventloop.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/eventloop.test.d.ts.map b/nodejs/node_modules/lib0/eventloop.test.d.ts.map new file mode 100644 index 00000000..2734062e --- /dev/null +++ b/nodejs/node_modules/lib0/eventloop.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eventloop.test.d.ts","sourceRoot":"","sources":["eventloop.test.js"],"names":[],"mappings":"AAOO,wCAFI,EAAE,QAAQ,yBAkBpB;AAKM,iCAFI,EAAE,QAAQ,iBAYpB;AAKM,kCAFI,EAAE,QAAQ,iBAepB;AAKM,wCAFI,EAAE,QAAQ,iBAOpB;AAKM,sCAFI,EAAE,QAAQ,iBAMpB;AAKM,mCAFI,EAAE,QAAQ,iBAcpB;mBA3FkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/function.d.ts b/nodejs/node_modules/lib0/function.d.ts new file mode 100644 index 00000000..bf9af1ee --- /dev/null +++ b/nodejs/node_modules/lib0/function.d.ts @@ -0,0 +1,14 @@ +export function callAll(fs: Array, args: Array, i?: number): void; +export function nop(): void; +export function apply(f: () => T): T; +export function id(a: A): A; +export function equalityStrict(a: T, b: T): boolean; +export function equalityFlat(a: object | T[], b: object | T[]): boolean; +export function equalityDeep(a: any, b: any): boolean; +export function isOneOf(value: V, options: OPTS[]): boolean; +export const isArray: (arg: any) => arg is any[]; +export function isString(s: any): s is string; +export function isNumber(n: any): n is number; +export function is any>(n: any, T: TYPE): n is InstanceType; +export function isTemplate any>(T: TYPE): (n: any) => n is InstanceType; +//# sourceMappingURL=function.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/function.d.ts.map b/nodejs/node_modules/lib0/function.d.ts.map new file mode 100644 index 00000000..eefe6a16 --- /dev/null +++ b/nodejs/node_modules/lib0/function.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"function.d.ts","sourceRoot":"","sources":["function.js"],"names":[],"mappings":"AAeO,4BAHI,eAAe,QACf,MAAM,GAAG,CAAC,oBAYpB;AAEM,4BAAoB;AAOpB,wCAAsB;AAQtB,+BAAiB;AASjB,+CAFK,OAAO,CAE4B;AASxC,mEAFK,OAAO,CAEyN;AASrO,gCAJI,GAAG,KACH,GAAG,GACF,OAAO,CA0ElB;AAUM,+EAA2D;AAGlE,iDAAoC;AAM7B,4BAHI,GAAG,eAG8C;AAMrD,4BAHI,GAAG,eAGoD;AAQ3D,uDAL8B,GAAG,KAAK,GAAG,KACrC,GAAG,oCAIsC;AAM7C,+DAH8B,GAAG,KAAK,GAAG,gBAKnC,GAAG,6BAGe"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/function.js b/nodejs/node_modules/lib0/function.js new file mode 100644 index 00000000..2f2f7f4c --- /dev/null +++ b/nodejs/node_modules/lib0/function.js @@ -0,0 +1,186 @@ +/** + * Common functions and function call helpers. + * + * @module function + */ + +import * as array from './array.js' +import * as object from './object.js' + +/** + * Calls all functions in `fs` with args. Only throws after all functions were called. + * + * @param {Array} fs + * @param {Array} args + */ +export const callAll = (fs, args, i = 0) => { + try { + for (; i < fs.length; i++) { + fs[i](...args) + } + } finally { + if (i < fs.length) { + callAll(fs, args, i + 1) + } + } +} + +export const nop = () => {} + +/** + * @template T + * @param {function():T} f + * @return {T} + */ +export const apply = f => f() + +/** + * @template A + * + * @param {A} a + * @return {A} + */ +export const id = a => a + +/** + * @template T + * + * @param {T} a + * @param {T} b + * @return {boolean} + */ +export const equalityStrict = (a, b) => a === b + +/** + * @template T + * + * @param {Array|object} a + * @param {Array|object} b + * @return {boolean} + */ +export const equalityFlat = (a, b) => a === b || (a != null && b != null && a.constructor === b.constructor && ((array.isArray(a) && array.equalFlat(a, /** @type {Array} */ (b))) || (typeof a === 'object' && object.equalFlat(a, b)))) + +/* c8 ignore start */ + +/** + * @param {any} a + * @param {any} b + * @return {boolean} + */ +export const equalityDeep = (a, b) => { + if (a == null || b == null) { + return equalityStrict(a, b) + } + if (a.constructor !== b.constructor) { + return false + } + if (a === b) { + return true + } + switch (a.constructor) { + case ArrayBuffer: + a = new Uint8Array(a) + b = new Uint8Array(b) + // eslint-disable-next-line no-fallthrough + case Uint8Array: { + if (a.byteLength !== b.byteLength) { + return false + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false + } + } + break + } + case Set: { + if (a.size !== b.size) { + return false + } + for (const value of a) { + if (!b.has(value)) { + return false + } + } + break + } + case Map: { + if (a.size !== b.size) { + return false + } + for (const key of a.keys()) { + if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) { + return false + } + } + break + } + case Object: + if (object.length(a) !== object.length(b)) { + return false + } + for (const key in a) { + if (!object.hasProperty(a, key) || !equalityDeep(a[key], b[key])) { + return false + } + } + break + case Array: + if (a.length !== b.length) { + return false + } + for (let i = 0; i < a.length; i++) { + if (!equalityDeep(a[i], b[i])) { + return false + } + } + break + default: + return false + } + return true +} + +/** + * @template V + * @template {V} OPTS + * + * @param {V} value + * @param {Array} options + */ +// @ts-ignore +export const isOneOf = (value, options) => options.includes(value) +/* c8 ignore stop */ + +export const isArray = array.isArray + +/** + * @param {any} s + * @return {s is String} + */ +export const isString = (s) => s && s.constructor === String + +/** + * @param {any} n + * @return {n is Number} + */ +export const isNumber = n => n != null && n.constructor === Number + +/** + * @template {abstract new (...args: any) => any} TYPE + * @param {any} n + * @param {TYPE} T + * @return {n is InstanceType} + */ +export const is = (n, T) => n && n.constructor === T + +/** + * @template {abstract new (...args: any) => any} TYPE + * @param {TYPE} T + */ +export const isTemplate = (T) => + /** + * @param {any} n + * @return {n is InstanceType} + **/ + n => n && n.constructor === T diff --git a/nodejs/node_modules/lib0/function.test.d.ts b/nodejs/node_modules/lib0/function.test.d.ts new file mode 100644 index 00000000..8d7b2775 --- /dev/null +++ b/nodejs/node_modules/lib0/function.test.d.ts @@ -0,0 +1,5 @@ +export function testBasics(_tc: t.TestCase): void; +export function testCallAll(_tc: t.TestCase): void; +export function testDeepEquality(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=function.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/function.test.d.ts.map b/nodejs/node_modules/lib0/function.test.d.ts.map new file mode 100644 index 00000000..d599e7d5 --- /dev/null +++ b/nodejs/node_modules/lib0/function.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"function.test.d.ts","sourceRoot":"","sources":["function.test.js"],"names":[],"mappings":"AAMO,gCAFI,EAAE,QAAQ,QA+CpB;AAKM,iCAFI,EAAE,QAAQ,QAuBpB;AAKM,sCAFI,EAAE,QAAQ,QAkEpB;mBAjJkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.d.ts b/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.d.ts new file mode 100644 index 00000000..fa8f26c1 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.d.ts @@ -0,0 +1,45 @@ +/** + * This is a GF2 Polynomial abstraction that is not meant for production! + * + * It is easy to understand and it's correctness is as obvious as possible. It can be used to verify + * efficient implementations of algorithms on GF2. + */ +export class GF2Polynomial { + /** + * @type {Set} + */ + degrees: Set; +} +export function createFromBytes(bytes: Uint8Array): GF2Polynomial; +export function toUint8Array(p: GF2Polynomial, byteLength?: number): Uint8Array; +export function createFromUint(uint: number): GF2Polynomial; +export function createRandom(degree: number): GF2Polynomial; +export function getHighestDegree(p: GF2Polynomial): number; +export function addInto(p1: GF2Polynomial, p2: GF2Polynomial): void; +export function orInto(p1: GF2Polynomial, p2: GF2Polynomial): void; +export function add(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function clone(p: GF2Polynomial): GF2Polynomial; +export function addDegreeInto(p: GF2Polynomial, degree: number): void; +export function multiply(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function shiftLeft(p: GF2Polynomial, shift: number): GF2Polynomial; +export function mod(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function modPow(p: GF2Polynomial, e: number, m: GF2Polynomial): GF2Polynomial; +export function gcd(p1: GF2Polynomial, p2: GF2Polynomial): GF2Polynomial; +export function equals(p1: GF2Polynomial, p2: GF2Polynomial): boolean; +export function isIrreducibleBenOr(p: GF2Polynomial): boolean; +export function createIrreducible(degree: number): GF2Polynomial; +export function fingerprint(buf: Uint8Array, m: GF2Polynomial): Uint8Array; +export class RabinPolynomialEncoder { + /** + * @param {GF2Polynomial} m The irreducible polynomial + */ + constructor(m: GF2Polynomial); + fingerprint: GF2Polynomial; + m: GF2Polynomial; + /** + * @param {number} b + */ + write(b: number): void; + getFingerprint(): Uint8Array; +} +//# sourceMappingURL=rabin-gf2-polynomial.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.d.ts.map b/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.d.ts.map new file mode 100644 index 00000000..4ea798d0 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin-gf2-polynomial.d.ts","sourceRoot":"","sources":["rabin-gf2-polynomial.js"],"names":[],"mappings":"AAqBA;;;;;GAKG;AACH;IAEI;;QAEI;IACJ,SAFW,IAAI,MAAM,CAAC,CAEE;CAE3B;AAOM,uCAFI,UAAU,iBAcpB;AAQM,gCAHI,aAAa,eACb,MAAM,cAahB;AAOM,qCAFI,MAAM,iBAQhB;AAOM,qCAFI,MAAM,iBAYhB;AAMM,oCAHI,aAAa,UAG2D;AAU5E,4BAHI,aAAa,MACb,aAAa,QAUvB;AAUM,2BAHI,aAAa,MACb,aAAa,QAMvB;AAUM,wBAHI,aAAa,MACb,aAAa,iBAevB;AASM,yBAFI,aAAa,iBAMvB;AAUM,iCAHI,aAAa,UACb,MAAM,QAQhB;AAQM,6BAHI,aAAa,MACb,aAAa,iBAUvB;AAQM,6BAHI,aAAa,SACb,MAAM,iBAShB;AAQM,wBAHI,aAAa,MACb,aAAa,iBAavB;AAWM,0BAJI,aAAa,KACb,MAAM,KACN,aAAa,iBAcvB;AAQM,wBAHI,aAAa,MACb,aAAa,iBASvB;AAQM,2BAHI,aAAa,MACb,aAAa,WAQvB;AAgCM,sCAFI,aAAa,WAYvB;AAKM,0CAFI,MAAM,iBAOhB;AAQM,iCAHI,UAAU,KACV,aAAa,cAE0G;AAElI;IACE;;OAEG;IACH,eAFW,aAAa,EAKvB;IAFC,2BAAsC;IACtC,iBAAU;IAGZ;;OAEG;IACH,SAFW,MAAM,QAOhB;IAED,6BAEC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.js b/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.js new file mode 100644 index 00000000..6ae87b27 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin-gf2-polynomial.js @@ -0,0 +1,379 @@ +/** + * The idea of the Rabin fingerprint algorithm is to represent the binary as a polynomial in a + * finite field (Galois Field G(2)). The polynomial will then be taken "modulo" by an irreducible + * polynomial of the desired size. + * + * This implementation is inefficient and is solely used to verify the actually performant + * implementation in `./rabin.js`. + * + * @module rabin-gf2-polynomial + */ + +import * as math from '../math.js' +import * as webcrypto from 'lib0/webcrypto' +import * as array from '../array.js' +import * as buffer from '../buffer.js' + +/** + * @param {number} degree + */ +const _degreeToMinByteLength = degree => math.floor(degree / 8) + 1 + +/** + * This is a GF2 Polynomial abstraction that is not meant for production! + * + * It is easy to understand and it's correctness is as obvious as possible. It can be used to verify + * efficient implementations of algorithms on GF2. + */ +export class GF2Polynomial { + constructor () { + /** + * @type {Set} + */ + this.degrees = new Set() + } +} + +/** + * From Uint8Array (MSB). + * + * @param {Uint8Array} bytes + */ +export const createFromBytes = bytes => { + const p = new GF2Polynomial() + for (let bsi = bytes.length - 1, currDegree = 0; bsi >= 0; bsi--) { + const currByte = bytes[bsi] + for (let i = 0; i < 8; i++) { + if (((currByte >>> i) & 1) === 1) { + p.degrees.add(currDegree) + } + currDegree++ + } + } + return p +} + +/** + * Transform to Uint8Array (MSB). + * + * @param {GF2Polynomial} p + * @param {number} byteLength + */ +export const toUint8Array = (p, byteLength = _degreeToMinByteLength(getHighestDegree(p))) => { + const buf = buffer.createUint8ArrayFromLen(byteLength) + /** + * @param {number} i + */ + const setBit = i => { + const bi = math.floor(i / 8) + buf[buf.length - 1 - bi] |= (1 << (i % 8)) + } + p.degrees.forEach(setBit) + return buf +} + +/** + * Create from unsigned integer (max 32bit uint) - read most-significant-byte first. + * + * @param {number} uint + */ +export const createFromUint = uint => { + const buf = new Uint8Array(4) + for (let i = 0; i < 4; i++) { + buf[i] = uint >>> 8 * (3 - i) + } + return createFromBytes(buf) +} + +/** + * Create a random polynomial of a specified degree. + * + * @param {number} degree + */ +export const createRandom = degree => { + const bs = new Uint8Array(_degreeToMinByteLength(degree)) + webcrypto.getRandomValues(bs) + // Get first byte and explicitly set the bit of "degree" to 1 (the result must have the specified + // degree). + const firstByte = bs[0] | 1 << (degree % 8) + // Find out how many bits of the first byte need to be filled with zeros because they are >degree. + const zeros = 7 - (degree % 8) + bs[0] = ((firstByte << zeros) & 0xff) >>> zeros + return createFromBytes(bs) +} + +/** + * @param {GF2Polynomial} p + * @return number + */ +export const getHighestDegree = p => array.fold(array.from(p.degrees), 0, math.max) + +/** + * Add (+) p2 int the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const addInto = (p1, p2) => { + p2.degrees.forEach(degree => { + if (p1.degrees.has(degree)) { + p1.degrees.delete(degree) + } else { + p1.degrees.add(degree) + } + }) +} + +/** + * Or (|) p2 into the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const orInto = (p1, p2) => { + p2.degrees.forEach(degree => { + p1.degrees.add(degree) + }) +} + +/** + * Add (+) p2 to the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const add = (p1, p2) => { + const result = new GF2Polynomial() + p2.degrees.forEach(degree => { + if (!p1.degrees.has(degree)) { + result.degrees.add(degree) + } + }) + p1.degrees.forEach(degree => { + if (!p2.degrees.has(degree)) { + result.degrees.add(degree) + } + }) + return result +} + +/** + * Add (+) p2 to the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p + */ +export const clone = (p) => { + const result = new GF2Polynomial() + p.degrees.forEach(d => result.degrees.add(d)) + return result +} + +/** + * Add (+) p2 to the p1 polynomial. + * + * Addition is defined as xor in F2. Substraction is equivalent to addition in F2. + * + * @param {GF2Polynomial} p + * @param {number} degree + */ +export const addDegreeInto = (p, degree) => { + if (p.degrees.has(degree)) { + p.degrees.delete(degree) + } else { + p.degrees.add(degree) + } +} + +/** + * Multiply (•) p1 with p2 and store the result in p1. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const multiply = (p1, p2) => { + const result = new GF2Polynomial() + p1.degrees.forEach(degree1 => { + p2.degrees.forEach(degree2 => { + addDegreeInto(result, degree1 + degree2) + }) + }) + return result +} + +/** + * Multiply (•) p1 with p2 and store the result in p1. + * + * @param {GF2Polynomial} p + * @param {number} shift + */ +export const shiftLeft = (p, shift) => { + const result = new GF2Polynomial() + p.degrees.forEach(degree => { + const r = degree + shift + r >= 0 && result.degrees.add(r) + }) + return result +} + +/** + * Computes p1 % p2. I.e. the remainder of p1/p2. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const mod = (p1, p2) => { + const maxDeg1 = getHighestDegree(p1) + const maxDeg2 = getHighestDegree(p2) + const result = clone(p1) + for (let i = maxDeg1 - maxDeg2; i >= 0; i--) { + if (result.degrees.has(maxDeg2 + i)) { + const shifted = shiftLeft(p2, i) + addInto(result, shifted) + } + } + return result +} + +/** + * Computes (p^e mod m). + * + * http://en.wikipedia.org/wiki/Modular_exponentiation + * + * @param {GF2Polynomial} p + * @param {number} e + * @param {GF2Polynomial} m + */ +export const modPow = (p, e, m) => { + let result = ONE + while (true) { + if ((e & 1) === 1) { + result = mod(multiply(result, p), m) + } + e >>>= 1 + if (e === 0) { + return result + } + p = mod(multiply(p, p), m) + } +} + +/** + * Find the greatest common divisor using Euclid's Algorithm. + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const gcd = (p1, p2) => { + while (p2.degrees.size > 0) { + const modded = mod(p1, p2) + p1 = p2 + p2 = modded + } + return p1 +} + +/** + * true iff p1 equals p2 + * + * @param {GF2Polynomial} p1 + * @param {GF2Polynomial} p2 + */ +export const equals = (p1, p2) => { + if (p1.degrees.size !== p2.degrees.size) return false + for (const d of p1.degrees) { + if (!p2.degrees.has(d)) return false + } + return true +} + +const X = createFromBytes(new Uint8Array([2])) +const ONE = createFromBytes(new Uint8Array([1])) + +/** + * Computes ( x^(2^p) - x ) mod f + * + * (shamelessly copied from + * https://github.com/opendedup/rabinfingerprint/blob/master/src/org/rabinfingerprint/polynomial/Polynomial.java) + * + * @param {GF2Polynomial} f + * @param {number} p + */ +const reduceExponent = (f, p) => { + // compute (x^q^p mod f) + const q2p = math.pow(2, p) + const x2q2p = modPow(X, q2p, f) + // subtract (x mod f) + return mod(add(x2q2p, X), f) +} + +/** + * BenOr Reducibility Test + * + * Tests and Constructions of Irreducible Polynomials over Finite Fields + * (1997) Shuhong Gao, Daniel Panario + * + * http://citeseer.ist.psu.edu/cache/papers/cs/27167/http:zSzzSzwww.math.clemson.eduzSzfacultyzSzGaozSzpaperszSzGP97a.pdf/gao97tests.pdf + * + * @param {GF2Polynomial} p + */ +export const isIrreducibleBenOr = p => { + const degree = getHighestDegree(p) + for (let i = 1; i < degree / 2; i++) { + const b = reduceExponent(p, i) + const g = gcd(p, b) + if (!equals(g, ONE)) { + return false + } + } + return true +} + +/** + * @param {number} degree + */ +export const createIrreducible = degree => { + while (true) { + const p = createRandom(degree) + if (isIrreducibleBenOr(p)) return p + } +} + +/** + * Create a fingerprint of buf using the irreducible polynomial m. + * + * @param {Uint8Array} buf + * @param {GF2Polynomial} m + */ +export const fingerprint = (buf, m) => toUint8Array(mod(createFromBytes(buf), m), _degreeToMinByteLength(getHighestDegree(m) - 1)) + +export class RabinPolynomialEncoder { + /** + * @param {GF2Polynomial} m The irreducible polynomial + */ + constructor (m) { + this.fingerprint = new GF2Polynomial() + this.m = m + } + + /** + * @param {number} b + */ + write (b) { + const bp = createFromBytes(new Uint8Array([b])) + const fingerprint = shiftLeft(this.fingerprint, 8) + orInto(fingerprint, bp) + this.fingerprint = mod(fingerprint, this.m) + } + + getFingerprint () { + return toUint8Array(this.fingerprint, _degreeToMinByteLength(getHighestDegree(this.m) - 1)) + } +} diff --git a/nodejs/node_modules/lib0/hash/rabin-uncached.d.ts b/nodejs/node_modules/lib0/hash/rabin-uncached.d.ts new file mode 100644 index 00000000..89e5dac0 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin-uncached.d.ts @@ -0,0 +1,29 @@ +export class RabinUncachedEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor(m: Uint8Array); + m: Uint8Array; + blen: number; + bs: Uint8Array; + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + bpos: number; + /** + * Add/Xor/Substract bytes. + * + * Discards bytes that are out of range. + * @todo put this in function or inline + * + * @param {Uint8Array} cs + */ + add(cs: Uint8Array): void; + /** + * @param {number} byte + */ + write(byte: number): void; + getFingerprint(): Uint8Array; +} +//# sourceMappingURL=rabin-uncached.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin-uncached.d.ts.map b/nodejs/node_modules/lib0/hash/rabin-uncached.d.ts.map new file mode 100644 index 00000000..0469e353 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin-uncached.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin-uncached.d.ts","sourceRoot":"","sources":["rabin-uncached.js"],"names":[],"mappings":"AAUA;IACE;;OAEG;IACH,eAFW,UAAU,EAWpB;IARC,cAAU;IACV,aAAwB;IACxB,eAAmC;IACnC;;;OAGG;IACH,aAAa;IAGf;;;;;;;OAOG;IACH,QAFW,UAAU,QAQpB;IAED;;OAEG;IACH,YAFW,MAAM,QAgBhB;IAED,6BAMC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin-uncached.js b/nodejs/node_modules/lib0/hash/rabin-uncached.js new file mode 100644 index 00000000..f40da971 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin-uncached.js @@ -0,0 +1,68 @@ +/** + * It is not recommended to use this package. This is the uncached implementation of the rabin + * fingerprint algorithm. However, it can be used to verify the `rabin.js` implementation. + * + * @module rabin-uncached + */ + +import * as math from '../math.js' +import * as buffer from '../buffer.js' + +export class RabinUncachedEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor (m) { + this.m = m + this.blen = m.byteLength + this.bs = new Uint8Array(this.blen) + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + this.bpos = 0 + } + + /** + * Add/Xor/Substract bytes. + * + * Discards bytes that are out of range. + * @todo put this in function or inline + * + * @param {Uint8Array} cs + */ + add (cs) { + const copyLen = math.min(this.blen, cs.byteLength) + // copy from right to left until max is reached + for (let i = 0; i < copyLen; i++) { + this.bs[(this.bpos + this.blen - i - 1) % this.blen] ^= cs[cs.byteLength - i - 1] + } + } + + /** + * @param {number} byte + */ + write (byte) { + // [0,m1,m2,b] + // x <- bpos + // Shift one byte to the left, add b + this.bs[this.bpos] = byte + this.bpos = (this.bpos + 1) % this.blen + // mod + for (let i = 7; i >= 0; i--) { + if (((this.bs[this.bpos] >>> i) & 1) === 1) { + this.add(buffer.shiftNBitsLeft(this.m, i)) + } + } + // if (this.bs[this.bpos] !== 0) { error.unexpectedCase() } + // assert(this.bs[this.bpos] === 0) + } + + getFingerprint () { + const result = new Uint8Array(this.blen - 1) + for (let i = 0; i < result.byteLength; i++) { + result[i] = this.bs[(this.bpos + i + 1) % this.blen] + } + return result + } +} diff --git a/nodejs/node_modules/lib0/hash/rabin.d.ts b/nodejs/node_modules/lib0/hash/rabin.d.ts new file mode 100644 index 00000000..3e1f578d --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin.d.ts @@ -0,0 +1,27 @@ +export const StandardIrreducible8: Uint8Array; +export const StandardIrreducible16: Uint8Array; +export const StandardIrreducible32: Uint8Array; +export const StandardIrreducible64: Uint8Array; +export const StandardIrreducible128: Uint8Array; +export class RabinEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor(m: Uint8Array); + m: Uint8Array; + blen: number; + bs: Uint8Array; + cache: Uint8Array; + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + bpos: number; + /** + * @param {number} byte + */ + write(byte: number): void; + getFingerprint(): Uint8Array; +} +export function fingerprint(irreducible: Uint8Array, data: Uint8Array): Uint8Array; +//# sourceMappingURL=rabin.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin.d.ts.map b/nodejs/node_modules/lib0/hash/rabin.d.ts.map new file mode 100644 index 00000000..b92f9a38 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin.d.ts","sourceRoot":"","sources":["rabin.js"],"names":[],"mappings":"AAUA,8CAA4D;AAC5D,+CAAkE;AAClE,+CAA4E;AAC5E,+CAA+F;AAC/F,gDAAmI;AAmCnI;IACE;;OAEG;IACH,eAFW,UAAU,EAYpB;IATC,cAAU;IACV,aAAwB;IACxB,eAAmC;IACnC,kBAA2B;IAC3B;;;OAGG;IACH,aAAa;IAGf;;OAEG;IACH,YAFW,MAAM,QAYhB;IAED,6BAMC;CACF;AAMM,yCAHI,UAAU,QACV,UAAU,cAQpB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin.js b/nodejs/node_modules/lib0/hash/rabin.js new file mode 100644 index 00000000..d5690f12 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin.js @@ -0,0 +1,100 @@ +/** + * @module rabin + * + * Very efficient & versatile fingerprint/hashing algorithm. However, it is not cryptographically + * secure. Well suited for fingerprinting. + */ + +import * as buffer from '../buffer.js' +import * as map from '../map.js' + +export const StandardIrreducible8 = new Uint8Array([1, 221]) +export const StandardIrreducible16 = new Uint8Array([1, 244, 157]) +export const StandardIrreducible32 = new Uint8Array([1, 149, 183, 205, 191]) +export const StandardIrreducible64 = new Uint8Array([1, 133, 250, 114, 193, 250, 28, 193, 231]) +export const StandardIrreducible128 = new Uint8Array([1, 94, 109, 166, 228, 6, 222, 102, 239, 27, 128, 184, 13, 50, 112, 169, 199]) + +/** + * Maps from a modulo to the precomputed values. + * + * @type {Map} + */ +const _precomputedFingerprintCache = new Map() + +/** + * @param {Uint8Array} m + */ +const ensureCache = m => map.setIfUndefined(_precomputedFingerprintCache, buffer.toBase64(m), () => { + const byteLen = m.byteLength + const cache = new Uint8Array(256 * byteLen) + // Use dynamic computing to compute the cached results. + // Starting values: cache(0) = 0; cache(1) = m + cache.set(m, byteLen) + for (let bit = 1; bit < 8; bit++) { + const mBitShifted = buffer.shiftNBitsLeft(m, bit) + const bitShifted = 1 << bit + for (let j = 0; j < bitShifted; j++) { + // apply the shifted result (reducing the degree of the polynomial) + const msb = bitShifted | j + const rest = msb ^ mBitShifted[0] + for (let i = 0; i < byteLen; i++) { + // rest is already precomputed in the cache + cache[msb * byteLen + i] = cache[rest * byteLen + i] ^ mBitShifted[i] + } + // if (cache[(bitShifted | j) * byteLen] !== (bitShifted | j)) { error.unexpectedCase() } + } + } + return cache +}) + +export class RabinEncoder { + /** + * @param {Uint8Array} m assert(m[0] === 1) + */ + constructor (m) { + this.m = m + this.blen = m.byteLength + this.bs = new Uint8Array(this.blen) + this.cache = ensureCache(m) + /** + * This describes the position of the most significant byte (starts with 0 and increases with + * shift) + */ + this.bpos = 0 + } + + /** + * @param {number} byte + */ + write (byte) { + // assert(this.bs[0] === 0) + // Shift one byte to the left, add b + this.bs[this.bpos] = byte + this.bpos = (this.bpos + 1) % this.blen + const msb = this.bs[this.bpos] + for (let i = 0; i < this.blen; i++) { + this.bs[(this.bpos + i) % this.blen] ^= this.cache[msb * this.blen + i] + } + // assert(this.bs[this.bpos] === 0) + } + + getFingerprint () { + const result = new Uint8Array(this.blen - 1) + for (let i = 0; i < result.byteLength; i++) { + result[i] = this.bs[(this.bpos + i + 1) % this.blen] + } + return result + } +} + +/** + * @param {Uint8Array} irreducible + * @param {Uint8Array} data + */ +export const fingerprint = (irreducible, data) => { + const encoder = new RabinEncoder(irreducible) + for (let i = 0; i < data.length; i++) { + encoder.write(data[i]) + } + return encoder.getFingerprint() +} diff --git a/nodejs/node_modules/lib0/hash/rabin.test.d.ts b/nodejs/node_modules/lib0/hash/rabin.test.d.ts new file mode 100644 index 00000000..6ed6dd5c --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin.test.d.ts @@ -0,0 +1,8 @@ +export function testPolynomialBasics(_tc: t.TestCase): void; +export function testIrreducibleInput(_tc: t.TestCase): void; +export function testIrreducibleSpread(_tc: t.TestCase): void; +export function testGenerateIrreducibles(_tc: t.TestCase): void; +export function testFingerprintCompatiblity(tc: t.TestCase): void; +export function testConflicts(tc: t.TestCase): void; +import * as t from '../testing.js'; +//# sourceMappingURL=rabin.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/rabin.test.d.ts.map b/nodejs/node_modules/lib0/hash/rabin.test.d.ts.map new file mode 100644 index 00000000..148db8bb --- /dev/null +++ b/nodejs/node_modules/lib0/hash/rabin.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rabin.test.d.ts","sourceRoot":"","sources":["rabin.test.js"],"names":[],"mappings":"AAaO,0CAFI,EAAE,QAAQ,QASpB;AAKM,0CAFI,EAAE,QAAQ,QAapB;AAKM,2CAFI,EAAE,QAAQ,QASpB;AAwBM,8CAFI,EAAE,QAAQ,QAyBpB;AAmGM,gDAFI,EAAE,QAAQ,QAQpB;AAKM,kCAFI,EAAE,QAAQ,QA4BpB;mBAvOkB,eAAe"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/sha256.d.ts b/nodejs/node_modules/lib0/hash/sha256.d.ts new file mode 100644 index 00000000..462cb008 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.d.ts @@ -0,0 +1,2 @@ +export function digest(data: Uint8Array): Uint8Array; +//# sourceMappingURL=sha256.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/sha256.d.ts.map b/nodejs/node_modules/lib0/hash/sha256.d.ts.map new file mode 100644 index 00000000..865d0b2a --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.d.ts","sourceRoot":"","sources":["sha256.js"],"names":[],"mappings":"AA2KO,6BAFI,UAAU,cAEkC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/sha256.js b/nodejs/node_modules/lib0/hash/sha256.js new file mode 100644 index 00000000..88e7e91a --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.js @@ -0,0 +1,172 @@ +/** + * @module sha256 + * Spec: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf + * Resources: + * - https://web.archive.org/web/20150315061807/http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf + */ + +import * as binary from '../binary.js' + +/** + * @param {number} w - a 32bit uint + * @param {number} shift + */ +const rotr = (w, shift) => (w >>> shift) | (w << (32 - shift)) + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sum0to256 = x => rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22) + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sum1to256 = x => rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25) + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sigma0to256 = x => rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3 + +/** + * Helper for SHA-224 & SHA-256. See 4.1.2. + * @param {number} x + */ +const sigma1to256 = x => rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10 + +// @todo don't init these variables globally + +/** + * See 4.2.2: Constant for sha256 & sha224 + * These words represent the first thirty-two bits of the fractional parts of + * the cube roots of the first sixty-four prime numbers. In hex, these constant words are (from left to + * right) + */ +const K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]) + +/** + * See 5.3.3. Initial hash value. + * + * These words were obtained by taking the first thirty-two bits of the fractional parts of the + * square roots of the first eight prime numbers. + * + * @todo shouldn't be a global variable + */ +const HINIT = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]) + +// time to beat: (large value < 4.35s) + +class Hasher { + constructor () { + const buf = new ArrayBuffer(64 + 64 * 4) + // Init working variables using a single arraybuffer + this._H = new Uint32Array(buf, 0, 8) + this._H.set(HINIT) + // "Message schedule" - a working variable + this._W = new Uint32Array(buf, 64, 64) + } + + _updateHash () { + const H = this._H + const W = this._W + for (let t = 16; t < 64; t++) { + W[t] = sigma1to256(W[t - 2]) + W[t - 7] + sigma0to256(W[t - 15]) + W[t - 16] + } + let a = H[0] + let b = H[1] + let c = H[2] + let d = H[3] + let e = H[4] + let f = H[5] + let g = H[6] + let h = H[7] + for (let tt = 0, T1, T2; tt < 64; tt++) { + T1 = (h + sum1to256(e) + ((e & f) ^ (~e & g)) + K[tt] + W[tt]) >>> 0 + T2 = (sum0to256(a) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0 + h = g + g = f + f = e + e = (d + T1) >>> 0 + d = c + c = b + b = a + a = (T1 + T2) >>> 0 + } + H[0] += a + H[1] += b + H[2] += c + H[3] += d + H[4] += e + H[5] += f + H[6] += g + H[7] += h + } + + /** + * @param {Uint8Array} data + */ + digest (data) { + let i = 0 + for (; i + 56 <= data.length;) { + // write data in big endianess + let j = 0 + for (; j < 16 && i + 3 < data.length; j++) { + this._W[j] = data[i++] << 24 | data[i++] << 16 | data[i++] << 8 | data[i++] + } + if (i % 64 !== 0) { // there is still room to write partial content and the ending bit. + this._W.fill(0, j, 16) + while (i < data.length) { + this._W[j] |= data[i] << ((3 - (i % 4)) * 8) + i++ + } + this._W[j] |= binary.BIT8 << ((3 - (i % 4)) * 8) + } + this._updateHash() + } + // same check as earlier - the ending bit has been written + const isPaddedWith1 = i % 64 !== 0 + this._W.fill(0, 0, 16) + let j = 0 + for (; i < data.length; j++) { + for (let ci = 3; ci >= 0 && i < data.length; ci--) { + this._W[j] |= data[i++] << (ci * 8) + } + } + // Write padding of the message. See 5.1.2. + if (!isPaddedWith1) { + this._W[j - (i % 4 === 0 ? 0 : 1)] |= binary.BIT8 << ((3 - (i % 4)) * 8) + } + // write length of message (size in bits) as 64 bit uint + // @todo test that this works correctly + this._W[14] = data.byteLength / binary.BIT30 // same as data.byteLength >>> 30 - but works on floats + this._W[15] = data.byteLength * 8 + this._updateHash() + // correct H endianness to use big endiannes and return a Uint8Array + const dv = new Uint8Array(32) + for (let i = 0; i < this._H.length; i++) { + for (let ci = 0; ci < 4; ci++) { + dv[i * 4 + ci] = this._H[i] >>> (3 - ci) * 8 + } + } + return dv + } +} + +/** + * @param {Uint8Array} data + */ +export const digest = data => new Hasher().digest(data) diff --git a/nodejs/node_modules/lib0/hash/sha256.node.d.ts b/nodejs/node_modules/lib0/hash/sha256.node.d.ts new file mode 100644 index 00000000..4046b5eb --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.node.d.ts @@ -0,0 +1,2 @@ +export function digest(data: Uint8Array): Buffer; +//# sourceMappingURL=sha256.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/sha256.node.d.ts.map b/nodejs/node_modules/lib0/hash/sha256.node.d.ts.map new file mode 100644 index 00000000..35b7a3db --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.node.d.ts","sourceRoot":"","sources":["sha256.node.js"],"names":[],"mappings":"AAKO,6BAFI,UAAU,UAMpB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/sha256.node.js b/nodejs/node_modules/lib0/hash/sha256.node.js new file mode 100644 index 00000000..55c3c77f --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.node.js @@ -0,0 +1,10 @@ +import { createHash } from 'node:crypto' + +/** + * @param {Uint8Array} data + */ +export const digest = data => { + const hasher = createHash('sha256') + hasher.update(data) + return hasher.digest() +} diff --git a/nodejs/node_modules/lib0/hash/sha256.test.d.ts b/nodejs/node_modules/lib0/hash/sha256.test.d.ts new file mode 100644 index 00000000..39fc5381 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.test.d.ts @@ -0,0 +1,7 @@ +export function testSelfReferencingHash(_tc: t.TestCase): void; +export function testSha256Basics(_tc: t.TestCase): Promise; +export function testLargeValue(_tc: t.TestCase): Promise; +export function testRepeatSha256Hashing(tc: t.TestCase): Promise; +export function testBenchmarkSha256(_tc: t.TestCase): Promise; +import * as t from '../testing.js'; +//# sourceMappingURL=sha256.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/hash/sha256.test.d.ts.map b/nodejs/node_modules/lib0/hash/sha256.test.d.ts.map new file mode 100644 index 00000000..56feb4c2 --- /dev/null +++ b/nodejs/node_modules/lib0/hash/sha256.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.test.d.ts","sourceRoot":"","sources":["sha256.test.js"],"names":[],"mappings":"AAcO,6CAFI,EAAE,QAAQ,QAKpB;AAKM,sCAFI,EAAE,QAAQ,iBA2BpB;AAOM,oCAFI,EAAE,QAAQ,iBA4BpB;AAKM,4CAFI,EAAE,QAAQ,iBAQpB;AAKM,yCAFI,EAAE,QAAQ,iBAmDpB;mBAjJkB,eAAe"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/index.d.ts b/nodejs/node_modules/lib0/index.d.ts new file mode 100644 index 00000000..8aa3ac2a --- /dev/null +++ b/nodejs/node_modules/lib0/index.d.ts @@ -0,0 +1,35 @@ +import * as array from './array.js'; +import * as binary from './binary.js'; +import * as broadcastchannel from './broadcastchannel.js'; +import * as buffer from './buffer.js'; +import * as conditions from './conditions.js'; +import * as decoding from './decoding.js'; +import * as diff from './diff.js'; +import * as dom from './dom.js'; +import * as encoding from './encoding.js'; +import * as environment from './environment.js'; +import * as error from './error.js'; +import * as eventloop from './eventloop.js'; +import * as func from './function.js'; +import * as indexeddb from './indexeddb.js'; +import * as iterator from './iterator.js'; +import * as json from './json.js'; +import * as logging from 'lib0/logging'; +import * as map from './map.js'; +import * as math from './math.js'; +import * as mutex from './mutex.js'; +import * as number from './number.js'; +import * as object from './object.js'; +import * as pair from './pair.js'; +import * as prng from './prng.js'; +import * as promise from './promise.js'; +import * as set from './set.js'; +import * as sort from './sort.js'; +import * as statistics from './statistics.js'; +import * as string from './string.js'; +import * as symbol from './symbol.js'; +import * as time from './time.js'; +import * as tree from './tree.js'; +import * as websocket from './websocket.js'; +export { array, binary, broadcastchannel, buffer, conditions, decoding, diff, dom, encoding, environment, error, eventloop, func, indexeddb, iterator, json, logging, map, math, mutex, number, object, pair, prng, promise, set, sort, statistics, string, symbol, time, tree, websocket }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/index.d.ts.map b/nodejs/node_modules/lib0/index.d.ts.map new file mode 100644 index 00000000..1e8cb8eb --- /dev/null +++ b/nodejs/node_modules/lib0/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"uBAQuB,YAAY;wBACX,aAAa;kCACH,uBAAuB;wBACjC,aAAa;4BACT,iBAAiB;0BACnB,eAAe;sBACnB,WAAW;qBACZ,UAAU;0BACL,eAAe;6BACZ,kBAAkB;uBACxB,YAAY;2BACR,gBAAgB;sBAErB,eAAe;2BACV,gBAAgB;0BACjB,eAAe;sBACnB,WAAW;yBACR,cAAc;qBAClB,UAAU;sBACT,WAAW;uBACV,YAAY;wBACX,aAAa;wBACb,aAAa;sBACf,WAAW;sBACX,WAAW;yBACR,cAAc;qBAElB,UAAU;sBACT,WAAW;4BACL,iBAAiB;wBACrB,aAAa;wBACb,aAAa;sBAEf,WAAW;sBACX,WAAW;2BACN,gBAAgB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/index.js b/nodejs/node_modules/lib0/index.js new file mode 100644 index 00000000..1ea2fdd2 --- /dev/null +++ b/nodejs/node_modules/lib0/index.js @@ -0,0 +1,82 @@ +/** + * Experimental method to import lib0. + * + * Not recommended if the module bundler doesn't support dead code elimination. + * + * @module lib0 + */ + +import * as array from './array.js' +import * as binary from './binary.js' +import * as broadcastchannel from './broadcastchannel.js' +import * as buffer from './buffer.js' +import * as conditions from './conditions.js' +import * as decoding from './decoding.js' +import * as diff from './diff.js' +import * as dom from './dom.js' +import * as encoding from './encoding.js' +import * as environment from './environment.js' +import * as error from './error.js' +import * as eventloop from './eventloop.js' +// @todo rename file to func +import * as func from './function.js' +import * as indexeddb from './indexeddb.js' +import * as iterator from './iterator.js' +import * as json from './json.js' +import * as logging from 'lib0/logging' +import * as map from './map.js' +import * as math from './math.js' +import * as mutex from './mutex.js' +import * as number from './number.js' +import * as object from './object.js' +import * as pair from './pair.js' +import * as prng from './prng.js' +import * as promise from './promise.js' +// import * as random from './random.js' +import * as set from './set.js' +import * as sort from './sort.js' +import * as statistics from './statistics.js' +import * as string from './string.js' +import * as symbol from './symbol.js' +// import * as testing from './testing.js' +import * as time from './time.js' +import * as tree from './tree.js' +import * as websocket from './websocket.js' + +export { + array, + binary, + broadcastchannel, + buffer, + conditions, + decoding, + diff, + dom, + encoding, + environment, + error, + eventloop, + func, + indexeddb, + iterator, + json, + logging, + map, + math, + mutex, + number, + object, + pair, + prng, + promise, + // random, + set, + sort, + statistics, + string, + symbol, + // testing, + time, + tree, + websocket +} diff --git a/nodejs/node_modules/lib0/indexeddb.d.ts b/nodejs/node_modules/lib0/indexeddb.d.ts new file mode 100644 index 00000000..712e7dcf --- /dev/null +++ b/nodejs/node_modules/lib0/indexeddb.d.ts @@ -0,0 +1,34 @@ +export function rtop(request: IDBRequest): Promise; +export function openDB(name: string, initDB: (arg0: IDBDatabase) => any): Promise; +export function deleteDB(name: string): Promise; +export function createStores(db: IDBDatabase, definitions: Array | Array>): void; +export function transact(db: IDBDatabase, stores: Array, access?: "readonly" | "readwrite" | undefined): Array; +export function count(store: IDBObjectStore, range?: IDBKeyRange | undefined): Promise; +export function get(store: IDBObjectStore, key: string | number | ArrayBuffer | Date | Array): Promise>; +export function del(store: IDBObjectStore, key: string | number | ArrayBuffer | Date | IDBKeyRange | Array): Promise; +export function put(store: IDBObjectStore, item: string | number | ArrayBuffer | Date | boolean, key?: string | number | any[] | Date | ArrayBuffer | undefined): Promise; +export function add(store: IDBObjectStore, item: string | number | ArrayBuffer | Date | boolean, key: string | number | ArrayBuffer | Date | Array): Promise; +export function addAutoKey(store: IDBObjectStore, item: string | number | ArrayBuffer | Date): Promise; +export function getAll(store: IDBObjectStore, range?: IDBKeyRange | undefined, limit?: number | undefined): Promise>; +export function getAllKeys(store: IDBObjectStore, range?: IDBKeyRange | undefined, limit?: number | undefined): Promise>; +export function queryFirst(store: IDBObjectStore, query: IDBKeyRange | null, direction: 'next' | 'prev' | 'nextunique' | 'prevunique'): Promise; +export function getLastKey(store: IDBObjectStore, range?: IDBKeyRange | null | undefined): Promise; +export function getFirstKey(store: IDBObjectStore, range?: IDBKeyRange | null | undefined): Promise; +export function getAllKeysValues(store: IDBObjectStore, range?: IDBKeyRange | undefined, limit?: number | undefined): Promise>; +export function iterate(store: IDBObjectStore, keyrange: IDBKeyRange | null, f: (arg0: any, arg1: any) => void | boolean | Promise, direction?: 'next' | 'prev' | 'nextunique' | 'prevunique'): Promise; +export function iterateKeys(store: IDBObjectStore, keyrange: IDBKeyRange | null, f: (arg0: any) => void | boolean | Promise, direction?: 'next' | 'prev' | 'nextunique' | 'prevunique'): Promise; +export function getStore(t: IDBTransaction, store: string): IDBObjectStore; +export function createIDBKeyRangeBound(lower: any, upper: any, lowerOpen: boolean, upperOpen: boolean): IDBKeyRange; +export function createIDBKeyRangeUpperBound(upper: any, upperOpen: boolean): IDBKeyRange; +export function createIDBKeyRangeLowerBound(lower: any, lowerOpen: boolean): IDBKeyRange; +export type KeyValuePair = { + /** + * key + */ + k: any; + /** + * Value + */ + v: any; +}; +//# sourceMappingURL=indexeddb.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/indexeddb.d.ts.map b/nodejs/node_modules/lib0/indexeddb.d.ts.map new file mode 100644 index 00000000..7382e79a --- /dev/null +++ b/nodejs/node_modules/lib0/indexeddb.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"indexeddb.d.ts","sourceRoot":"","sources":["indexeddb.js"],"names":[],"mappings":"AAmBO,8BAHI,UAAU,GACT,QAAQ,GAAG,CAAC,CAOtB;AAOK,6BAJI,MAAM,iBACG,WAAW,KAAE,GAAG,GACxB,QAAQ,WAAW,CAAC,CAuB9B;AAKK,+BAFI,MAAM,gBAEmD;AAM7D,iCAHI,WAAW,eACX,MAAM,MAAM,MAAM,CAAC,GAAC,MAAM,MAAM,GAAC,wBAAwB,GAAC,SAAS,CAAC,CAAC,QAK/E;AAQM,6BALI,WAAW,UACX,MAAM,MAAM,CAAC,kDAEZ,MAAM,cAAc,CAAC,CAKhC;AAOM,6BAJI,cAAc,oCAEb,QAAQ,MAAM,CAAC,CAGD;AAOnB,2BAJI,cAAc,OACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,GAChD,QAAQ,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,CAAC,CAGhD;AAMf,2BAHI,cAAc,OACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,WAAW,GAAG,MAAM,GAAG,CAAC,gBAGjD;AAOlB,2BAJI,cAAc,QACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,OAAO,gFAI7B;AAQrB,2BALI,cAAc,QACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,OAAO,OAC9C,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,GAChD,QAAQ,GAAG,CAAC,CAGI;AAOrB,kCAJI,cAAc,QACd,SAAS,MAAM,GAAG,WAAW,GAAG,IAAI,GACnC,QAAQ,MAAM,CAAC,CAGJ;AAQhB,8BALI,cAAc,gEAGb,QAAQ,MAAM,GAAG,CAAC,CAAC,CAGG;AAQ3B,kCALI,cAAc,gEAGb,QAAQ,MAAM,GAAG,CAAC,CAAC,CAGO;AAQ/B,kCALI,cAAc,SACd,WAAW,GAAC,IAAI,aAChB,MAAM,GAAC,MAAM,GAAC,YAAY,GAAC,YAAY,GACtC,QAAQ,GAAG,CAAC,CAWvB;AAOM,kCAJI,cAAc,2CAEb,QAAQ,GAAG,CAAC,CAE2D;AAO5E,mCAJI,cAAc,2CAEb,QAAQ,GAAG,CAAC,CAE4D;AAe7E,wCALI,cAAc,gEAGb,QAAQ,MAAM,YAAY,CAAC,CAAC,CAI6F;AA4B9H,+BALI,cAAc,YACd,WAAW,GAAC,IAAI,YACP,GAAG,QAAC,GAAG,KAAE,IAAI,GAAC,OAAO,GAAC,QAAQ,IAAI,GAAC,OAAO,CAAC,cACpD,MAAM,GAAC,MAAM,GAAC,YAAY,GAAC,YAAY,iBAG8C;AAUzF,mCALI,cAAc,YACd,WAAW,GAAC,IAAI,YACP,GAAG,KAAE,IAAI,GAAC,OAAO,GAAC,QAAQ,IAAI,GAAC,OAAO,CAAC,cAChD,MAAM,GAAC,MAAM,GAAC,YAAY,GAAC,YAAY,iBAGmC;AAQ9E,4BAJI,cAAc,kBAEZ,cAAc,CAE+B;AAQnD,8CALI,GAAG,SACH,GAAG,aACH,OAAO,aACP,OAAO,eAEiH;AAM5H,mDAHI,GAAG,aACH,OAAO,eAEuF;AAMlG,mDAHI,GAAG,aACH,OAAO,eAEuF;;;;;OAhF3F,GAAG;;;;OACH,GAAG"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/indexeddb.js b/nodejs/node_modules/lib0/indexeddb.js new file mode 100644 index 00000000..a2288686 --- /dev/null +++ b/nodejs/node_modules/lib0/indexeddb.js @@ -0,0 +1,262 @@ +/* eslint-env browser */ + +/** + * Helpers to work with IndexedDB. + * + * @module indexeddb + */ + +import * as promise from './promise.js' +import * as error from './error.js' + +/* c8 ignore start */ + +/** + * IDB Request to Promise transformer + * + * @param {IDBRequest} request + * @return {Promise} + */ +export const rtop = request => promise.create((resolve, reject) => { + // @ts-ignore + request.onerror = event => reject(new Error(event.target.error)) + // @ts-ignore + request.onsuccess = event => resolve(event.target.result) +}) + +/** + * @param {string} name + * @param {function(IDBDatabase):any} initDB Called when the database is first created + * @return {Promise} + */ +export const openDB = (name, initDB) => promise.create((resolve, reject) => { + const request = indexedDB.open(name) + /** + * @param {any} event + */ + request.onupgradeneeded = event => initDB(event.target.result) + /** + * @param {any} event + */ + request.onerror = event => reject(error.create(event.target.error)) + /** + * @param {any} event + */ + request.onsuccess = event => { + /** + * @type {IDBDatabase} + */ + const db = event.target.result + db.onversionchange = () => { db.close() } + resolve(db) + } +}) + +/** + * @param {string} name + */ +export const deleteDB = name => rtop(indexedDB.deleteDatabase(name)) + +/** + * @param {IDBDatabase} db + * @param {Array|Array>} definitions + */ +export const createStores = (db, definitions) => definitions.forEach(d => + // @ts-ignore + db.createObjectStore.apply(db, d) +) + +/** + * @param {IDBDatabase} db + * @param {Array} stores + * @param {"readwrite"|"readonly"} [access] + * @return {Array} + */ +export const transact = (db, stores, access = 'readwrite') => { + const transaction = db.transaction(stores, access) + return stores.map(store => getStore(transaction, store)) +} + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @return {Promise} + */ +export const count = (store, range) => + rtop(store.count(range)) + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | Array } key + * @return {Promise>} + */ +export const get = (store, key) => + rtop(store.get(key)) + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | IDBKeyRange | Array } key + */ +export const del = (store, key) => + rtop(store.delete(key)) + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | boolean} item + * @param {String | number | ArrayBuffer | Date | Array} [key] + */ +export const put = (store, item, key) => + rtop(store.put(item, key)) + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date | boolean} item + * @param {String | number | ArrayBuffer | Date | Array} key + * @return {Promise} + */ +export const add = (store, item, key) => + rtop(store.add(item, key)) + +/** + * @param {IDBObjectStore} store + * @param {String | number | ArrayBuffer | Date} item + * @return {Promise} Returns the generated key + */ +export const addAutoKey = (store, item) => + rtop(store.add(item)) + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @param {number} [limit] + * @return {Promise>} + */ +export const getAll = (store, range, limit) => + rtop(store.getAll(range, limit)) + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @param {number} [limit] + * @return {Promise>} + */ +export const getAllKeys = (store, range, limit) => + rtop(store.getAllKeys(range, limit)) + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange|null} query + * @param {'next'|'prev'|'nextunique'|'prevunique'} direction + * @return {Promise} + */ +export const queryFirst = (store, query, direction) => { + /** + * @type {any} + */ + let first = null + return iterateKeys(store, query, key => { + first = key + return false + }, direction).then(() => first) +} + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange?} [range] + * @return {Promise} + */ +export const getLastKey = (store, range = null) => queryFirst(store, range, 'prev') + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange?} [range] + * @return {Promise} + */ +export const getFirstKey = (store, range = null) => queryFirst(store, range, 'next') + +/** + * @typedef KeyValuePair + * @type {Object} + * @property {any} k key + * @property {any} v Value + */ + +/** + * @param {IDBObjectStore} store + * @param {IDBKeyRange} [range] + * @param {number} [limit] + * @return {Promise>} + */ +export const getAllKeysValues = (store, range, limit) => + // @ts-ignore + promise.all([getAllKeys(store, range, limit), getAll(store, range, limit)]).then(([ks, vs]) => ks.map((k, i) => ({ k, v: vs[i] }))) + +/** + * @param {any} request + * @param {function(IDBCursorWithValue):void|boolean|Promise} f + * @return {Promise} + */ +const iterateOnRequest = (request, f) => promise.create((resolve, reject) => { + request.onerror = reject + /** + * @param {any} event + */ + request.onsuccess = async event => { + const cursor = event.target.result + if (cursor === null || (await f(cursor)) === false) { + return resolve() + } + cursor.continue() + } +}) + +/** + * Iterate on keys and values + * @param {IDBObjectStore} store + * @param {IDBKeyRange|null} keyrange + * @param {function(any,any):void|boolean|Promise} f Callback that receives (value, key) + * @param {'next'|'prev'|'nextunique'|'prevunique'} direction + */ +export const iterate = (store, keyrange, f, direction = 'next') => + iterateOnRequest(store.openCursor(keyrange, direction), cursor => f(cursor.value, cursor.key)) + +/** + * Iterate on the keys (no values) + * + * @param {IDBObjectStore} store + * @param {IDBKeyRange|null} keyrange + * @param {function(any):void|boolean|Promise} f callback that receives the key + * @param {'next'|'prev'|'nextunique'|'prevunique'} direction + */ +export const iterateKeys = (store, keyrange, f, direction = 'next') => + iterateOnRequest(store.openKeyCursor(keyrange, direction), cursor => f(cursor.key)) + +/** + * Open store from transaction + * @param {IDBTransaction} t + * @param {String} store + * @returns {IDBObjectStore} + */ +export const getStore = (t, store) => t.objectStore(store) + +/** + * @param {any} lower + * @param {any} upper + * @param {boolean} lowerOpen + * @param {boolean} upperOpen + */ +export const createIDBKeyRangeBound = (lower, upper, lowerOpen, upperOpen) => IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) + +/** + * @param {any} upper + * @param {boolean} upperOpen + */ +export const createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen) + +/** + * @param {any} lower + * @param {boolean} lowerOpen + */ +export const createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen) + +/* c8 ignore stop */ diff --git a/nodejs/node_modules/lib0/indexeddb.test.d.ts b/nodejs/node_modules/lib0/indexeddb.test.d.ts new file mode 100644 index 00000000..e45d0c98 --- /dev/null +++ b/nodejs/node_modules/lib0/indexeddb.test.d.ts @@ -0,0 +1,3 @@ +export function testRetrieveElements(): Promise; +export function testBlocked(): Promise; +//# sourceMappingURL=indexeddb.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/indexeddb.test.d.ts.map b/nodejs/node_modules/lib0/indexeddb.test.d.ts.map new file mode 100644 index 00000000..2b53eb37 --- /dev/null +++ b/nodejs/node_modules/lib0/indexeddb.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"indexeddb.test.d.ts","sourceRoot":"","sources":["indexeddb.test.js"],"names":[],"mappings":"AAyBO,sDAoEN;AAGM,6CAWN"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/isomorphic.d.ts b/nodejs/node_modules/lib0/isomorphic.d.ts new file mode 100644 index 00000000..05103a67 --- /dev/null +++ b/nodejs/node_modules/lib0/isomorphic.d.ts @@ -0,0 +1,2 @@ +export { performance, cryptoRandomBuffer } from "isomorphic.js"; +//# sourceMappingURL=isomorphic.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/isomorphic.d.ts.map b/nodejs/node_modules/lib0/isomorphic.d.ts.map new file mode 100644 index 00000000..90a3fb35 --- /dev/null +++ b/nodejs/node_modules/lib0/isomorphic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"isomorphic.d.ts","sourceRoot":"","sources":["isomorphic.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/isomorphic.js b/nodejs/node_modules/lib0/isomorphic.js new file mode 100644 index 00000000..208e9a27 --- /dev/null +++ b/nodejs/node_modules/lib0/isomorphic.js @@ -0,0 +1,13 @@ +/** + * Isomorphic library exports from isomorphic.js. + * + * @todo remove this module + * @deprecated + * + * @module isomorphic + */ + +// @todo remove this module + +// @ts-ignore +export { performance, cryptoRandomBuffer } from 'isomorphic.js' diff --git a/nodejs/node_modules/lib0/iterator.d.ts b/nodejs/node_modules/lib0/iterator.d.ts new file mode 100644 index 00000000..0254cc99 --- /dev/null +++ b/nodejs/node_modules/lib0/iterator.d.ts @@ -0,0 +1,5 @@ +export function mapIterator(iterator: Iterator, f: (arg0: T) => R): IterableIterator; +export function createIterator(next: () => IteratorResult): IterableIterator; +export function iteratorFilter(iterator: Iterator, filter: (arg0: T) => boolean): IterableIterator; +export function iteratorMap(iterator: Iterator, fmap: (arg0: T) => M): IterableIterator; +//# sourceMappingURL=iterator.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/iterator.d.ts.map b/nodejs/node_modules/lib0/iterator.d.ts.map new file mode 100644 index 00000000..12cc079e --- /dev/null +++ b/nodejs/node_modules/lib0/iterator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"iterator.d.ts","sourceRoot":"","sources":["iterator.js"],"names":[],"mappings":"AAYO,iHASL;AAOK,2FASL;AAOK,8FAFgB,OAAO,uBAQ5B;AAOK,gIAGL"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/iterator.js b/nodejs/node_modules/lib0/iterator.js new file mode 100644 index 00000000..6ab0e7a3 --- /dev/null +++ b/nodejs/node_modules/lib0/iterator.js @@ -0,0 +1,61 @@ +/** + * Utility module to create and manipulate Iterators. + * + * @module iterator + */ + +/** + * @template T,R + * @param {Iterator} iterator + * @param {function(T):R} f + * @return {IterableIterator} + */ +export const mapIterator = (iterator, f) => ({ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next () { + const r = iterator.next() + return { value: r.done ? undefined : f(r.value), done: r.done } + } +}) + +/** + * @template T + * @param {function():IteratorResult} next + * @return {IterableIterator} + */ +export const createIterator = next => ({ + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next +}) + +/** + * @template T + * @param {Iterator} iterator + * @param {function(T):boolean} filter + */ +export const iteratorFilter = (iterator, filter) => createIterator(() => { + let res + do { + res = iterator.next() + } while (!res.done && !filter(res.value)) + return res +}) + +/** + * @template T,M + * @param {Iterator} iterator + * @param {function(T):M} fmap + */ +export const iteratorMap = (iterator, fmap) => createIterator(() => { + const { done, value } = iterator.next() + return { done, value: done ? undefined : fmap(value) } +}) diff --git a/nodejs/node_modules/lib0/json.d.ts b/nodejs/node_modules/lib0/json.d.ts new file mode 100644 index 00000000..494abcf6 --- /dev/null +++ b/nodejs/node_modules/lib0/json.d.ts @@ -0,0 +1,23 @@ +/** + * JSON utility functions. + * + * @module json + */ +/** + * Transform JavaScript object to JSON. + * + * @param {any} object + * @return {string} + */ +export const stringify: { + (value: any, replacer?: ((this: any, key: string, value: any) => any) | undefined, space?: string | number | undefined): string; + (value: any, replacer?: (string | number)[] | null | undefined, space?: string | number | undefined): string; +}; +/** + * Parse JSON object. + * + * @param {string} json + * @return {any} + */ +export const parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any; +//# sourceMappingURL=json.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/json.d.ts.map b/nodejs/node_modules/lib0/json.d.ts.map new file mode 100644 index 00000000..d2bb7c1f --- /dev/null +++ b/nodejs/node_modules/lib0/json.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["json.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;GAKG;AACH;;;EAAuC;AAEvC;;;;;GAKG;AACH,+GAA+B"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/json.js b/nodejs/node_modules/lib0/json.js new file mode 100644 index 00000000..73540895 --- /dev/null +++ b/nodejs/node_modules/lib0/json.js @@ -0,0 +1,21 @@ +/** + * JSON utility functions. + * + * @module json + */ + +/** + * Transform JavaScript object to JSON. + * + * @param {any} object + * @return {string} + */ +export const stringify = JSON.stringify + +/** + * Parse JSON object. + * + * @param {string} json + * @return {any} + */ +export const parse = JSON.parse diff --git a/nodejs/node_modules/lib0/list.d.ts b/nodejs/node_modules/lib0/list.d.ts new file mode 100644 index 00000000..77b148a7 --- /dev/null +++ b/nodejs/node_modules/lib0/list.d.ts @@ -0,0 +1,38 @@ +export class ListNode { + /** + * @type {this|null} + */ + next: ListNode | null; + /** + * @type {this|null} + */ + prev: ListNode | null; +} +/** + * @template {ListNode} N + */ +export class List { + /** + * @type {N | null} + */ + start: N | null; + /** + * @type {N | null} + */ + end: N | null; + len: number; +} +export function create(): List; +export function isEmpty(queue: List): boolean; +export function remove(queue: List, node: N): N; +export function removeNode(queue: List, node: N): N; +export function insertBetween(queue: List, left: N | null, right: N | null, node: N): void; +export function replace(queue: List, node: N, newNode: N): void; +export function pushEnd(queue: List, n: N): void; +export function pushFront(queue: List, n: N): void; +export function popFront(list: List): N | null; +export function popEnd(list: List): N | null; +export function map(list: List, f: (arg0: N) => M): M[]; +export function toArray(list: List): N[]; +export function forEach(list: List, f: (arg0: N) => M): void; +//# sourceMappingURL=list.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/list.d.ts.map b/nodejs/node_modules/lib0/list.d.ts.map new file mode 100644 index 00000000..fb736f37 --- /dev/null +++ b/nodejs/node_modules/lib0/list.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"list.d.ts","sourceRoot":"","sources":["list.js"],"names":[],"mappings":"AAGA;IAEI;;OAEG;IACH,sBAAgB;IAChB;;OAEG;IACH,sBAAgB;CAEnB;AAED;;GAEG;AACH;IAEI;;OAEG;IACH,OAFU,CAAC,GAAG,IAAI,CAED;IACjB;;OAEG;IACH,KAFU,CAAC,GAAG,IAAI,CAEH;IACf,YAAY;CAEf;AAUM,sDAA+B;AAO/B,qEAA6C;AAU7C,uEAeN;AAfM,2EAeN;AAeM,kHAmBN;AAWM,uFAGN;AAQM,wEACmC;AAQnC,0EACqC;AAQrC,sEAC2C;AAQ3C,oEACuC;AAUvC,kFAWN;AAOM,gEAAqC;AASrC,uFAMN"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/list.js b/nodejs/node_modules/lib0/list.js new file mode 100644 index 00000000..33cd3bc6 --- /dev/null +++ b/nodejs/node_modules/lib0/list.js @@ -0,0 +1,201 @@ +import { id } from './function.js' +import * as error from './error.js' + +export class ListNode { + constructor () { + /** + * @type {this|null} + */ + this.next = null + /** + * @type {this|null} + */ + this.prev = null + } +} + +/** + * @template {ListNode} N + */ +export class List { + constructor () { + /** + * @type {N | null} + */ + this.start = null + /** + * @type {N | null} + */ + this.end = null + this.len = 0 + } +} + +/** + * @note The queue implementation is experimental and unfinished. + * Don't use this in production yet. + * + * @template {ListNode} N + * + * @return {List} + */ +export const create = () => new List() + +/** + * @template {ListNode} N + * + * @param {List} queue + */ +export const isEmpty = queue => queue.start === null + +/** + * Remove a single node from the queue. Only works with Queues that operate on Doubly-linked lists of nodes. + * + * @template {ListNode} N + * + * @param {List} queue + * @param {N} node + */ +export const remove = (queue, node) => { + const prev = node.prev + const next = node.next + if (prev) { + prev.next = next + } else { + queue.start = next + } + if (next) { + next.prev = prev + } else { + queue.end = prev + } + queue.len-- + return node +} + +/** + * @deprecated @todo remove in next major release + */ +export const removeNode = remove + +/** + * @template {ListNode} N + * + * @param {List} queue + * @param {N| null} left + * @param {N| null} right + * @param {N} node + */ +export const insertBetween = (queue, left, right, node) => { + /* c8 ignore start */ + if (left != null && left.next !== right) { + throw error.unexpectedCase() + } + /* c8 ignore stop */ + if (left) { + left.next = node + } else { + queue.start = node + } + if (right) { + right.prev = node + } else { + queue.end = node + } + node.prev = left + node.next = right + queue.len++ +} + +/** + * Remove a single node from the queue. Only works with Queues that operate on Doubly-linked lists of nodes. + * + * @template {ListNode} N + * + * @param {List} queue + * @param {N} node + * @param {N} newNode + */ +export const replace = (queue, node, newNode) => { + insertBetween(queue, node, node.next, newNode) + remove(queue, node) +} + +/** + * @template {ListNode} N + * + * @param {List} queue + * @param {N} n + */ +export const pushEnd = (queue, n) => + insertBetween(queue, queue.end, null, n) + +/** + * @template {ListNode} N + * + * @param {List} queue + * @param {N} n + */ +export const pushFront = (queue, n) => + insertBetween(queue, null, queue.start, n) + +/** + * @template {ListNode} N + * + * @param {List} list + * @return {N| null} + */ +export const popFront = list => + list.start ? removeNode(list, list.start) : null + +/** + * @template {ListNode} N + * + * @param {List} list + * @return {N| null} + */ +export const popEnd = list => + list.end ? removeNode(list, list.end) : null + +/** + * @template {ListNode} N + * @template M + * + * @param {List} list + * @param {function(N):M} f + * @return {Array} + */ +export const map = (list, f) => { + /** + * @type {Array} + */ + const arr = [] + let n = list.start + while (n) { + arr.push(f(n)) + n = n.next + } + return arr +} + +/** + * @template {ListNode} N + * + * @param {List} list + */ +export const toArray = list => map(list, id) + +/** + * @template {ListNode} N + * @template M + * + * @param {List} list + * @param {function(N):M} f + */ +export const forEach = (list, f) => { + let n = list.start + while (n) { + f(n) + n = n.next + } +} diff --git a/nodejs/node_modules/lib0/list.test.d.ts b/nodejs/node_modules/lib0/list.test.d.ts new file mode 100644 index 00000000..006aeae5 --- /dev/null +++ b/nodejs/node_modules/lib0/list.test.d.ts @@ -0,0 +1,4 @@ +export function testEnqueueDequeue(_tc: t.TestCase): void; +export function testSelectivePop(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=list.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/list.test.d.ts.map b/nodejs/node_modules/lib0/list.test.d.ts.map new file mode 100644 index 00000000..244da643 --- /dev/null +++ b/nodejs/node_modules/lib0/list.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"list.test.d.ts","sourceRoot":"","sources":["list.test.js"],"names":[],"mappings":"AAgBO,wCAFI,EAAE,QAAQ,QA8BpB;AAKM,sCAFI,EAAE,QAAQ,QA+BpB;mBA9EkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.common.d.ts b/nodejs/node_modules/lib0/logging.common.d.ts new file mode 100644 index 00000000..23e47917 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.common.d.ts @@ -0,0 +1,12 @@ +export const BOLD: symbol; +export const UNBOLD: symbol; +export const BLUE: symbol; +export const GREY: symbol; +export const GREEN: symbol; +export const RED: symbol; +export const PURPLE: symbol; +export const ORANGE: symbol; +export const UNCOLOR: symbol; +export function computeNoColorLoggingArgs(args: Array any)>): Array; +export function createModuleLogger(_print: (...args: any[]) => void, moduleName: string): (...args: any[]) => void; +//# sourceMappingURL=logging.common.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.common.d.ts.map b/nodejs/node_modules/lib0/logging.common.d.ts.map new file mode 100644 index 00000000..230a6b16 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.common.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.common.d.ts","sourceRoot":"","sources":["logging.common.js"],"names":[],"mappings":"AAMA,0BAAmC;AACnC,4BAAqC;AACrC,0BAAmC;AACnC,0BAAmC;AACnC,2BAAoC;AACpC,yBAAkC;AAClC,4BAAqC;AACrC,4BAAqC;AACrC,6BAAsC;AAO/B,gDAHI,MAAM,SAAS,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,UAAY,GAAG,CAAA,CAAC,GAC1D,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,CAqBtC;AAaM,qDAJgB,GAAG,OAAE,IAAI,cACrB,MAAM,aACO,GAAG,OAAE,IAAI,CAyChC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.common.js b/nodejs/node_modules/lib0/logging.common.js new file mode 100644 index 00000000..969d9308 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.common.js @@ -0,0 +1,94 @@ +import * as symbol from './symbol.js' +import * as time from './time.js' +import * as env from './environment.js' +import * as func from './function.js' +import * as json from './json.js' + +export const BOLD = symbol.create() +export const UNBOLD = symbol.create() +export const BLUE = symbol.create() +export const GREY = symbol.create() +export const GREEN = symbol.create() +export const RED = symbol.create() +export const PURPLE = symbol.create() +export const ORANGE = symbol.create() +export const UNCOLOR = symbol.create() + +/* c8 ignore start */ +/** + * @param {Array} args + * @return {Array} + */ +export const computeNoColorLoggingArgs = args => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]()) + } + const strBuilder = [] + const logArgs = [] + // try with formatting until we find something unsupported + let i = 0 + for (; i < args.length; i++) { + const arg = args[i] + if (arg === undefined) { + strBuilder.push('undefined') + } else if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg) + } else if (arg.constructor === Object) { + logArgs.push(JSON.stringify(arg)) + } + } + return logArgs +} +/* c8 ignore stop */ + +const loggingColors = [GREEN, PURPLE, ORANGE, BLUE] +let nextColor = 0 +let lastLoggingTime = time.getUnixTime() + +/* c8 ignore start */ +/** + * @param {function(...any):void} _print + * @param {string} moduleName + * @return {function(...any):void} + */ +export const createModuleLogger = (_print, moduleName) => { + const color = loggingColors[nextColor] + const debugRegexVar = env.getVariable('log') + const doLogging = debugRegexVar !== null && + (debugRegexVar === '*' || debugRegexVar === 'true' || + new RegExp(debugRegexVar, 'gi').test(moduleName)) + nextColor = (nextColor + 1) % loggingColors.length + moduleName += ': ' + return !doLogging + ? func.nop + : (...args) => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = args[0]() + } + const timeNow = time.getUnixTime() + const timeDiff = timeNow - lastLoggingTime + lastLoggingTime = timeNow + _print( + color, + moduleName, + UNCOLOR, + ...args.map((arg) => { + if (arg != null && arg.constructor === Uint8Array) { + arg = Array.from(arg) + } + const t = typeof arg + switch (t) { + case 'string': + case 'symbol': + return arg + default: { + return json.stringify(arg) + } + } + }), + color, + ' +' + timeDiff + 'ms' + ) + } +} +/* c8 ignore stop */ diff --git a/nodejs/node_modules/lib0/logging.d.ts b/nodejs/node_modules/lib0/logging.d.ts new file mode 100644 index 00000000..a768a17d --- /dev/null +++ b/nodejs/node_modules/lib0/logging.d.ts @@ -0,0 +1,55 @@ +export function print(...args: Array): void; +export function warn(...args: Array): void; +export function printError(err: Error): void; +export function printImg(url: string, height: number): void; +export function printImgBase64(base64: string, height: number): void; +export function group(...args: Array): void; +export function groupCollapsed(...args: Array): void; +export function groupEnd(): void; +export function printDom(createNode: () => Node): void; +export function printCanvas(canvas: HTMLCanvasElement, height: number): void; +export const vconsoles: Set; +export class VConsole { + /** + * @param {Element} dom + */ + constructor(dom: Element); + dom: Element; + /** + * @type {Element} + */ + ccontainer: Element; + depth: number; + /** + * @param {Array} args + * @param {boolean} collapsed + */ + group(args: Array, collapsed?: boolean): void; + /** + * @param {Array} args + */ + groupCollapsed(args: Array): void; + groupEnd(): void; + /** + * @param {Array} args + */ + print(args: Array): void; + /** + * @param {Error} err + */ + printError(err: Error): void; + /** + * @param {string} url + * @param {number} height + */ + printImg(url: string, height: number): void; + /** + * @param {Node} node + */ + printDom(node: Node): void; + destroy(): void; +} +export function createVConsole(dom: Element): VConsole; +export function createModuleLogger(moduleName: string): (...args: any[]) => void; +export { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from "./logging.common.js"; +//# sourceMappingURL=logging.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.d.ts.map b/nodejs/node_modules/lib0/logging.d.ts.map new file mode 100644 index 00000000..c674a841 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.d.ts","sourceRoot":"","sources":["logging.js"],"names":[],"mappings":"AAmGO,+BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAMM,8BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAOM,gCAHI,KAAK,QAMf;AAQM,8BAJI,MAAM,UACN,MAAM,QAYhB;AAQM,uCAJI,MAAM,UACN,MAAM,QAIoC;AAK9C,+BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAKM,wCAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAM5C;AAEM,iCAIN;AAMM,2CAHe,IAAI,QAI4B;AAO/C,oCAJI,iBAAiB,UACjB,MAAM,QAIqB;AAEtC,iCAAqC;AAwDrC;IACE;;OAEG;IACH,iBAFW,OAAO,EAUjB;IAPC,aAAc;IACd;;OAEG;IACH,YAFU,OAAO,CAES;IAC1B,cAAc;IAIhB;;;OAGG;IACH,YAHW,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,cAClC,OAAO,QAoCjB;IAED;;OAEG;IACH,qBAFW,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAI5C;IAED,iBAQC;IAED;;OAEG;IACH,YAFW,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAa5C;IAED;;OAEG;IACH,gBAFW,KAAK,QAIf;IAED;;;OAGG;IACH,cAHW,MAAM,UACN,MAAM,QAWhB;IAED;;OAEG;IACH,eAFW,IAAI,QAMd;IAED,gBAIC;CACF;AAOM,oCAHI,OAAO,YAGsC;AAMjD,+CAHI,MAAM,aACO,GAAG,OAAE,IAAI,CAE6D"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.js b/nodejs/node_modules/lib0/logging.js new file mode 100644 index 00000000..d6c77c60 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.js @@ -0,0 +1,383 @@ +/** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + +import * as env from './environment.js' +import * as set from './set.js' +import * as pair from './pair.js' +import * as dom from './dom.js' +import * as json from './json.js' +import * as map from './map.js' +import * as eventloop from './eventloop.js' +import * as math from './math.js' +import * as common from './logging.common.js' + +export { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from './logging.common.js' + +/** + * @type {Object>} + */ +const _browserStyleMap = { + [common.BOLD]: pair.create('font-weight', 'bold'), + [common.UNBOLD]: pair.create('font-weight', 'normal'), + [common.BLUE]: pair.create('color', 'blue'), + [common.GREEN]: pair.create('color', 'green'), + [common.GREY]: pair.create('color', 'grey'), + [common.RED]: pair.create('color', 'red'), + [common.PURPLE]: pair.create('color', 'purple'), + [common.ORANGE]: pair.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate + [common.UNCOLOR]: pair.create('color', 'black') +} + +/** + * @param {Array} args + * @return {Array} + */ +/* c8 ignore start */ +const computeBrowserLoggingArgs = (args) => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]()) + } + const strBuilder = [] + const styles = [] + const currentStyle = map.create() + /** + * @type {Array} + */ + let logArgs = [] + // try with formatting until we find something unsupported + let i = 0 + for (; i < args.length; i++) { + const arg = args[i] + // @ts-ignore + const style = _browserStyleMap[arg] + if (style !== undefined) { + currentStyle.set(style.left, style.right) + } else { + if (arg === undefined) { + break + } + if (arg.constructor === String || arg.constructor === Number) { + const style = dom.mapToStyleString(currentStyle) + if (i > 0 || style.length > 0) { + strBuilder.push('%c' + arg) + styles.push(style) + } else { + strBuilder.push(arg) + } + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + logArgs = styles + logArgs.unshift(strBuilder.join('')) + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i] + if (!(arg instanceof Symbol)) { + logArgs.push(arg) + } + } + return logArgs +} +/* c8 ignore stop */ + +/* c8 ignore start */ +const computeLoggingArgs = env.supportsColor + ? computeBrowserLoggingArgs + : common.computeNoColorLoggingArgs +/* c8 ignore stop */ + +/** + * @param {Array} args + */ +export const print = (...args) => { + console.log(...computeLoggingArgs(args)) + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.print(args)) +} + +/* c8 ignore start */ +/** + * @param {Array} args + */ +export const warn = (...args) => { + console.warn(...computeLoggingArgs(args)) + args.unshift(common.ORANGE) + vconsoles.forEach((vc) => vc.print(args)) +} +/* c8 ignore stop */ + +/** + * @param {Error} err + */ +/* c8 ignore start */ +export const printError = (err) => { + console.error(err) + vconsoles.forEach((vc) => vc.printError(err)) +} +/* c8 ignore stop */ + +/** + * @param {string} url image location + * @param {number} height height of the image in pixel + */ +/* c8 ignore start */ +export const printImg = (url, height) => { + if (env.isBrowser) { + console.log( + '%c ', + `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})` + ) + // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`) + } + vconsoles.forEach((vc) => vc.printImg(url, height)) +} +/* c8 ignore stop */ + +/** + * @param {string} base64 + * @param {number} height + */ +/* c8 ignore next 2 */ +export const printImgBase64 = (base64, height) => + printImg(`data:image/gif;base64,${base64}`, height) + +/** + * @param {Array} args + */ +export const group = (...args) => { + console.group(...computeLoggingArgs(args)) + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.group(args)) +} + +/** + * @param {Array} args + */ +export const groupCollapsed = (...args) => { + console.groupCollapsed(...computeLoggingArgs(args)) + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.groupCollapsed(args)) +} + +export const groupEnd = () => { + console.groupEnd() + /* c8 ignore next */ + vconsoles.forEach((vc) => vc.groupEnd()) +} + +/** + * @param {function():Node} createNode + */ +/* c8 ignore next 2 */ +export const printDom = (createNode) => + vconsoles.forEach((vc) => vc.printDom(createNode())) + +/** + * @param {HTMLCanvasElement} canvas + * @param {number} height + */ +/* c8 ignore next 2 */ +export const printCanvas = (canvas, height) => + printImg(canvas.toDataURL(), height) + +export const vconsoles = set.create() + +/** + * @param {Array} args + * @return {Array} + */ +/* c8 ignore start */ +const _computeLineSpans = (args) => { + const spans = [] + const currentStyle = new Map() + // try with formatting until we find something unsupported + let i = 0 + for (; i < args.length; i++) { + let arg = args[i] + // @ts-ignore + const style = _browserStyleMap[arg] + if (style !== undefined) { + currentStyle.set(style.left, style.right) + } else { + if (arg === undefined) { + arg = 'undefined ' + } + if (arg.constructor === String || arg.constructor === Number) { + // @ts-ignore + const span = dom.element('span', [ + pair.create('style', dom.mapToStyleString(currentStyle)) + ], [dom.text(arg.toString())]) + if (span.innerHTML === '') { + span.innerHTML = ' ' + } + spans.push(span) + } else { + break + } + } + } + // append the rest + for (; i < args.length; i++) { + let content = args[i] + if (!(content instanceof Symbol)) { + if (content.constructor !== String && content.constructor !== Number) { + content = ' ' + json.stringify(content) + ' ' + } + spans.push( + dom.element('span', [], [dom.text(/** @type {string} */ (content))]) + ) + } + } + return spans +} +/* c8 ignore stop */ + +const lineStyle = + 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;' + +/* c8 ignore start */ +export class VConsole { + /** + * @param {Element} dom + */ + constructor (dom) { + this.dom = dom + /** + * @type {Element} + */ + this.ccontainer = this.dom + this.depth = 0 + vconsoles.add(this) + } + + /** + * @param {Array} args + * @param {boolean} collapsed + */ + group (args, collapsed = false) { + eventloop.enqueue(() => { + const triangleDown = dom.element('span', [ + pair.create('hidden', collapsed), + pair.create('style', 'color:grey;font-size:120%;') + ], [dom.text('▼')]) + const triangleRight = dom.element('span', [ + pair.create('hidden', !collapsed), + pair.create('style', 'color:grey;font-size:125%;') + ], [dom.text('▶')]) + const content = dom.element( + 'div', + [pair.create( + 'style', + `${lineStyle};padding-left:${this.depth * 10}px` + )], + [triangleDown, triangleRight, dom.text(' ')].concat( + _computeLineSpans(args) + ) + ) + const nextContainer = dom.element('div', [ + pair.create('hidden', collapsed) + ]) + const nextLine = dom.element('div', [], [content, nextContainer]) + dom.append(this.ccontainer, [nextLine]) + this.ccontainer = nextContainer + this.depth++ + // when header is clicked, collapse/uncollapse container + dom.addEventListener(content, 'click', (_event) => { + nextContainer.toggleAttribute('hidden') + triangleDown.toggleAttribute('hidden') + triangleRight.toggleAttribute('hidden') + }) + }) + } + + /** + * @param {Array} args + */ + groupCollapsed (args) { + this.group(args, true) + } + + groupEnd () { + eventloop.enqueue(() => { + if (this.depth > 0) { + this.depth-- + // @ts-ignore + this.ccontainer = this.ccontainer.parentElement.parentElement + } + }) + } + + /** + * @param {Array} args + */ + print (args) { + eventloop.enqueue(() => { + dom.append(this.ccontainer, [ + dom.element('div', [ + pair.create( + 'style', + `${lineStyle};padding-left:${this.depth * 10}px` + ) + ], _computeLineSpans(args)) + ]) + }) + } + + /** + * @param {Error} err + */ + printError (err) { + this.print([common.RED, common.BOLD, err.toString()]) + } + + /** + * @param {string} url + * @param {number} height + */ + printImg (url, height) { + eventloop.enqueue(() => { + dom.append(this.ccontainer, [ + dom.element('img', [ + pair.create('src', url), + pair.create('height', `${math.round(height * 1.5)}px`) + ]) + ]) + }) + } + + /** + * @param {Node} node + */ + printDom (node) { + eventloop.enqueue(() => { + dom.append(this.ccontainer, [node]) + }) + } + + destroy () { + eventloop.enqueue(() => { + vconsoles.delete(this) + }) + } +} +/* c8 ignore stop */ + +/** + * @param {Element} dom + */ +/* c8 ignore next */ +export const createVConsole = (dom) => new VConsole(dom) + +/** + * @param {string} moduleName + * @return {function(...any):void} + */ +export const createModuleLogger = (moduleName) => common.createModuleLogger(print, moduleName) diff --git a/nodejs/node_modules/lib0/logging.node.d.ts b/nodejs/node_modules/lib0/logging.node.d.ts new file mode 100644 index 00000000..69edeebd --- /dev/null +++ b/nodejs/node_modules/lib0/logging.node.d.ts @@ -0,0 +1,14 @@ +export function print(...args: Array): void; +export function warn(...args: Array): void; +export function printError(err: Error): void; +export function printImg(_url: string, _height: number): void; +export function printImgBase64(base64: string, height: number): void; +export function group(...args: Array): void; +export function groupCollapsed(...args: Array): void; +export function groupEnd(): void; +export function printDom(_createNode: () => Node): void; +export function printCanvas(canvas: HTMLCanvasElement, height: number): void; +export function createVConsole(_dom: Element): void; +export function createModuleLogger(moduleName: string): (...args: any[]) => void; +export { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from "./logging.common.js"; +//# sourceMappingURL=logging.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.node.d.ts.map b/nodejs/node_modules/lib0/logging.node.d.ts.map new file mode 100644 index 00000000..b63616c9 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.node.d.ts","sourceRoot":"","sources":["logging.node.js"],"names":[],"mappings":"AA6EO,+BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,SAAS,CAAC,QAItD;AAMM,8BAFI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAI5C;AAOM,gCAHI,KAAK,QAKf;AAQM,+BAJI,MAAM,WACN,MAAM,QAKhB;AAQM,uCAJI,MAAM,UACN,MAAM,QAIoC;AAM9C,+BAHI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAK5C;AAMM,wCAHI,MAAM,MAAM,GAAC,MAAM,GAAC,MAAM,GAAC,MAAM,CAAC,QAK5C;AAGM,iCAEN;AAMM,4CAHe,IAAI,QAGiB;AAOpC,oCAJI,iBAAiB,UACjB,MAAM,QAIqB;AAM/B,qCAHI,OAAO,QAGwB;AAOnC,+CAJI,MAAM,aACO,GAAG,OAAE,IAAI,CAG6D"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.node.js b/nodejs/node_modules/lib0/logging.node.js new file mode 100644 index 00000000..63d41ec5 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.node.js @@ -0,0 +1,164 @@ +/** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + +import * as env from './environment.js' +import * as common from './logging.common.js' + +export { BOLD, UNBOLD, BLUE, GREY, GREEN, RED, PURPLE, ORANGE, UNCOLOR } from './logging.common.js' + +const _nodeStyleMap = { + [common.BOLD]: '\u001b[1m', + [common.UNBOLD]: '\u001b[2m', + [common.BLUE]: '\x1b[34m', + [common.GREEN]: '\x1b[32m', + [common.GREY]: '\u001b[37m', + [common.RED]: '\x1b[31m', + [common.PURPLE]: '\x1b[35m', + [common.ORANGE]: '\x1b[38;5;208m', + [common.UNCOLOR]: '\x1b[0m' +} + +/* c8 ignore start */ +/** + * @param {Array>} args + * @return {Array} + */ +const computeNodeLoggingArgs = (args) => { + if (args.length === 1 && args[0]?.constructor === Function) { + args = /** @type {Array} */ (/** @type {[function]} */ (args)[0]()) + } + const strBuilder = [] + const logArgs = [] + // try with formatting until we find something unsupported + let i = 0 + for (; i < args.length; i++) { + const arg = args[i] + // @ts-ignore + const style = _nodeStyleMap[arg] + if (style !== undefined) { + strBuilder.push(style) + } else { + if (arg === undefined) { + break + } else if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg) + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + strBuilder.push('\x1b[0m') + logArgs.push(strBuilder.join('')) + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i] + if (!(arg instanceof Symbol)) { + logArgs.push(arg) + } + } + return logArgs +} +/* c8 ignore stop */ + +/* c8 ignore start */ +const computeLoggingArgs = env.supportsColor + ? computeNodeLoggingArgs + : common.computeNoColorLoggingArgs +/* c8 ignore stop */ + +/** + * @param {Array} args + */ +export const print = (...args) => { + console.log(...computeLoggingArgs(args)) +} + +/* c8 ignore start */ +/** + * @param {Array} args + */ +export const warn = (...args) => { + console.warn(...computeLoggingArgs(args)) +} +/* c8 ignore stop */ + +/** + * @param {Error} err + */ +/* c8 ignore start */ +export const printError = (err) => { + console.error(err) +} +/* c8 ignore stop */ + +/** + * @param {string} _url image location + * @param {number} _height height of the image in pixel + */ +/* c8 ignore start */ +export const printImg = (_url, _height) => { + // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`) +} +/* c8 ignore stop */ + +/** + * @param {string} base64 + * @param {number} height + */ +/* c8 ignore next 2 */ +export const printImgBase64 = (base64, height) => + printImg(`data:image/gif;base64,${base64}`, height) + +/** + * @param {Array} args + */ +/* c8 ignore next 3 */ +export const group = (...args) => { + console.group(...computeLoggingArgs(args)) +} + +/** + * @param {Array} args + */ +/* c8 ignore next 3 */ +export const groupCollapsed = (...args) => { + console.groupCollapsed(...computeLoggingArgs(args)) +} + +/* c8 ignore next 3 */ +export const groupEnd = () => { + console.groupEnd() +} + +/** + * @param {function():Node} _createNode + */ +/* c8 ignore next 2 */ +export const printDom = (_createNode) => {} + +/** + * @param {HTMLCanvasElement} canvas + * @param {number} height + */ +/* c8 ignore next 2 */ +export const printCanvas = (canvas, height) => + printImg(canvas.toDataURL(), height) + +/** + * @param {Element} _dom + */ +/* c8 ignore next */ +export const createVConsole = (_dom) => {} + +/** + * @param {string} moduleName + * @return {function(...any):void} + */ +/* c8 ignore next */ +export const createModuleLogger = (moduleName) => common.createModuleLogger(print, moduleName) diff --git a/nodejs/node_modules/lib0/logging.test.d.ts b/nodejs/node_modules/lib0/logging.test.d.ts new file mode 100644 index 00000000..0bdf3291 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.test.d.ts @@ -0,0 +1,3 @@ +export function testLogging(): void; +export function testModuleLogger(): void; +//# sourceMappingURL=logging.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/logging.test.d.ts.map b/nodejs/node_modules/lib0/logging.test.d.ts.map new file mode 100644 index 00000000..38b69bf2 --- /dev/null +++ b/nodejs/node_modules/lib0/logging.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.test.d.ts","sourceRoot":"","sources":["logging.test.js"],"names":[],"mappings":"AAEO,oCAgBN;AAEM,yCAON"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/map.d.ts b/nodejs/node_modules/lib0/map.d.ts new file mode 100644 index 00000000..da32bdd3 --- /dev/null +++ b/nodejs/node_modules/lib0/map.d.ts @@ -0,0 +1,7 @@ +export function create(): Map; +export function copy(m: Map): Map; +export function setIfUndefined, CF extends MAP extends Map ? () => V : unknown>(map: MAP, key: MAP extends Map ? K : unknown, createT: CF): ReturnType; +export function map(m: Map, f: (arg0: V, arg1: K) => R): R[]; +export function any(m: Map, f: (arg0: V, arg1: K) => boolean): boolean; +export function all(m: Map, f: (arg0: V, arg1: K) => boolean): boolean; +//# sourceMappingURL=map.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/map.d.ts.map b/nodejs/node_modules/lib0/map.d.ts.map new file mode 100644 index 00000000..c13bb76b --- /dev/null +++ b/nodejs/node_modules/lib0/map.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["map.js"],"names":[],"mappings":"AAcO,0BAJK,IAAI,GAAG,EAAE,GAAG,CAAC,CAIY;AAU9B,oDAIN;AAkBM,iNAMN;AAaM,4EAMN;AAcM,iEAHkB,OAAO,GACpB,OAAO,CASlB;AAYM,iEAHkB,OAAO,GACpB,OAAO,CASlB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/map.js b/nodejs/node_modules/lib0/map.js new file mode 100644 index 00000000..ad2c6425 --- /dev/null +++ b/nodejs/node_modules/lib0/map.js @@ -0,0 +1,112 @@ +/** + * Utility module to work with key-value stores. + * + * @module map + */ + +/** + * Creates a new Map instance. + * + * @function + * @return {Map} + * + * @function + */ +export const create = () => new Map() + +/** + * Copy a Map object into a fresh Map object. + * + * @function + * @template K,V + * @param {Map} m + * @return {Map} + */ +export const copy = m => { + const r = create() + m.forEach((v, k) => { r.set(k, v) }) + return r +} + +/** + * Get map property. Create T if property is undefined and set T on map. + * + * ```js + * const listeners = map.setIfUndefined(events, 'eventName', set.create) + * listeners.add(listener) + * ``` + * + * @function + * @template {Map} MAP + * @template {MAP extends Map ? function():V : unknown} CF + * @param {MAP} map + * @param {MAP extends Map ? K : unknown} key + * @param {CF} createT + * @return {ReturnType} + */ +export const setIfUndefined = (map, key, createT) => { + let set = map.get(key) + if (set === undefined) { + map.set(key, set = createT()) + } + return set +} + +/** + * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function. + * + * @function + * @template K + * @template V + * @template R + * @param {Map} m + * @param {function(V,K):R} f + * @return {Array} + */ +export const map = (m, f) => { + const res = [] + for (const [key, value] of m) { + res.push(f(value, key)) + } + return res +} + +/** + * Tests whether any key-value pairs pass the test implemented by `f(value, key)`. + * + * @todo should rename to some - similarly to Array.some + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ +export const any = (m, f) => { + for (const [key, value] of m) { + if (f(value, key)) { + return true + } + } + return false +} + +/** + * Tests whether all key-value pairs pass the test implemented by `f(value, key)`. + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ +export const all = (m, f) => { + for (const [key, value] of m) { + if (!f(value, key)) { + return false + } + } + return true +} diff --git a/nodejs/node_modules/lib0/map.test.d.ts b/nodejs/node_modules/lib0/map.test.d.ts new file mode 100644 index 00000000..ca8dbcc5 --- /dev/null +++ b/nodejs/node_modules/lib0/map.test.d.ts @@ -0,0 +1,4 @@ +export function testMap(_tc: t.TestCase): void; +export function testTypeDefinitions(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=map.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/map.test.d.ts.map b/nodejs/node_modules/lib0/map.test.d.ts.map new file mode 100644 index 00000000..c19dc234 --- /dev/null +++ b/nodejs/node_modules/lib0/map.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.test.d.ts","sourceRoot":"","sources":["map.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QAsBpB;AAKM,yCAFI,EAAE,QAAQ,QAwBpB;mBApDkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/math.d.ts b/nodejs/node_modules/lib0/math.d.ts new file mode 100644 index 00000000..7490f904 --- /dev/null +++ b/nodejs/node_modules/lib0/math.d.ts @@ -0,0 +1,23 @@ +/** + * Common Math expressions. + * + * @module math + */ +export const floor: (x: number) => number; +export const ceil: (x: number) => number; +export const abs: (x: number) => number; +export const imul: (x: number, y: number) => number; +export const round: (x: number) => number; +export const log10: (x: number) => number; +export const log2: (x: number) => number; +export const log: (x: number) => number; +export const sqrt: (x: number) => number; +export function add(a: number, b: number): number; +export function min(a: number, b: number): number; +export function max(a: number, b: number): number; +export const isNaN: (number: unknown) => boolean; +export const pow: (x: number, y: number) => number; +export function exp10(exp: number): number; +export const sign: (x: number) => number; +export function isNegativeZero(n: number): boolean; +//# sourceMappingURL=math.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/math.d.ts.map b/nodejs/node_modules/lib0/math.d.ts.map new file mode 100644 index 00000000..ea6ecbec --- /dev/null +++ b/nodejs/node_modules/lib0/math.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"math.d.ts","sourceRoot":"","sources":["math.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,0CAA+B;AAC/B,yCAA6B;AAC7B,wCAA2B;AAC3B,oDAA6B;AAC7B,0CAA+B;AAC/B,0CAA+B;AAC/B,yCAA6B;AAC7B,wCAA2B;AAC3B,yCAA6B;AAQtB,uBAJI,MAAM,KACN,MAAM,GACL,MAAM,CAEgB;AAQ3B,uBAJI,MAAM,KACN,MAAM,GACL,MAAM,CAEwB;AAQnC,uBAJI,MAAM,KACN,MAAM,GACL,MAAM,CAEwB;AAE1C,iDAAiC;AAEjC,mDAA2B;AAOpB,2BAHI,MAAM,GACL,MAAM,CAE2B;AAE7C,yCAA6B;AAMtB,kCAHI,MAAM,GACL,OAAO,CAE2C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/math.js b/nodejs/node_modules/lib0/math.js new file mode 100644 index 00000000..b212545f --- /dev/null +++ b/nodejs/node_modules/lib0/math.js @@ -0,0 +1,58 @@ +/** + * Common Math expressions. + * + * @module math + */ + +export const floor = Math.floor +export const ceil = Math.ceil +export const abs = Math.abs +export const imul = Math.imul +export const round = Math.round +export const log10 = Math.log10 +export const log2 = Math.log2 +export const log = Math.log +export const sqrt = Math.sqrt + +/** + * @function + * @param {number} a + * @param {number} b + * @return {number} The sum of a and b + */ +export const add = (a, b) => a + b + +/** + * @function + * @param {number} a + * @param {number} b + * @return {number} The smaller element of a and b + */ +export const min = (a, b) => a < b ? a : b + +/** + * @function + * @param {number} a + * @param {number} b + * @return {number} The bigger element of a and b + */ +export const max = (a, b) => a > b ? a : b + +export const isNaN = Number.isNaN + +export const pow = Math.pow +/** + * Base 10 exponential function. Returns the value of 10 raised to the power of pow. + * + * @param {number} exp + * @return {number} + */ +export const exp10 = exp => Math.pow(10, exp) + +export const sign = Math.sign + +/** + * @param {number} n + * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0 + */ +export const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0 diff --git a/nodejs/node_modules/lib0/math.test.d.ts b/nodejs/node_modules/lib0/math.test.d.ts new file mode 100644 index 00000000..ff01d80f --- /dev/null +++ b/nodejs/node_modules/lib0/math.test.d.ts @@ -0,0 +1,3 @@ +export function testMath(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=math.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/math.test.d.ts.map b/nodejs/node_modules/lib0/math.test.d.ts.map new file mode 100644 index 00000000..ea0576c5 --- /dev/null +++ b/nodejs/node_modules/lib0/math.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"math.test.d.ts","sourceRoot":"","sources":["math.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QA0BpB;mBA/BkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/metric.d.ts b/nodejs/node_modules/lib0/metric.d.ts new file mode 100644 index 00000000..88482315 --- /dev/null +++ b/nodejs/node_modules/lib0/metric.d.ts @@ -0,0 +1,25 @@ +export const yotta: 1e+24; +export const zetta: 1e+21; +export const exa: 1000000000000000000; +export const peta: 1000000000000000; +export const tera: 1000000000000; +export const giga: 1000000000; +export const mega: 1000000; +export const kilo: 1000; +export const hecto: 100; +export const deca: 10; +export const deci: 0.1; +export const centi: 0.01; +export const milli: 0.001; +export const micro: 0.000001; +export const nano: 1e-9; +export const pico: 1e-12; +export const femto: 1e-15; +export const atto: 1e-18; +export const zepto: 1e-21; +export const yocto: 1e-24; +export function prefix(n: number, baseMultiplier?: number | undefined): { + n: number; + prefix: string; +}; +//# sourceMappingURL=metric.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/metric.d.ts.map b/nodejs/node_modules/lib0/metric.d.ts.map new file mode 100644 index 00000000..976b0dd6 --- /dev/null +++ b/nodejs/node_modules/lib0/metric.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metric.d.ts","sourceRoot":"","sources":["metric.js"],"names":[],"mappings":"AAQA,0BAAyB;AACzB,0BAAyB;AACzB,sCAAuB;AACvB,oCAAwB;AACxB,iCAAwB;AACxB,8BAAuB;AACvB,2BAAuB;AACvB,wBAAuB;AACvB,wBAAwB;AACxB,sBAAsB;AACtB,uBAAuB;AACvB,yBAAyB;AACzB,0BAAyB;AACzB,6BAAyB;AACzB,wBAAwB;AACxB,yBAAyB;AACzB,0BAA0B;AAC1B,yBAAyB;AACzB,0BAA0B;AAC1B,0BAA0B;AAYnB,0BAJI,MAAM;OAEF,MAAM;YAAQ,MAAM;EAkBlC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/metric.js b/nodejs/node_modules/lib0/metric.js new file mode 100644 index 00000000..6365453f --- /dev/null +++ b/nodejs/node_modules/lib0/metric.js @@ -0,0 +1,56 @@ +/** + * Utility module to convert metric values. + * + * @module metric + */ + +import * as math from './math.js' + +export const yotta = 1e24 +export const zetta = 1e21 +export const exa = 1e18 +export const peta = 1e15 +export const tera = 1e12 +export const giga = 1e9 +export const mega = 1e6 +export const kilo = 1e3 +export const hecto = 1e2 +export const deca = 10 +export const deci = 0.1 +export const centi = 0.01 +export const milli = 1e-3 +export const micro = 1e-6 +export const nano = 1e-9 +export const pico = 1e-12 +export const femto = 1e-15 +export const atto = 1e-18 +export const zepto = 1e-21 +export const yocto = 1e-24 + +const prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] +const prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y'] + +/** + * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }` + * + * @param {number} n + * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds + * @return {{n:number,prefix:string}} + */ +export const prefix = (n, baseMultiplier = 0) => { + const nPow = n === 0 ? 0 : math.log10(n) + let mult = 0 + while (nPow < mult * 3 && baseMultiplier > -8) { + baseMultiplier-- + mult-- + } + while (nPow >= 3 + mult * 3 && baseMultiplier < 8) { + baseMultiplier++ + mult++ + } + const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier] + return { + n: math.round((mult > 0 ? n / math.exp10(mult * 3) : n * math.exp10(mult * -3)) * 1e12) / 1e12, + prefix + } +} diff --git a/nodejs/node_modules/lib0/metric.test.d.ts b/nodejs/node_modules/lib0/metric.test.d.ts new file mode 100644 index 00000000..36727264 --- /dev/null +++ b/nodejs/node_modules/lib0/metric.test.d.ts @@ -0,0 +1,3 @@ +export function testMetricPrefix(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=metric.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/metric.test.d.ts.map b/nodejs/node_modules/lib0/metric.test.d.ts.map new file mode 100644 index 00000000..0d1e4757 --- /dev/null +++ b/nodejs/node_modules/lib0/metric.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metric.test.d.ts","sourceRoot":"","sources":["metric.test.js"],"names":[],"mappings":"AAMO,qCAFI,EAAE,QAAQ,QA8BpB;mBAlCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/mutex.d.ts b/nodejs/node_modules/lib0/mutex.d.ts new file mode 100644 index 00000000..92fd40fd --- /dev/null +++ b/nodejs/node_modules/lib0/mutex.d.ts @@ -0,0 +1,3 @@ +export function createMutex(): mutex; +export type mutex = (cb: () => void, elseCb?: (() => void) | undefined) => any; +//# sourceMappingURL=mutex.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/mutex.d.ts.map b/nodejs/node_modules/lib0/mutex.d.ts.map new file mode 100644 index 00000000..83a729b1 --- /dev/null +++ b/nodejs/node_modules/lib0/mutex.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mutex.d.ts","sourceRoot":"","sources":["mutex.js"],"names":[],"mappings":"AA4BO,+BAHK,KAAK,CAiBhB;+BAlCqB,IAAI,kBACJ,IAAI"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/mutex.js b/nodejs/node_modules/lib0/mutex.js new file mode 100644 index 00000000..41513efb --- /dev/null +++ b/nodejs/node_modules/lib0/mutex.js @@ -0,0 +1,43 @@ +/** + * Mutual exclude for JavaScript. + * + * @module mutex + */ + +/** + * @callback mutex + * @param {function():void} cb Only executed when this mutex is not in the current stack + * @param {function():void} [elseCb] Executed when this mutex is in the current stack + */ + +/** + * Creates a mutual exclude function with the following property: + * + * ```js + * const mutex = createMutex() + * mutex(() => { + * // This function is immediately executed + * mutex(() => { + * // This function is not executed, as the mutex is already active. + * }) + * }) + * ``` + * + * @return {mutex} A mutual exclude function + * @public + */ +export const createMutex = () => { + let token = true + return (f, g) => { + if (token) { + token = false + try { + f() + } finally { + token = true + } + } else if (g !== undefined) { + g() + } + } +} diff --git a/nodejs/node_modules/lib0/number.d.ts b/nodejs/node_modules/lib0/number.d.ts new file mode 100644 index 00000000..59c3e6a6 --- /dev/null +++ b/nodejs/node_modules/lib0/number.d.ts @@ -0,0 +1,10 @@ +export const MAX_SAFE_INTEGER: number; +export const MIN_SAFE_INTEGER: number; +export const LOWEST_INT32: number; +export const HIGHEST_INT32: number; +export const HIGHEST_UINT32: number; +export const isInteger: (number: unknown) => boolean; +export const isNaN: (number: unknown) => boolean; +export const parseInt: (string: string, radix?: number | undefined) => number; +export function countBits(n: number): number; +//# sourceMappingURL=number.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/number.d.ts.map b/nodejs/node_modules/lib0/number.d.ts.map new file mode 100644 index 00000000..31e96fc3 --- /dev/null +++ b/nodejs/node_modules/lib0/number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.ts","sourceRoot":"","sources":["number.js"],"names":[],"mappings":"AASA,sCAAuD;AACvD,sCAAuD;AAEvD,kCAAmC;AACnC,mCAA0C;AAC1C,oCAA2C;AAG3C,qDAAyH;AACzH,iDAAiC;AACjC,8EAAuC;AAShC,6BAFI,MAAM,UAUhB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/number.js b/nodejs/node_modules/lib0/number.js new file mode 100644 index 00000000..bbc297a2 --- /dev/null +++ b/nodejs/node_modules/lib0/number.js @@ -0,0 +1,37 @@ +/** + * Utility helpers for working with numbers. + * + * @module number + */ + +import * as math from './math.js' +import * as binary from './binary.js' + +export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER +export const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER + +export const LOWEST_INT32 = 1 << 31 +export const HIGHEST_INT32 = binary.BITS31 +export const HIGHEST_UINT32 = binary.BITS32 + +/* c8 ignore next */ +export const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num) +export const isNaN = Number.isNaN +export const parseInt = Number.parseInt + +/** + * Count the number of "1" bits in an unsigned 32bit number. + * + * Super fun bitcount algorithm by Brian Kernighan. + * + * @param {number} n + */ +export const countBits = n => { + n &= binary.BITS32 + let count = 0 + while (n) { + n &= (n - 1) + count++ + } + return count +} diff --git a/nodejs/node_modules/lib0/number.test.d.ts b/nodejs/node_modules/lib0/number.test.d.ts new file mode 100644 index 00000000..71df1857 --- /dev/null +++ b/nodejs/node_modules/lib0/number.test.d.ts @@ -0,0 +1,4 @@ +export function testNumber(_tc: t.TestCase): void; +export function testShiftVsDivision(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=number.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/number.test.d.ts.map b/nodejs/node_modules/lib0/number.test.d.ts.map new file mode 100644 index 00000000..d040cb0f --- /dev/null +++ b/nodejs/node_modules/lib0/number.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.test.d.ts","sourceRoot":"","sources":["number.test.js"],"names":[],"mappings":"AAQO,gCAFI,EAAE,QAAQ,QAiBpB;AAOM,wCAFI,EAAE,QAAQ,QA6DpB;mBAzFkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/object.d.ts b/nodejs/node_modules/lib0/object.d.ts new file mode 100644 index 00000000..4233fccc --- /dev/null +++ b/nodejs/node_modules/lib0/object.d.ts @@ -0,0 +1,42 @@ +export function create(): { + [x: string]: any; +}; +/** + * Object.assign + */ +export const assign: { + (target: T, source: U): T & U; + (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; + (target: T_2, source1: U_2, source2: V_1, source3: W): T_2 & U_2 & V_1 & W; + (target: object, ...sources: any[]): any; +}; +/** + * @param {Object} obj + */ +export const keys: { + (o: object): string[]; + (o: {}): string[]; +}; +export function forEach(obj: { + [k: string]: V; +}, f: (arg0: V, arg1: string) => any): void; +export function map(obj: { + [x: string]: any; +}, f: (arg0: any, arg1: string) => R): R[]; +export function length(obj: { + [x: string]: any; +}): number; +export function some(obj: { + [x: string]: any; +}, f: (arg0: any, arg1: string) => boolean): boolean; +export function isEmpty(obj: Object | undefined): boolean; +export function every(obj: { + [x: string]: any; +}, f: (arg0: any, arg1: string) => boolean): boolean; +export function hasProperty(obj: any, key: string | symbol): boolean; +export function equalFlat(a: { + [x: string]: any; +}, b: { + [x: string]: any; +}): boolean; +//# sourceMappingURL=object.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/object.d.ts.map b/nodejs/node_modules/lib0/object.d.ts.map new file mode 100644 index 00000000..8084fe25 --- /dev/null +++ b/nodejs/node_modules/lib0/object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["object.js"],"names":[],"mappings":"AASO;QAFY,MAAM,GAAC,GAAG;EAEkB;AAE/C;;GAEG;AACH;;;;;EAAmC;AAEnC;;GAEG;AACH;;;EAA+B;AAOxB;;sBAFe,MAAM,KAAE,GAAG,QAMhC;AAUM;QAJW,MAAM,GAAC,GAAG;aACR,GAAG,QAAC,MAAM,aAS7B;AAMM;QAHW,MAAM,GAAC,GAAG;IAChB,MAAM,CAE2B;AAOtC;QAJW,MAAM,GAAC,GAAG;aACR,GAAG,QAAC,MAAM,KAAE,OAAO,GAC3B,OAAO,CASlB;AAKM,6BAFI,MAAM,GAAC,SAAS,WAQ1B;AAOM;QAJW,MAAM,GAAC,GAAG;aACR,GAAG,QAAC,MAAM,KAAE,OAAO,GAC3B,OAAO,CASlB;AASM,iCAJI,GAAG,OACH,MAAM,GAAC,MAAM,GACZ,OAAO,CAEoE;AAOhF;QAJW,MAAM,GAAC,GAAG;;QACV,MAAM,GAAC,GAAG;IAChB,OAAO,CAE4I"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/object.js b/nodejs/node_modules/lib0/object.js new file mode 100644 index 00000000..149448c1 --- /dev/null +++ b/nodejs/node_modules/lib0/object.js @@ -0,0 +1,108 @@ +/** + * Utility functions for working with EcmaScript objects. + * + * @module object + */ + +/** + * @return {Object} obj + */ +export const create = () => Object.create(null) + +/** + * Object.assign + */ +export const assign = Object.assign + +/** + * @param {Object} obj + */ +export const keys = Object.keys + +/** + * @template V + * @param {{[k:string]:V}} obj + * @param {function(V,string):any} f + */ +export const forEach = (obj, f) => { + for (const key in obj) { + f(obj[key], key) + } +} + +/** + * @todo implement mapToArray & map + * + * @template R + * @param {Object} obj + * @param {function(any,string):R} f + * @return {Array} + */ +export const map = (obj, f) => { + const results = [] + for (const key in obj) { + results.push(f(obj[key], key)) + } + return results +} + +/** + * @param {Object} obj + * @return {number} + */ +export const length = obj => keys(obj).length + +/** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ +export const some = (obj, f) => { + for (const key in obj) { + if (f(obj[key], key)) { + return true + } + } + return false +} + +/** + * @param {Object|undefined} obj + */ +export const isEmpty = obj => { + // eslint-disable-next-line + for (const _k in obj) { + return false + } + return true +} + +/** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ +export const every = (obj, f) => { + for (const key in obj) { + if (!f(obj[key], key)) { + return false + } + } + return true +} + +/** + * Calls `Object.prototype.hasOwnProperty`. + * + * @param {any} obj + * @param {string|symbol} key + * @return {boolean} + */ +export const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key) + +/** + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ +export const equalFlat = (a, b) => a === b || (length(a) === length(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val)) diff --git a/nodejs/node_modules/lib0/object.test.d.ts b/nodejs/node_modules/lib0/object.test.d.ts new file mode 100644 index 00000000..f6472902 --- /dev/null +++ b/nodejs/node_modules/lib0/object.test.d.ts @@ -0,0 +1,3 @@ +export function testObject(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=object.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/object.test.d.ts.map b/nodejs/node_modules/lib0/object.test.d.ts.map new file mode 100644 index 00000000..0e5a7bdd --- /dev/null +++ b/nodejs/node_modules/lib0/object.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.test.d.ts","sourceRoot":"","sources":["object.test.js"],"names":[],"mappings":"AAOO,gCAFI,EAAE,QAAQ,QA+BpB;mBApCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/observable.d.ts b/nodejs/node_modules/lib0/observable.d.ts new file mode 100644 index 00000000..590b1566 --- /dev/null +++ b/nodejs/node_modules/lib0/observable.d.ts @@ -0,0 +1,86 @@ +/** + * Handles named events. + * @experimental + * + * This is basically a (better typed) duplicate of Observable, which will replace Observable in the + * next release. + * + * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS + */ +export class ObservableV2 void; }> { + /** + * Some desc. + * @type {Map>} + */ + _observers: Map>; + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + on(name: NAME, f: EVENTS[NAME]): EVENTS[NAME]; + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + once(name: NAME_1, f: EVENTS[NAME_1]): void; + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + off(name: NAME_2, f: EVENTS[NAME_2]): void; + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @template {keyof EVENTS & string} NAME + * @param {NAME} name The event name. + * @param {Parameters} args The arguments that are applied to the event listener. + */ + emit(name: NAME_3, args: Parameters): void; + destroy(): void; +} +/** + * Handles named events. + * + * @deprecated + * @template N + */ +export class Observable { + /** + * Some desc. + * @type {Map} + */ + _observers: Map; + /** + * @param {N} name + * @param {function} f + */ + on(name: N, f: Function): void; + /** + * @param {N} name + * @param {function} f + */ + once(name: N, f: Function): void; + /** + * @param {N} name + * @param {function} f + */ + off(name: N, f: Function): void; + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit(name: N, args: Array): void; + destroy(): void; +} +//# sourceMappingURL=observable.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/observable.d.ts.map b/nodejs/node_modules/lib0/observable.d.ts.map new file mode 100644 index 00000000..04464bc2 --- /dev/null +++ b/nodejs/node_modules/lib0/observable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"observable.d.ts","sourceRoot":"","sources":["observable.js"],"names":[],"mappings":"AAUA;;;;;;;;GAQG;AACH,4EAFkD,GAAG,OAAE,IAAI;IAIvD;;;OAGG;IACH,YAFU,IAAI,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,CAED;IAGhC;;;;OAIG;IACH,kFAGC;IAED;;;;OAIG;IACH,kFASC;IAED;;;;OAIG;IACH,iFAQC;IAED;;;;;;;;;OASG;IACH,iGAGC;IAED,gBAEC;CACF;AAGD;;;;;GAKG;AACH;IAEI;;;OAGG;IACH,YAFU,IAAI,CAAC,EAAE,GAAG,CAAC,CAES;IAGhC;;;OAGG;IACH,SAHW,CAAC,qBAKX;IAED;;;OAGG;IACH,WAHW,CAAC,qBAYX;IAED;;;OAGG;IACH,UAHW,CAAC,qBAWX;IAED;;;;;;;;OAQG;IACH,WAHW,CAAC,QACD,MAAM,GAAG,CAAC,QAKpB;IAED,gBAEC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/observable.js b/nodejs/node_modules/lib0/observable.js new file mode 100644 index 00000000..c1c0ed26 --- /dev/null +++ b/nodejs/node_modules/lib0/observable.js @@ -0,0 +1,161 @@ +/** + * Observable class prototype. + * + * @module observable + */ + +import * as map from './map.js' +import * as set from './set.js' +import * as array from './array.js' + +/** + * Handles named events. + * @experimental + * + * This is basically a (better typed) duplicate of Observable, which will replace Observable in the + * next release. + * + * @template {{[key in keyof EVENTS]: function(...any):void}} EVENTS + */ +export class ObservableV2 { + constructor () { + /** + * Some desc. + * @type {Map>} + */ + this._observers = map.create() + } + + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + on (name, f) { + map.setIfUndefined(this._observers, /** @type {string} */ (name), set.create).add(f) + return f + } + + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, /** @type {any} */ (_f)) + f(...args) + } + this.on(name, /** @type {any} */ (_f)) + } + + /** + * @template {keyof EVENTS & string} NAME + * @param {NAME} name + * @param {EVENTS[NAME]} f + */ + off (name, f) { + const observers = this._observers.get(name) + if (observers !== undefined) { + observers.delete(f) + if (observers.size === 0) { + this._observers.delete(name) + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @template {keyof EVENTS & string} NAME + * @param {NAME} name The event name. + * @param {Parameters} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = map.create() + } +} + +/* c8 ignore start */ +/** + * Handles named events. + * + * @deprecated + * @template N + */ +export class Observable { + constructor () { + /** + * Some desc. + * @type {Map} + */ + this._observers = map.create() + } + + /** + * @param {N} name + * @param {function} f + */ + on (name, f) { + map.setIfUndefined(this._observers, name, set.create).add(f) + } + + /** + * @param {N} name + * @param {function} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, _f) + f(...args) + } + this.on(name, _f) + } + + /** + * @param {N} name + * @param {function} f + */ + off (name, f) { + const observers = this._observers.get(name) + if (observers !== undefined) { + observers.delete(f) + if (observers.size === 0) { + this._observers.delete(name) + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return array.from((this._observers.get(name) || map.create()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = map.create() + } +} +/* c8 ignore end */ diff --git a/nodejs/node_modules/lib0/observable.test.d.ts b/nodejs/node_modules/lib0/observable.test.d.ts new file mode 100644 index 00000000..895ebfe4 --- /dev/null +++ b/nodejs/node_modules/lib0/observable.test.d.ts @@ -0,0 +1,3 @@ +export function testTypedObservable(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=observable.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/observable.test.d.ts.map b/nodejs/node_modules/lib0/observable.test.d.ts.map new file mode 100644 index 00000000..e43826b2 --- /dev/null +++ b/nodejs/node_modules/lib0/observable.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"observable.test.d.ts","sourceRoot":"","sources":["observable.test.js"],"names":[],"mappings":"AAMO,yCAFI,EAAE,QAAQ,QA6CpB;mBAjDkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/package.json b/nodejs/node_modules/lib0/package.json new file mode 100644 index 00000000..846f9a72 --- /dev/null +++ b/nodejs/node_modules/lib0/package.json @@ -0,0 +1,531 @@ +{ + "name": "lib0", + "version": "0.2.93", + "description": "", + "sideEffects": false, + "type": "module", + "main": "./dist/index.cjs", + "module": "./index.js", + "types": "./index.d.ts", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "bin": { + "0gentesthtml": "./bin/gentesthtml.js", + "0serve": "./bin/0serve.js", + "0ecdsa-generate-keypair": "./bin/0ecdsa-generate-keypair.js" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./index.d.ts", + "module": "./index.js", + "import": "./index.js", + "require": "./dist/index.cjs" + }, + "./array.js": "./array.js", + "./dist/array.cjs": "./dist/array.cjs", + "./array": { + "types": "./array.d.ts", + "module": "./array.js", + "import": "./array.js", + "require": "./dist/array.cjs" + }, + "./binary.js": "./binary.js", + "./dist/binary.cjs": "./dist/binary.cjs", + "./binary": { + "types": "./binary.d.ts", + "module": "./binary.js", + "import": "./binary.js", + "require": "./dist/binary.cjs" + }, + "./broadcastchannel.js": "./broadcastchannel.js", + "./dist/broadcastchannel.cjs": "./dist/broadcastchannel.cjs", + "./broadcastchannel": { + "types": "./broadcastchannel.d.ts", + "module": "./broadcastchannel.js", + "import": "./broadcastchannel.js", + "require": "./dist/broadcastchannel.cjs" + }, + "./buffer.js": "./buffer.js", + "./dist/buffer.cjs": "./dist/buffer.cjs", + "./buffer": { + "types": "./buffer.d.ts", + "module": "./buffer.js", + "import": "./buffer.js", + "require": "./dist/buffer.cjs" + }, + "./cache.js": "./cache.js", + "./dist/cache.cjs": "./dist/cache.cjs", + "./cache": { + "types": "./cache.d.ts", + "module": "./cache.js", + "import": "./cache.js", + "require": "./dist/cache.cjs" + }, + "./component.js": "./component.js", + "./dist/component.cjs": "./dist/component.cjs", + "./component": { + "types": "./component.d.ts", + "module": "./component.js", + "import": "./component.js", + "require": "./dist/component.cjs" + }, + "./conditions.js": "./conditions.js", + "./dist/conditions.cjs": "./dist/conditions.cjs", + "./conditions": { + "types": "./condititons.d.ts", + "module": "./condititons.js", + "import": "./condititons.js", + "require": "./dist/conditions.cjs" + }, + "./crypto/jwt": { + "types": "./crypto/jwt.d.ts", + "module": "./crypto/jwt.js", + "import": "./crypto/jwt.js", + "require": "./dist/jwt.cjs" + }, + "./crypto/aes-gcm": { + "types": "./crypto/aes-gcm.d.ts", + "module": "./crypto/aes-gcm.js", + "import": "./crypto/aes-gcm.js", + "require": "./dist/aes-gcm.cjs" + }, + "./crypto/ecdsa": { + "types": "./crypto/ecdsa.d.ts", + "module": "./crypto/ecdsa.js", + "import": "./crypto/ecdsa.js", + "require": "./dist/ecdsa.cjs" + }, + "./crypto/rsa-oaep": { + "types": "./crypto/rsa-oaep.d.ts", + "module": "./crypto/rsa-oaep.js", + "import": "./crypto/rsa-oaep.js", + "require": "./dist/rsa-oaep.cjs" + }, + "./hash/rabin": { + "types": "./hash/rabin.d.ts", + "module": "./hash/rabin.js", + "import": "./hash/rabin.js", + "require": "./dist/rabin.cjs" + }, + "./hash/sha256": { + "types": "./hash/sha256.d.ts", + "browser": { + "module": "./hash/sha256.js", + "require": "./dist/sha256.cjs", + "default": "./hash/sha256.js" + }, + "node": { + "require": "./dist/sha256.node.cjs", + "default": "./hash/sha256.node.js" + }, + "default": { + "module": "./hash/sha256.js", + "require": "./dist/sha256.cjs", + "default": "./hash/sha256.js" + } + }, + "./decoding.js": "./decoding.js", + "./dist/decoding.cjs": "./dist/decoding.cjs", + "./decoding": { + "types": "./decoding.d.ts", + "module": "./decoding.js", + "import": "./decoding.js", + "require": "./dist/decoding.cjs" + }, + "./diff.js": "./diff.js", + "./dist/diff.cjs": "./dist/diff.cjs", + "./diff": { + "types": "./diff.d.ts", + "module": "./diff.js", + "import": "./diff.js", + "require": "./dist/diff.cjs" + }, + "./dom.js": "./dom.js", + "./dist/dom.cjs": "./dist/dom.cjs", + "./dom": { + "types": "./dom.d.ts", + "module": "./dom.js", + "import": "./dom.js", + "require": "./dist/dom.cjs" + }, + "./encoding.js": "./encoding.js", + "./dist/encoding.cjs": "./dist/encoding.cjs", + "./encoding": { + "types": "./encoding.d.ts", + "module": "./encoding.js", + "import": "./encoding.js", + "require": "./dist/encoding.cjs" + }, + "./environment.js": "./environment.js", + "./dist/environment.cjs": "./dist/environment.cjs", + "./environment": { + "types": "./environment.d.ts", + "module": "./environment.js", + "import": "./environment.js", + "require": "./dist/environment.cjs" + }, + "./error.js": "./error.js", + "./dist/error.cjs": "./dist/error.cjs", + "./error": { + "types": "./error.d.ts", + "module": "./error.js", + "import": "./error.js", + "require": "./dist/error.cjs" + }, + "./eventloop.js": "./eventloop.js", + "./dist/eventloop.cjs": "./dist/eventloop.cjs", + "./eventloop": { + "types": "./eventloop.d.ts", + "module": "./eventloop.js", + "import": "./eventloop.js", + "require": "./dist/eventloop.cjs" + }, + "./function.js": "./function.js", + "./dist/function.cjs": "./dist/function.cjs", + "./function": { + "types": "./function.d.ts", + "module": "./function.js", + "import": "./function.js", + "require": "./dist/function.cjs" + }, + "./indexeddb.js": "./indexeddb.js", + "./dist/indexeddb.cjs": "./dist/indexeddb.cjs", + "./indexeddb": { + "types": "./indexeddb.d.ts", + "module": "./indexeddb.js", + "import": "./indexeddb.js", + "require": "./dist/indexeddb.cjs" + }, + "./isomorphic.js": "./isomorphic.js", + "./dist/isomorphic.cjs": "./dist/isomorphic.cjs", + "./isomorphic": { + "types": "./isomorphic.d.ts", + "module": "./isomorphic.js", + "import": "./isomorphic.js", + "require": "./dist/isomorphic.cjs" + }, + "./iterator.js": "./iterator.js", + "./dist/iterator.cjs": "./dist/iterator.cjs", + "./iterator": { + "types": "./iterator.d.ts", + "module": "./iterator.js", + "import": "./iterator.js", + "require": "./dist/iterator.cjs" + }, + "./json.js": "./json.js", + "./dist/json.cjs": "./dist/json.cjs", + "./json": { + "types": "./json.d.ts", + "module": "./json.js", + "import": "./json.js", + "require": "./dist/json.cjs" + }, + "./list.js": "./list.js", + "./dist/list.cjs": "./dist/list.cjs", + "./list": { + "types": "./list.d.ts", + "module": "./list.js", + "import": "./list.js", + "require": "./dist/list.cjs" + }, + "./logging.js": "./logging.js", + "./dist/logging.cjs": "./dist/logging.node.cjs", + "./logging": { + "types": "./logging.node.d.ts", + "deno": "./logging.node.js", + "bun": "./logging.js", + "browser": { + "module": "./logging.js", + "require": "./dist/logging.cjs", + "default": "./logging.js" + }, + "node": { + "module": "./logging.node.js", + "require": "./dist/logging.node.cjs", + "default": "./logging.node.js" + }, + "default": { + "module": "./logging.js", + "require": "./dist/logging.cjs", + "default": "./logging.js" + } + }, + "./map.js": "./map.js", + "./dist/map.cjs": "./dist/map.cjs", + "./map": { + "types": "./map.d.ts", + "module": "./map.js", + "import": "./map.js", + "require": "./dist/map.cjs" + }, + "./math.js": "./math.js", + "./dist/math.cjs": "./dist/math.cjs", + "./math": { + "types": "./math.d.ts", + "module": "./math.js", + "import": "./math.js", + "require": "./dist/math.cjs" + }, + "./metric.js": "./metric.js", + "./dist/metric.cjs": "./dist/metric.cjs", + "./metric": { + "types": "./metric.d.ts", + "module": "./metric.js", + "import": "./metric.js", + "require": "./dist/metric.cjs" + }, + "./mutex.js": "./mutex.js", + "./dist/mutex.cjs": "./dist/mutex.cjs", + "./mutex": { + "types": "./mutex.d.ts", + "module": "./mutex.js", + "import": "./mutex.js", + "require": "./dist/mutex.cjs" + }, + "./number.js": "./number.js", + "./dist/number.cjs": "./dist/number.cjs", + "./number": { + "types": "./number.d.ts", + "module": "./number.js", + "import": "./number.js", + "require": "./dist/number.cjs" + }, + "./object.js": "./object.js", + "./dist/object.cjs": "./dist/object.cjs", + "./object": { + "types": "./object.d.ts", + "module": "./object.js", + "import": "./object.js", + "require": "./dist/object.cjs" + }, + "./observable.js": "./observable.js", + "./dist/observable.cjs": "./dist/observable.cjs", + "./observable": { + "types": "./observable.d.ts", + "module": "./observable.js", + "import": "./observable.js", + "require": "./dist/observable.cjs" + }, + "./pair.js": "./pair.js", + "./dist/pair.cjs": "./dist/pair.cjs", + "./pair": { + "types": "./pair.d.ts", + "module": "./pair.js", + "import": "./pair.js", + "require": "./dist/pair.cjs" + }, + "./prng.js": "./prng.js", + "./dist/prng.cjs": "./dist/prng.cjs", + "./prng": { + "types": "./prng.d.ts", + "module": "./prng.js", + "import": "./prng.js", + "require": "./dist/prng.cjs" + }, + "./promise.js": "./promise.js", + "./dist/promise.cjs": "./dist/promise.cjs", + "./promise": { + "types": "./promise.d.ts", + "module": "./promise.js", + "import": "./promise.js", + "require": "./dist/promise.cjs" + }, + "./queue.js": "./queue.js", + "./dist/queue.cjs": "./dist/queue.cjs", + "./queue": { + "types": "./queue.d.ts", + "module": "./queue.js", + "import": "./queue.js", + "require": "./dist/queue.cjs" + }, + "./random.js": "./random.js", + "./dist/random.cjs": "./dist/random.cjs", + "./random": { + "types": "./random.d.ts", + "module": "./random.js", + "import": "./random.js", + "require": "./dist/random.cjs" + }, + "./set.js": "./set.js", + "./dist/set.cjs": "./dist/set.cjs", + "./set": { + "types": "./set.d.ts", + "module": "./set.js", + "import": "./set.js", + "require": "./dist/set.cjs" + }, + "./sort.js": "./sort.js", + "./dist/sort.cjs": "./dist/sort.cjs", + "./sort": { + "types": "./sort.d.ts", + "module": "./sort.js", + "import": "./sort.js", + "require": "./dist/sort.cjs" + }, + "./statistics.js": "./statistics.js", + "./dist/statistics.cjs": "./dist/statistics.cjs", + "./statistics": { + "types": "./statistics.d.ts", + "module": "./statistics.js", + "import": "./statistics.js", + "require": "./dist/statistics.cjs" + }, + "./storage.js": "./storage.js", + "./dist/storage.cjs": "./dist/storage.cjs", + "./storage": { + "types": "./storage.d.ts", + "module": "./storage.js", + "import": "./storage.js", + "require": "./dist/storage.cjs" + }, + "./string.js": "./string.js", + "./dist/string.cjs": "./dist/string.cjs", + "./string": { + "types": "./string.d.ts", + "module": "./string.js", + "import": "./string.js", + "require": "./dist/string.cjs" + }, + "./symbol.js": "./symbol.js", + "./dist/symbol.cjs": "./dist/symbol.cjs", + "./symbol": { + "types": "./symbol.d.ts", + "module": "./symbol.js", + "import": "./symbol.js", + "require": "./dist/symbol.cjs" + }, + "./testing.js": "./testing.js", + "./dist/testing.cjs": "./dist/testing.cjs", + "./testing": { + "types": "./testing.d.ts", + "module": "./testing.js", + "import": "./testing.js", + "require": "./dist/testing.cjs" + }, + "./time.js": "./time.js", + "./dist/time.cjs": "./dist/time.cjs", + "./time": { + "types": "./time.d.ts", + "module": "./time.js", + "import": "./time.js", + "require": "./dist/time.cjs" + }, + "./tree.js": "./tree.js", + "./dist/tree.cjs": "./dist/tree.cjs", + "./tree": { + "types": "./tree.d.ts", + "module": "./tree.js", + "import": "./tree.js", + "require": "./dist/tree.cjs" + }, + "./url.js": "./url.js", + "./dist/url.cjs": "./dist/url.cjs", + "./url": { + "types": "./url.d.ts", + "module": "./url.js", + "import": "./url.js", + "require": "./dist/url.cjs" + }, + "./websocket.js": "./websocket.js", + "./dist/websocket.cjs": "./dist/websocket.cjs", + "./websocket": { + "types": "./websocket.d.ts", + "module": "./websocket.js", + "import": "./websocket.js", + "require": "./dist/websocket.cjs" + }, + "./webcrypto": { + "types": "./webcrypto.d.ts", + "deno": "./webcrypto.deno.js", + "bun": "./webcrypto.js", + "browser": { + "module": "./webcrypto.js", + "require": "./dist/webcrypto.cjs", + "default": "./webcrypto.js" + }, + "node": { + "module": "./webcrypto.node.js", + "require": "./dist/webcrypto.node.cjs", + "default": "./webcrypto.node.js" + }, + "default": { + "module": "./webcrypto.js", + "require": "./dist/webcrypto.cjs", + "default": "./webcrypto.js" + } + }, + "./performance.js": "./performance.js", + "./dist/performance.cjs": "./dist/performance.node.cjs", + "./performance": { + "types": "./performance.d.ts", + "deno": "./performance.node.js", + "bun": "./performance.node.js", + "browser": { + "module": "./performance.js", + "require": "./dist/performance.cjs", + "default": "./performance.js" + }, + "node": { + "module": "./performance.node.js", + "require": "./dist/performance.node.cjs", + "default": "./performance.node.js" + }, + "default": { + "module": "./performance.js", + "require": "./dist/performance.cjs", + "default": "./performance.js" + } + } + }, + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "devDependencies": { + "@types/node": "^18.14.0", + "c8": "^7.13.0", + "jsdoc-api": "^8.0.0", + "jsdoc-plugin-typescript": "^2.2.1", + "rollup": "^2.42.1", + "standard": "^17.1.0", + "typescript": "^5.0.2" + }, + "scripts": { + "clean": "rm -rf dist *.d.ts */*.d.ts *.d.ts.map */*.d.ts.map", + "types": "tsc --outDir .", + "dist": "rollup -c", + "debug": "npm run gentesthtml && node ./bin/0serve.js -o test.html", + "test": "c8 --check-coverage --lines 100 --branches 100 --functions 100 --statements 100 node --unhandled-rejections=strict ./test.js --repetition-time 50 --production", + "test-inspect": "node --inspect-brk --unhandled-rejections=strict ./test.js --repetition-time 50 --production", + "test-extensive": "c8 --check-coverage --lines 100 --branches 100 --functions 100 --statements 100 node test.js --repetition-time 30000 --extensive --production", + "trace-deopt": "clear && rollup -c && node --trace-deopt dist/test.cjs", + "trace-opt": "clear && rollup -c && node --trace-opt dist/test.cjs", + "lint": "standard && tsc", + "gendocs": "node ./bin/gendocs.js", + "preversion": "npm run clean && npm run lint && npm run test && npm run types && npm run dist && git add README.md", + "postpublish": "npm run clean", + "gentesthtml": "node ./bin/gentesthtml.js --script test.js > test.html" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dmonad/lib0.git" + }, + "author": "Kevin Jahns ", + "license": "MIT", + "bugs": { + "url": "https://github.com/dmonad/lib0/issues" + }, + "homepage": "https://github.com/dmonad/lib0#readme", + "standard": { + "ignore": [ + "/dist", + "/node_modules", + "/docs" + ] + }, + "engines": { + "node": ">=16" + } +} diff --git a/nodejs/node_modules/lib0/pair.d.ts b/nodejs/node_modules/lib0/pair.d.ts new file mode 100644 index 00000000..fcb7d8b0 --- /dev/null +++ b/nodejs/node_modules/lib0/pair.d.ts @@ -0,0 +1,22 @@ +/** + * Working with value pairs. + * + * @module pair + */ +/** + * @template L,R + */ +export class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor(left: L, right: R); + left: L; + right: R; +} +export function create(left: L, right: R): Pair; +export function createReversed(right: R, left: L): Pair; +export function forEach(arr: Pair[], f: (arg0: L, arg1: R) => any): void; +export function map(arr: Pair[], f: (arg0: L, arg1: R) => X): X[]; +//# sourceMappingURL=pair.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/pair.d.ts.map b/nodejs/node_modules/lib0/pair.d.ts.map new file mode 100644 index 00000000..adae82d0 --- /dev/null +++ b/nodejs/node_modules/lib0/pair.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pair.d.ts","sourceRoot":"","sources":["pair.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH;IACE;;;OAGG;IACH,kBAHW,CAAC,SACD,CAAC,EAKX;IAFC,QAAgB;IAChB,SAAkB;CAErB;AAQM,4DAAqD;AAQrD,oEAA6D;AAO7D,0EAFmB,GAAG,QAE0C;AAQhE,iFAAwD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/pair.js b/nodejs/node_modules/lib0/pair.js new file mode 100644 index 00000000..8b88e7ea --- /dev/null +++ b/nodejs/node_modules/lib0/pair.js @@ -0,0 +1,50 @@ +/** + * Working with value pairs. + * + * @module pair + */ + +/** + * @template L,R + */ +export class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor (left, right) { + this.left = left + this.right = right + } +} + +/** + * @template L,R + * @param {L} left + * @param {R} right + * @return {Pair} + */ +export const create = (left, right) => new Pair(left, right) + +/** + * @template L,R + * @param {R} right + * @param {L} left + * @return {Pair} + */ +export const createReversed = (right, left) => new Pair(left, right) + +/** + * @template L,R + * @param {Array>} arr + * @param {function(L, R):any} f + */ +export const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right)) + +/** + * @template L,R,X + * @param {Array>} arr + * @param {function(L, R):X} f + * @return {Array} + */ +export const map = (arr, f) => arr.map(p => f(p.left, p.right)) diff --git a/nodejs/node_modules/lib0/pair.test.d.ts b/nodejs/node_modules/lib0/pair.test.d.ts new file mode 100644 index 00000000..ab51b8bc --- /dev/null +++ b/nodejs/node_modules/lib0/pair.test.d.ts @@ -0,0 +1,3 @@ +export function testPair(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=pair.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/pair.test.d.ts.map b/nodejs/node_modules/lib0/pair.test.d.ts.map new file mode 100644 index 00000000..51160901 --- /dev/null +++ b/nodejs/node_modules/lib0/pair.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pair.test.d.ts","sourceRoot":"","sources":["pair.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QAepB;mBApBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/performance.d.ts b/nodejs/node_modules/lib0/performance.d.ts new file mode 100644 index 00000000..7d24b63a --- /dev/null +++ b/nodejs/node_modules/lib0/performance.d.ts @@ -0,0 +1,4 @@ +export const measure: (measureName: string, startOrMeasureOptions?: string | PerformanceMeasureOptions | undefined, endMark?: string | undefined) => PerformanceMeasure; +export const now: () => number; +export const mark: (markName: string, markOptions?: PerformanceMarkOptions | undefined) => PerformanceMark; +//# sourceMappingURL=performance.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/performance.d.ts.map b/nodejs/node_modules/lib0/performance.d.ts.map new file mode 100644 index 00000000..c65f6752 --- /dev/null +++ b/nodejs/node_modules/lib0/performance.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"performance.d.ts","sourceRoot":"","sources":["performance.js"],"names":[],"mappings":"AAEA,wKAA4D;AAC5D,+BAAoD;AACpD,2GAAsD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/performance.js b/nodejs/node_modules/lib0/performance.js new file mode 100644 index 00000000..ed151c65 --- /dev/null +++ b/nodejs/node_modules/lib0/performance.js @@ -0,0 +1,5 @@ +/* eslint-env browser */ + +export const measure = performance.measure.bind(performance) +export const now = performance.now.bind(performance) +export const mark = performance.mark.bind(performance) diff --git a/nodejs/node_modules/lib0/performance.node.d.ts b/nodejs/node_modules/lib0/performance.node.d.ts new file mode 100644 index 00000000..261fa7c2 --- /dev/null +++ b/nodejs/node_modules/lib0/performance.node.d.ts @@ -0,0 +1,15 @@ +/// +/** + * @type {typeof performance.measure} + */ +export const measure: typeof performance.measure; +/** + * @type {typeof performance.now} + */ +export const now: typeof performance.now; +/** + * @type {typeof performance.mark} + */ +export const mark: typeof performance.mark; +import { performance } from 'node:perf_hooks'; +//# sourceMappingURL=performance.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/performance.node.d.ts.map b/nodejs/node_modules/lib0/performance.node.d.ts.map new file mode 100644 index 00000000..b2acd5d4 --- /dev/null +++ b/nodejs/node_modules/lib0/performance.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"performance.node.d.ts","sourceRoot":"","sources":["performance.node.js"],"names":[],"mappings":";AAIA;;GAEG;AAEH,sBAHU,OAAO,mBAAmB,CAGyE;AAE7G;;GAEG;AAEH,kBAHU,OAAO,eAAe,CAGyD;AAEzF;;GAEG;AAEH,mBAHU,OAAO,gBAAgB,CAGmE;4BApBxE,iBAAiB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/performance.node.js b/nodejs/node_modules/lib0/performance.node.js new file mode 100644 index 00000000..72d08e8c --- /dev/null +++ b/nodejs/node_modules/lib0/performance.node.js @@ -0,0 +1,21 @@ +import { performance } from 'node:perf_hooks' +import { nop } from './function.js' +import * as time from './time.js' + +/** + * @type {typeof performance.measure} + */ +/* c8 ignore next */ +export const measure = performance.measure ? performance.measure.bind(performance) : /** @type {any} */ (nop) + +/** + * @type {typeof performance.now} + */ +/* c8 ignore next */ +export const now = performance.now ? performance.now.bind(performance) : time.getUnixTime + +/** + * @type {typeof performance.mark} + */ +/* c8 ignore next */ +export const mark = performance.mark ? performance.mark.bind(performance) : /** @type {any} */ (nop) diff --git a/nodejs/node_modules/lib0/prng.d.ts b/nodejs/node_modules/lib0/prng.d.ts new file mode 100644 index 00000000..af72c2ed --- /dev/null +++ b/nodejs/node_modules/lib0/prng.d.ts @@ -0,0 +1,44 @@ +/** + * Description of the function + * @callback generatorNext + * @return {number} A random float in the cange of [0,1) + */ +/** + * A random type generator. + * + * @typedef {Object} PRNG + * @property {generatorNext} next Generate new number + */ +export const DefaultPRNG: typeof Xoroshiro128plus; +export function create(seed: number): PRNG; +export function bool(gen: PRNG): boolean; +export function int53(gen: PRNG, min: number, max: number): number; +export function uint53(gen: PRNG, min: number, max: number): number; +export function int32(gen: PRNG, min: number, max: number): number; +export function uint32(gen: PRNG, min: number, max: number): number; +export function int31(gen: PRNG, min: number, max: number): number; +export function real53(gen: PRNG): number; +export function char(gen: PRNG): string; +export function letter(gen: PRNG): string; +export function word(gen: PRNG, minLen?: number | undefined, maxLen?: number | undefined): string; +export function utf16Rune(gen: PRNG): string; +export function utf16String(gen: PRNG, maxlen?: number | undefined): string; +export function oneOf(gen: PRNG, array: T[]): T; +export function uint8Array(gen: PRNG, len: number): Uint8Array; +export function uint16Array(gen: PRNG, len: number): Uint16Array; +export function uint32Array(gen: PRNG, len: number): Uint32Array; +/** + * Description of the function + */ +export type generatorNext = () => number; +/** + * A random type generator. + */ +export type PRNG = { + /** + * Generate new number + */ + next: generatorNext; +}; +import { Xoroshiro128plus } from './prng/Xoroshiro128plus.js'; +//# sourceMappingURL=prng.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng.d.ts.map b/nodejs/node_modules/lib0/prng.d.ts.map new file mode 100644 index 00000000..0abbc2fd --- /dev/null +++ b/nodejs/node_modules/lib0/prng.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prng.d.ts","sourceRoot":"","sources":["prng.js"],"names":[],"mappings":"AAeA;;;;GAIG;AAEH;;;;;GAKG;AACH,kDAA2C;AAUpC,6BAHI,MAAM,GACL,IAAI,CAEmC;AAQ5C,0BAHI,IAAI,WAG+B;AAUvC,2BALI,IAAI,oCAKuE;AAU/E,4BALI,IAAI,oCAKwD;AAUhE,2BALI,IAAI,oCAKuE;AAU/E,4BALI,IAAI,oCAKoD;AAY5D,2BALI,IAAI,oCAK6C;AAQrD,4BAHI,IAAI,UAGwB;AAUhC,0BALI,IAAI,GACH,MAAM,CAI0C;AAMrD,4BAHI,IAAI,GACH,MAAM,CAE4C;AAQvD,0BALI,IAAI,6DAGH,MAAM,CASjB;AAQM,+BAHI,IAAI,GACH,MAAM,CAKjB;AAMM,iCAHI,IAAI,uCAUd;AAUM,8BALI,IAAI,iBAK4D;AAOpE,gCAJI,IAAI,OACJ,MAAM,GACL,UAAU,CAQrB;AAQM,iCAJI,IAAI,OACJ,MAAM,GACL,WAAW,CAEkE;AAOlF,iCAJI,IAAI,OACJ,MAAM,GACL,WAAW,CAEkE;;;;kCApL5E,MAAM;;;;;;;;UAOL,aAAa;;iCAbM,4BAA4B"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng.js b/nodejs/node_modules/lib0/prng.js new file mode 100644 index 00000000..f8aaa3d7 --- /dev/null +++ b/nodejs/node_modules/lib0/prng.js @@ -0,0 +1,200 @@ +/** + * Fast Pseudo Random Number Generators. + * + * Given a seed a PRNG generates a sequence of numbers that cannot be reasonably predicted. + * Two PRNGs must generate the same random sequence of numbers if given the same seed. + * + * @module prng + */ + +import * as binary from './binary.js' +import { fromCharCode, fromCodePoint } from './string.js' +import * as math from './math.js' +import { Xoroshiro128plus } from './prng/Xoroshiro128plus.js' +import * as buffer from './buffer.js' + +/** + * Description of the function + * @callback generatorNext + * @return {number} A random float in the cange of [0,1) + */ + +/** + * A random type generator. + * + * @typedef {Object} PRNG + * @property {generatorNext} next Generate new number + */ +export const DefaultPRNG = Xoroshiro128plus + +/** + * Create a Xoroshiro128plus Pseudo-Random-Number-Generator. + * This is the fastest full-period generator passing BigCrush without systematic failures. + * But there are more PRNGs available in ./PRNG/. + * + * @param {number} seed A positive 32bit integer. Do not use negative numbers. + * @return {PRNG} + */ +export const create = seed => new DefaultPRNG(seed) + +/** + * Generates a single random bool. + * + * @param {PRNG} gen A random number generator. + * @return {Boolean} A random boolean + */ +export const bool = gen => (gen.next() >= 0.5) + +/** + * Generates a random integer with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +export const int53 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min) + +/** + * Generates a random integer with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +export const uint53 = (gen, min, max) => math.abs(int53(gen, min, max)) + +/** + * Generates a random integer with 32 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +export const int32 = (gen, min, max) => math.floor(gen.next() * (max + 1 - min) + min) + +/** + * Generates a random integer with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). + * @return {Number} A random integer on [min, max] + */ +export const uint32 = (gen, min, max) => int32(gen, min, max) >>> 0 + +/** + * @deprecated + * Optimized version of prng.int32. It has the same precision as prng.int32, but should be preferred when + * openaring on smaller ranges. + * + * @param {PRNG} gen A random number generator. + * @param {Number} min The lower bound of the allowed return values (inclusive). + * @param {Number} max The upper bound of the allowed return values (inclusive). The max inclusive number is `binary.BITS31-1` + * @return {Number} A random integer on [min, max] + */ +export const int31 = (gen, min, max) => int32(gen, min, max) + +/** + * Generates a random real on [0, 1) with 53 bit resolution. + * + * @param {PRNG} gen A random number generator. + * @return {Number} A random real number on [0, 1). + */ +export const real53 = gen => gen.next() // (((gen.next() >>> 5) * binary.BIT26) + (gen.next() >>> 6)) / MAX_SAFE_INTEGER + +/** + * Generates a random character from char code 32 - 126. I.e. Characters, Numbers, special characters, and Space: + * + * @param {PRNG} gen A random number generator. + * @return {string} + * + * (Space)!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~ + */ +export const char = gen => fromCharCode(int31(gen, 32, 126)) + +/** + * @param {PRNG} gen + * @return {string} A single letter (a-z) + */ +export const letter = gen => fromCharCode(int31(gen, 97, 122)) + +/** + * @param {PRNG} gen + * @param {number} [minLen=0] + * @param {number} [maxLen=20] + * @return {string} A random word (0-20 characters) without spaces consisting of letters (a-z) + */ +export const word = (gen, minLen = 0, maxLen = 20) => { + const len = int31(gen, minLen, maxLen) + let str = '' + for (let i = 0; i < len; i++) { + str += letter(gen) + } + return str +} + +/** + * TODO: this function produces invalid runes. Does not cover all of utf16!! + * + * @param {PRNG} gen + * @return {string} + */ +export const utf16Rune = gen => { + const codepoint = int31(gen, 0, 256) + return fromCodePoint(codepoint) +} + +/** + * @param {PRNG} gen + * @param {number} [maxlen = 20] + */ +export const utf16String = (gen, maxlen = 20) => { + const len = int31(gen, 0, maxlen) + let str = '' + for (let i = 0; i < len; i++) { + str += utf16Rune(gen) + } + return str +} + +/** + * Returns one element of a given array. + * + * @param {PRNG} gen A random number generator. + * @param {Array} array Non empty Array of possible values. + * @return {T} One of the values of the supplied Array. + * @template T + */ +export const oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)] + +/** + * @param {PRNG} gen + * @param {number} len + * @return {Uint8Array} + */ +export const uint8Array = (gen, len) => { + const buf = buffer.createUint8ArrayFromLen(len) + for (let i = 0; i < buf.length; i++) { + buf[i] = int32(gen, 0, binary.BITS8) + } + return buf +} + +/* c8 ignore start */ +/** + * @param {PRNG} gen + * @param {number} len + * @return {Uint16Array} + */ +export const uint16Array = (gen, len) => new Uint16Array(uint8Array(gen, len * 2).buffer) + +/** + * @param {PRNG} gen + * @param {number} len + * @return {Uint32Array} + */ +export const uint32Array = (gen, len) => new Uint32Array(uint8Array(gen, len * 4).buffer) +/* c8 ignore stop */ diff --git a/nodejs/node_modules/lib0/prng.test.d.ts b/nodejs/node_modules/lib0/prng.test.d.ts new file mode 100644 index 00000000..dd69f9a7 --- /dev/null +++ b/nodejs/node_modules/lib0/prng.test.d.ts @@ -0,0 +1,6 @@ +export function testGeneratorXoroshiro128plus(tc: t.TestCase): void; +export function testGeneratorXorshift32(tc: t.TestCase): void; +export function testGeneratorMt19937(tc: t.TestCase): void; +export function testNumberDistributions(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=prng.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng.test.d.ts.map b/nodejs/node_modules/lib0/prng.test.d.ts.map new file mode 100644 index 00000000..04809088 --- /dev/null +++ b/nodejs/node_modules/lib0/prng.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prng.test.d.ts","sourceRoot":"","sources":["prng.test.js"],"names":[],"mappings":"AA4LO,kDAFI,EAAE,QAAQ,QAE2E;AAKzF,4CAFI,EAAE,QAAQ,QAKpB;AAKM,yCAFI,EAAE,QAAQ,QAKpB;AA2BM,4CAFI,EAAE,QAAQ,QAOpB;mBAxOkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Mt19937.d.ts b/nodejs/node_modules/lib0/prng/Mt19937.d.ts new file mode 100644 index 00000000..d644fabf --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Mt19937.d.ts @@ -0,0 +1,29 @@ +/** + * This is a port of Shawn Cokus's implementation of the original Mersenne Twister algorithm (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/MTARCOK/mt19937ar-cok.c). + * MT has a very high period of 2^19937. Though the authors of xorshift describe that a high period is not + * very relevant (http://vigna.di.unimi.it/xorshift/). It is four times slower than xoroshiro128plus and + * needs to recompute its state after generating 624 numbers. + * + * ```js + * const gen = new Mt19937(new Date().getTime()) + * console.log(gen.next()) + * ``` + * + * @public + */ +export class Mt19937 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor(seed: number); + seed: number; + _state: Uint32Array; + _i: number; + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next(): number; +} +//# sourceMappingURL=Mt19937.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Mt19937.d.ts.map b/nodejs/node_modules/lib0/prng/Mt19937.d.ts.map new file mode 100644 index 00000000..b8c8d478 --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Mt19937.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Mt19937.d.ts","sourceRoot":"","sources":["Mt19937.js"],"names":[],"mappings":"AA8BA;;;;;;;;;;;;GAYG;AACH;IACE;;OAEG;IACH,kBAFW,MAAM,EAYhB;IATC,aAAgB;IAMhB,oBAAmB;IACnB,WAAW;IAIb;;;;OAIG;IACH,eAYC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Mt19937.js b/nodejs/node_modules/lib0/prng/Mt19937.js new file mode 100644 index 00000000..a0d5643e --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Mt19937.js @@ -0,0 +1,78 @@ +import * as binary from '../binary.js' +import * as math from '../math.js' + +/** + * @module prng + */ +const N = 624 +const M = 397 + +/** + * @param {number} u + * @param {number} v + */ +const twist = (u, v) => ((((u & 0x80000000) | (v & 0x7fffffff)) >>> 1) ^ ((v & 1) ? 0x9908b0df : 0)) + +/** + * @param {Uint32Array} state + */ +const nextState = state => { + let p = 0 + let j + for (j = N - M + 1; --j; p++) { + state[p] = state[p + M] ^ twist(state[p], state[p + 1]) + } + for (j = M; --j; p++) { + state[p] = state[p + M - N] ^ twist(state[p], state[p + 1]) + } + state[p] = state[p + M - N] ^ twist(state[p], state[0]) +} + +/** + * This is a port of Shawn Cokus's implementation of the original Mersenne Twister algorithm (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/MTARCOK/mt19937ar-cok.c). + * MT has a very high period of 2^19937. Though the authors of xorshift describe that a high period is not + * very relevant (http://vigna.di.unimi.it/xorshift/). It is four times slower than xoroshiro128plus and + * needs to recompute its state after generating 624 numbers. + * + * ```js + * const gen = new Mt19937(new Date().getTime()) + * console.log(gen.next()) + * ``` + * + * @public + */ +export class Mt19937 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed + const state = new Uint32Array(N) + state[0] = seed + for (let i = 1; i < N; i++) { + state[i] = (math.imul(1812433253, (state[i - 1] ^ (state[i - 1] >>> 30))) + i) & binary.BITS32 + } + this._state = state + this._i = 0 + nextState(this._state) + } + + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next () { + if (this._i === N) { + // need to compute a new state + nextState(this._state) + this._i = 0 + } + let y = this._state[this._i++] + y ^= (y >>> 11) + y ^= (y << 7) & 0x9d2c5680 + y ^= (y << 15) & 0xefc60000 + y ^= (y >>> 18) + return (y >>> 0) / (binary.BITS32 + 1) + } +} diff --git a/nodejs/node_modules/lib0/prng/Xoroshiro128plus.d.ts b/nodejs/node_modules/lib0/prng/Xoroshiro128plus.d.ts new file mode 100644 index 00000000..1975394f --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Xoroshiro128plus.d.ts @@ -0,0 +1,27 @@ +/** + * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures. + * + * This implementation follows the idea of the original xoroshiro128plus implementation, + * but is optimized for the JavaScript runtime. I.e. + * * The operations are performed on 32bit integers (the original implementation works with 64bit values). + * * The initial 128bit state is computed based on a 32bit seed and Xorshift32. + * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus. + * Caution: The last addition step works slightly different than in the original implementation - the add carry of the + * first 32bit addition is not carried over to the last 32bit. + * + * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c) + */ +export class Xoroshiro128plus { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor(seed: number); + seed: number; + state: Uint32Array; + _fresh: boolean; + /** + * @return {number} Float/Double in [0,1) + */ + next(): number; +} +//# sourceMappingURL=Xoroshiro128plus.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Xoroshiro128plus.d.ts.map b/nodejs/node_modules/lib0/prng/Xoroshiro128plus.d.ts.map new file mode 100644 index 00000000..fbda7164 --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Xoroshiro128plus.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Xoroshiro128plus.d.ts","sourceRoot":"","sources":["Xoroshiro128plus.js"],"names":[],"mappings":"AAOA;;;;;;;;;;;;GAYG;AACH;IACE;;OAEG;IACH,kBAFW,MAAM,EAWhB;IARC,aAAgB;IAGhB,mBAA+B;IAI/B,gBAAkB;IAGpB;;OAEG;IACH,QAFY,MAAM,CA4BjB;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Xoroshiro128plus.js b/nodejs/node_modules/lib0/prng/Xoroshiro128plus.js new file mode 100644 index 00000000..ba9b84a8 --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Xoroshiro128plus.js @@ -0,0 +1,111 @@ +/** + * @module prng + */ + +import { Xorshift32 } from './Xorshift32.js' +import * as binary from '../binary.js' + +/** + * This is a variant of xoroshiro128plus - the fastest full-period generator passing BigCrush without systematic failures. + * + * This implementation follows the idea of the original xoroshiro128plus implementation, + * but is optimized for the JavaScript runtime. I.e. + * * The operations are performed on 32bit integers (the original implementation works with 64bit values). + * * The initial 128bit state is computed based on a 32bit seed and Xorshift32. + * * This implementation returns two 32bit values based on the 64bit value that is computed by xoroshiro128plus. + * Caution: The last addition step works slightly different than in the original implementation - the add carry of the + * first 32bit addition is not carried over to the last 32bit. + * + * [Reference implementation](http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c) + */ +export class Xoroshiro128plus { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed + // This is a variant of Xoroshiro128plus to fill the initial state + const xorshift32 = new Xorshift32(seed) + this.state = new Uint32Array(4) + for (let i = 0; i < 4; i++) { + this.state[i] = xorshift32.next() * binary.BITS32 + } + this._fresh = true + } + + /** + * @return {number} Float/Double in [0,1) + */ + next () { + const state = this.state + if (this._fresh) { + this._fresh = false + return ((state[0] + state[2]) >>> 0) / (binary.BITS32 + 1) + } else { + this._fresh = true + const s0 = state[0] + const s1 = state[1] + const s2 = state[2] ^ s0 + const s3 = state[3] ^ s1 + // function js_rotl (x, k) { + // k = k - 32 + // const x1 = x[0] + // const x2 = x[1] + // x[0] = x2 << k | x1 >>> (32 - k) + // x[1] = x1 << k | x2 >>> (32 - k) + // } + // rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23 + state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18) + state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14) + // rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9 + state[2] = s3 << 4 | s2 >>> 28 + state[3] = s2 << 4 | s3 >>> 28 + return (((state[1] + state[3]) >>> 0) / (binary.BITS32 + 1)) + } + } +} + +/* +// Reference implementation +// Source: http://vigna.di.unimi.it/xorshift/xoroshiro128plus.c +// By David Blackman and Sebastiano Vigna +// Who published the reference implementation under Public Domain (CC0) + +#include +#include + +uint64_t s[2]; + +static inline uint64_t rotl(const uint64_t x, int k) { + return (x << k) | (x >> (64 - k)); +} + +uint64_t next(void) { + const uint64_t s0 = s[0]; + uint64_t s1 = s[1]; + s1 ^= s0; + s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b + s[1] = rotl(s1, 36); // c + return (s[0] + s[1]) & 0xFFFFFFFF; +} + +int main(void) +{ + int i; + s[0] = 1111 | (1337ul << 32); + s[1] = 1234 | (9999ul << 32); + + printf("1000 outputs of genrand_int31()\n"); + for (i=0; i<100; i++) { + printf("%10lu ", i); + printf("%10lu ", next()); + printf("- %10lu ", s[0] >> 32); + printf("%10lu ", (s[0] << 32) >> 32); + printf("%10lu ", s[1] >> 32); + printf("%10lu ", (s[1] << 32) >> 32); + printf("\n"); + // if (i%5==4) printf("\n"); + } + return 0; +} +*/ diff --git a/nodejs/node_modules/lib0/prng/Xorshift32.d.ts b/nodejs/node_modules/lib0/prng/Xorshift32.d.ts new file mode 100644 index 00000000..436b8bcf --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Xorshift32.d.ts @@ -0,0 +1,21 @@ +/** + * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`. + */ +export class Xorshift32 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor(seed: number); + seed: number; + /** + * @type {number} + */ + _state: number; + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next(): number; +} +//# sourceMappingURL=Xorshift32.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Xorshift32.d.ts.map b/nodejs/node_modules/lib0/prng/Xorshift32.d.ts.map new file mode 100644 index 00000000..281c0280 --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Xorshift32.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"Xorshift32.d.ts","sourceRoot":"","sources":["Xorshift32.js"],"names":[],"mappings":"AAMA;;GAEG;AACH;IACE;;OAEG;IACH,kBAFW,MAAM,EAQhB;IALC,aAAgB;IAChB;;OAEG;IACH,QAFU,MAAM,CAEE;IAGpB;;;;OAIG;IACH,eAOC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/prng/Xorshift32.js b/nodejs/node_modules/lib0/prng/Xorshift32.js new file mode 100644 index 00000000..91535049 --- /dev/null +++ b/nodejs/node_modules/lib0/prng/Xorshift32.js @@ -0,0 +1,35 @@ +/** + * @module prng + */ + +import * as binary from '../binary.js' + +/** + * Xorshift32 is a very simple but elegang PRNG with a period of `2^32-1`. + */ +export class Xorshift32 { + /** + * @param {number} seed Unsigned 32 bit number + */ + constructor (seed) { + this.seed = seed + /** + * @type {number} + */ + this._state = seed + } + + /** + * Generate a random signed integer. + * + * @return {Number} A 32 bit signed integer. + */ + next () { + let x = this._state + x ^= x << 13 + x ^= x >> 17 + x ^= x << 5 + this._state = x + return (x >>> 0) / (binary.BITS32 + 1) + } +} diff --git a/nodejs/node_modules/lib0/promise.d.ts b/nodejs/node_modules/lib0/promise.d.ts new file mode 100644 index 00000000..0109982b --- /dev/null +++ b/nodejs/node_modules/lib0/promise.d.ts @@ -0,0 +1,21 @@ +export function create(f: (arg0: PromiseResolve, arg1: (arg0: Error) => void) => any): Promise; +export function createEmpty(f: (arg0: () => void, arg1: (arg0: Error) => void) => void): Promise; +/** + * `Promise.all` wait for all promises in the array to resolve and return the result + * @template {unknown[] | []} PS + * + * @param {PS} ps + * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>} + */ +export const all: { + (values: Iterable>): Promise[]>; + (values: T_1): Promise<{ -readonly [P in keyof T_1]: Awaited; }>; +}; +export function reject(reason?: Error | undefined): Promise; +export function resolve(res: void | T): Promise; +export function resolveWith(res: T): Promise; +export function until(timeout: number, check: () => boolean, intervalResolution?: number | undefined): Promise; +export function wait(timeout: number): Promise; +export function isPromise(p: any): boolean; +export type PromiseResolve = (result?: T | PromiseLike | undefined) => any; +//# sourceMappingURL=promise.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/promise.d.ts.map b/nodejs/node_modules/lib0/promise.d.ts.map new file mode 100644 index 00000000..2907d422 --- /dev/null +++ b/nodejs/node_modules/lib0/promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.d.ts","sourceRoot":"","sources":["promise.js"],"names":[],"mappings":"AAmBO,oEAHwC,KAAK,KAAE,IAAI,KAAE,GAAG,cAGM;AAM9D,4CAHwB,IAAI,eAAU,KAAK,KAAE,IAAI,KAAE,IAAI,GAClD,QAAQ,IAAI,CAAC,CAEqB;AAE9C;;;;;;GAMG;AACH;;;EAA4C;AAMrC,oDAFK,QAAQ,KAAK,CAAC,CAE4B;AAO/C,6DAA2C;AAO3C,mDAA+C;AAU/C,+BALI,MAAM,eACK,OAAO,4CAEjB,QAAQ,IAAI,CAAC,CAkBvB;AAMK,8BAHI,MAAM,GACL,QAAQ,SAAS,CAAC,CAE0D;AAWjF,6BAHI,GAAG,GACF,OAAO,CAEwE"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/promise.js b/nodejs/node_modules/lib0/promise.js new file mode 100644 index 00000000..8254fc82 --- /dev/null +++ b/nodejs/node_modules/lib0/promise.js @@ -0,0 +1,98 @@ +/** + * Utility helpers to work with promises. + * + * @module promise + */ + +import * as time from './time.js' + +/** + * @template T + * @callback PromiseResolve + * @param {T|PromiseLike} [result] + */ + +/** + * @template T + * @param {function(PromiseResolve,function(Error):void):any} f + * @return {Promise} + */ +export const create = f => /** @type {Promise} */ (new Promise(f)) + +/** + * @param {function(function():void,function(Error):void):void} f + * @return {Promise} + */ +export const createEmpty = f => new Promise(f) + +/** + * `Promise.all` wait for all promises in the array to resolve and return the result + * @template {unknown[] | []} PS + * + * @param {PS} ps + * @return {Promise<{ -readonly [P in keyof PS]: Awaited }>} + */ +export const all = Promise.all.bind(Promise) + +/** + * @param {Error} [reason] + * @return {Promise} + */ +export const reject = reason => Promise.reject(reason) + +/** + * @template T + * @param {T|void} res + * @return {Promise} + */ +export const resolve = res => Promise.resolve(res) + +/** + * @template T + * @param {T} res + * @return {Promise} + */ +export const resolveWith = res => Promise.resolve(res) + +/** + * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]] + * + * @param {number} timeout + * @param {function():boolean} check + * @param {number} [intervalResolution] + * @return {Promise} + */ +export const until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => { + const startTime = time.getUnixTime() + const hasTimeout = timeout > 0 + const untilInterval = () => { + if (check()) { + clearInterval(intervalHandle) + resolve() + } else if (hasTimeout) { + /* c8 ignore else */ + if (time.getUnixTime() - startTime > timeout) { + clearInterval(intervalHandle) + reject(new Error('Timeout')) + } + } + } + const intervalHandle = setInterval(untilInterval, intervalResolution) +}) + +/** + * @param {number} timeout + * @return {Promise} + */ +export const wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout)) + +/** + * Checks if an object is a promise using ducktyping. + * + * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this + * library has some insane environment where global Promise objects are overwritten. + * + * @param {any} p + * @return {boolean} + */ +export const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally) diff --git a/nodejs/node_modules/lib0/promise.test.d.ts b/nodejs/node_modules/lib0/promise.test.d.ts new file mode 100644 index 00000000..aa230e1b --- /dev/null +++ b/nodejs/node_modules/lib0/promise.test.d.ts @@ -0,0 +1,5 @@ +export function testRepeatPromise(_tc: t.TestCase): Promise; +export function testispromise(_tc: t.TestCase): void; +export function testTypings(_tc: t.TestCase): Promise; +import * as t from './testing.js'; +//# sourceMappingURL=promise.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/promise.test.d.ts.map b/nodejs/node_modules/lib0/promise.test.d.ts.map new file mode 100644 index 00000000..547b3138 --- /dev/null +++ b/nodejs/node_modules/lib0/promise.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.test.d.ts","sourceRoot":"","sources":["promise.test.js"],"names":[],"mappings":"AA6BO,uCAFI,EAAE,QAAQ,iBAgBpB;AAKM,mCAFI,EAAE,QAAQ,QAapB;AAKM,iCAFI,EAAE,QAAQ,iBAapB;mBA1EkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/queue.d.ts b/nodejs/node_modules/lib0/queue.d.ts new file mode 100644 index 00000000..4ed95974 --- /dev/null +++ b/nodejs/node_modules/lib0/queue.d.ts @@ -0,0 +1,34 @@ +export class QueueNode { + /** + * @type {QueueNode|null} + */ + next: QueueNode | null; +} +/** + * @template V + */ +export class QueueValue extends QueueNode { + /** + * @param {V} v + */ + constructor(v: V); + v: V; +} +/** + * @template {QueueNode} N + */ +export class Queue { + /** + * @type {N | null} + */ + start: N | null; + /** + * @type {N | null} + */ + end: N | null; +} +export function create(): Queue; +export function isEmpty(queue: Queue): boolean; +export function enqueue>(queue: Q, n: Q extends Queue ? N : never): void; +export function dequeue(queue: Queue): N | null; +//# sourceMappingURL=queue.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/queue.d.ts.map b/nodejs/node_modules/lib0/queue.d.ts.map new file mode 100644 index 00000000..967ff8c7 --- /dev/null +++ b/nodejs/node_modules/lib0/queue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.d.ts","sourceRoot":"","sources":["queue.js"],"names":[],"mappings":"AAAA;IAEI;;OAEG;IACH,MAFU,SAAS,GAAC,IAAI,CAER;CAEnB;AAED;;GAEG;AACH;IACE;;OAEG;IACH,eAFW,CAAC,EAKX;IADC,KAAU;CAEb;AAED;;GAEG;AACH;IAEI;;OAEG;IACH,OAFU,CAAC,GAAG,IAAI,CAED;IACjB;;OAEG;IACH,KAFU,CAAC,GAAG,IAAI,CAEH;CAElB;AASM,wDAAgC;AAKhC,+BAFI,MAAM,GAAG,CAAC,WAE+B;AAO7C,yHAQN;AAOM,wEAWN"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/queue.js b/nodejs/node_modules/lib0/queue.js new file mode 100644 index 00000000..5be7fd43 --- /dev/null +++ b/nodejs/node_modules/lib0/queue.js @@ -0,0 +1,84 @@ +export class QueueNode { + constructor () { + /** + * @type {QueueNode|null} + */ + this.next = null + } +} + +/** + * @template V + */ +export class QueueValue extends QueueNode { + /** + * @param {V} v + */ + constructor (v) { + super() + this.v = v + } +} + +/** + * @template {QueueNode} N + */ +export class Queue { + constructor () { + /** + * @type {N | null} + */ + this.start = null + /** + * @type {N | null} + */ + this.end = null + } +} + +/** + * @note The queue implementation is experimental and unfinished. + * Don't use this in production yet. + * + * @template {QueueNode} N + * @return {Queue} + */ +export const create = () => new Queue() + +/** + * @param {Queue} queue + */ +export const isEmpty = queue => queue.start === null + +/** + * @template {Queue} Q + * @param {Q} queue + * @param {Q extends Queue ? N : never} n + */ +export const enqueue = (queue, n) => { + if (queue.end !== null) { + queue.end.next = n + queue.end = n + } else { + queue.end = n + queue.start = n + } +} + +/** + * @template {QueueNode} N + * @param {Queue} queue + * @return {N | null} + */ +export const dequeue = queue => { + const n = queue.start + if (n !== null) { + // @ts-ignore + queue.start = n.next + if (queue.start === null) { + queue.end = null + } + return n + } + return null +} diff --git a/nodejs/node_modules/lib0/queue.test.d.ts b/nodejs/node_modules/lib0/queue.test.d.ts new file mode 100644 index 00000000..7caa54d9 --- /dev/null +++ b/nodejs/node_modules/lib0/queue.test.d.ts @@ -0,0 +1,3 @@ +export function testEnqueueDequeue(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=queue.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/queue.test.d.ts.map b/nodejs/node_modules/lib0/queue.test.d.ts.map new file mode 100644 index 00000000..1f1f3fbd --- /dev/null +++ b/nodejs/node_modules/lib0/queue.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"queue.test.d.ts","sourceRoot":"","sources":["queue.test.js"],"names":[],"mappings":"AAMO,wCAFI,EAAE,QAAQ,QA8BpB;mBAlCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/random.d.ts b/nodejs/node_modules/lib0/random.d.ts new file mode 100644 index 00000000..3fe9ebfb --- /dev/null +++ b/nodejs/node_modules/lib0/random.d.ts @@ -0,0 +1,6 @@ +export const rand: () => number; +export function uint32(): number; +export function uint53(): number; +export function oneOf(arr: T[]): T; +export function uuidv4(): string; +//# sourceMappingURL=random.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/random.d.ts.map b/nodejs/node_modules/lib0/random.d.ts.map new file mode 100644 index 00000000..ab6a778b --- /dev/null +++ b/nodejs/node_modules/lib0/random.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.d.ts","sourceRoot":"","sources":["random.js"],"names":[],"mappings":"AAYA,gCAA+B;AAExB,iCAA2D;AAE3D,iCAGN;AAOM,sCAAyD;AAQzD,0BAFK,MAAM,CAIjB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/random.js b/nodejs/node_modules/lib0/random.js new file mode 100644 index 00000000..741e5f1c --- /dev/null +++ b/nodejs/node_modules/lib0/random.js @@ -0,0 +1,37 @@ +/** + * Isomorphic module for true random numbers / buffers / uuids. + * + * Attention: falls back to Math.random if the browser does not support crypto. + * + * @module random + */ + +import * as math from './math.js' +import * as binary from './binary.js' +import { getRandomValues } from 'lib0/webcrypto' + +export const rand = Math.random + +export const uint32 = () => getRandomValues(new Uint32Array(1))[0] + +export const uint53 = () => { + const arr = getRandomValues(new Uint32Array(8)) + return (arr[0] & binary.BITS21) * (binary.BITS32 + 1) + (arr[1] >>> 0) +} + +/** + * @template T + * @param {Array} arr + * @return {T} + */ +export const oneOf = arr => arr[math.floor(rand() * arr.length)] + +// @ts-ignore +const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11 + +/** + * @return {string} + */ +export const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c => + (c ^ uint32() & 15 >> c / 4).toString(16) +) diff --git a/nodejs/node_modules/lib0/random.test.d.ts b/nodejs/node_modules/lib0/random.test.d.ts new file mode 100644 index 00000000..d3b2523c --- /dev/null +++ b/nodejs/node_modules/lib0/random.test.d.ts @@ -0,0 +1,7 @@ +export function testRandom(tc: t.TestCase): void; +export function testUint32(tc: t.TestCase): void; +export function testUint53(tc: t.TestCase): void; +export function testUuidv4(tc: t.TestCase): void; +export function testUuidv4Overlaps(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=random.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/random.test.d.ts.map b/nodejs/node_modules/lib0/random.test.d.ts.map new file mode 100644 index 00000000..2cdf8084 --- /dev/null +++ b/nodejs/node_modules/lib0/random.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.test.d.ts","sourceRoot":"","sources":["random.test.js"],"names":[],"mappings":"AASO,+BAFI,EAAE,QAAQ,QAKpB;AAKM,+BAFI,EAAE,QAAQ,QA0BpB;AAKM,+BAFI,EAAE,QAAQ,QAyBpB;AAKM,+BAFI,EAAE,QAAQ,QAIpB;AAKM,uCAFI,EAAE,QAAQ,QAkBpB;mBAhGkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/rollup.config.d.ts b/nodejs/node_modules/lib0/rollup.config.d.ts new file mode 100644 index 00000000..7192ab2c --- /dev/null +++ b/nodejs/node_modules/lib0/rollup.config.d.ts @@ -0,0 +1,13 @@ +declare const _default: { + input: string[]; + output: { + dir: string; + format: string; + sourcemap: boolean; + entryFileNames: string; + chunkFileNames: string; + }; + external: string[]; +}[]; +export default _default; +//# sourceMappingURL=rollup.config.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/rollup.config.d.ts.map b/nodejs/node_modules/lib0/rollup.config.d.ts.map new file mode 100644 index 00000000..26da1df5 --- /dev/null +++ b/nodejs/node_modules/lib0/rollup.config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rollup.config.d.ts","sourceRoot":"","sources":["rollup.config.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/set.d.ts b/nodejs/node_modules/lib0/set.d.ts new file mode 100644 index 00000000..b2c1a6bd --- /dev/null +++ b/nodejs/node_modules/lib0/set.d.ts @@ -0,0 +1,5 @@ +export function create(): Set; +export function toArray(set: Set): T[]; +export function first(set: Set): T; +export function from(entries: Iterable): Set; +//# sourceMappingURL=set.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/set.d.ts.map b/nodejs/node_modules/lib0/set.d.ts.map new file mode 100644 index 00000000..a023cc08 --- /dev/null +++ b/nodejs/node_modules/lib0/set.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.d.ts","sourceRoot":"","sources":["set.js"],"names":[],"mappings":"AAMO,mCAA8B;AAO9B,6CAAsC;AAOtC,yCACiC;AAOjC,sDAAwC"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/set.js b/nodejs/node_modules/lib0/set.js new file mode 100644 index 00000000..4f1d5e36 --- /dev/null +++ b/nodejs/node_modules/lib0/set.js @@ -0,0 +1,29 @@ +/** + * Utility module to work with sets. + * + * @module set + */ + +export const create = () => new Set() + +/** + * @template T + * @param {Set} set + * @return {Array} + */ +export const toArray = set => Array.from(set) + +/** + * @template T + * @param {Set} set + * @return {T} + */ +export const first = set => + set.values().next().value || undefined + +/** + * @template T + * @param {Iterable} entries + * @return {Set} + */ +export const from = entries => new Set(entries) diff --git a/nodejs/node_modules/lib0/set.test.d.ts b/nodejs/node_modules/lib0/set.test.d.ts new file mode 100644 index 00000000..075f0d1e --- /dev/null +++ b/nodejs/node_modules/lib0/set.test.d.ts @@ -0,0 +1,3 @@ +export function testFirst(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=set.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/set.test.d.ts.map b/nodejs/node_modules/lib0/set.test.d.ts.map new file mode 100644 index 00000000..30d32fdc --- /dev/null +++ b/nodejs/node_modules/lib0/set.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.test.d.ts","sourceRoot":"","sources":["set.test.js"],"names":[],"mappings":"AAMO,+BAFI,EAAE,QAAQ,QAUpB;mBAdkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/sort.d.ts b/nodejs/node_modules/lib0/sort.d.ts new file mode 100644 index 00000000..f80cece4 --- /dev/null +++ b/nodejs/node_modules/lib0/sort.d.ts @@ -0,0 +1,4 @@ +export function _insertionSort(arr: T[], lo: number, hi: number, compare: (arg0: T, arg1: T) => number): void; +export function insertionSort(arr: T[], compare: (arg0: T, arg1: T) => number): void; +export function quicksort(arr: T[], compare: (arg0: T, arg1: T) => number): void; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/sort.d.ts.map b/nodejs/node_modules/lib0/sort.d.ts.map new file mode 100644 index 00000000..f700373f --- /dev/null +++ b/nodejs/node_modules/lib0/sort.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["sort.js"],"names":[],"mappings":"AAkBO,gDAJI,MAAM,MACN,MAAM,iCACQ,MAAM,QAU9B;AAQM,0EAHkB,MAAM,GACnB,IAAI,CAIf;AAiDM,sEAHkB,MAAM,GACnB,IAAI,CAIf"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/sort.js b/nodejs/node_modules/lib0/sort.js new file mode 100644 index 00000000..149e3186 --- /dev/null +++ b/nodejs/node_modules/lib0/sort.js @@ -0,0 +1,88 @@ +/** + * Efficient sort implementations. + * + * Note: These sort implementations were created to compare different sorting algorithms in JavaScript. + * Don't use them if you don't know what you are doing. Native Array.sort is almost always a better choice. + * + * @module sort + */ + +import * as math from './math.js' + +/** + * @template T + * @param {Array} arr + * @param {number} lo + * @param {number} hi + * @param {function(T,T):number} compare + */ +export const _insertionSort = (arr, lo, hi, compare) => { + for (let i = lo + 1; i <= hi; i++) { + for (let j = i; j > 0 && compare(arr[j - 1], arr[j]) > 0; j--) { + const tmp = arr[j] + arr[j] = arr[j - 1] + arr[j - 1] = tmp + } + } +} + +/** + * @template T + * @param {Array} arr + * @param {function(T,T):number} compare + * @return {void} + */ +export const insertionSort = (arr, compare) => { + _insertionSort(arr, 0, arr.length - 1, compare) +} + +/** + * @template T + * @param {Array} arr + * @param {number} lo + * @param {number} hi + * @param {function(T,T):number} compare + */ +const _quickSort = (arr, lo, hi, compare) => { + if (hi - lo < 42) { + _insertionSort(arr, lo, hi, compare) + } else { + const pivot = arr[math.floor((lo + hi) / 2)] + let i = lo + let j = hi + while (true) { + while (compare(pivot, arr[i]) > 0) { + i++ + } + while (compare(arr[j], pivot) > 0) { + j-- + } + if (i >= j) { + break + } + // swap arr[i] with arr[j] + // and increment i and j + const arri = arr[i] + arr[i++] = arr[j] + arr[j--] = arri + } + _quickSort(arr, lo, j, compare) + _quickSort(arr, j + 1, hi, compare) + } +} + +/** + * This algorithm beats Array.prototype.sort in Chrome only with arrays with 10 million entries. + * In most cases [].sort will do just fine. Make sure to performance test your use-case before you + * integrate this algorithm. + * + * Note that Chrome's sort is now a stable algorithm (Timsort). Quicksort is not stable. + * + * @template T + * @param {Array} arr + * @param {function(T,T):number} compare + * @return {void} + */ +export const quicksort = (arr, compare) => { + _quickSort(arr, 0, arr.length - 1, compare) +} diff --git a/nodejs/node_modules/lib0/sort.test.d.ts b/nodejs/node_modules/lib0/sort.test.d.ts new file mode 100644 index 00000000..11344b1d --- /dev/null +++ b/nodejs/node_modules/lib0/sort.test.d.ts @@ -0,0 +1,7 @@ +export function testSortUint8(tc: t.TestCase): void; +export function testSortUint32(tc: t.TestCase): void; +export function testSortUint16(tc: t.TestCase): void; +export function testSortObjectUint32(tc: t.TestCase): void; +export function testListVsArrayPerformance(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=sort.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/sort.test.d.ts.map b/nodejs/node_modules/lib0/sort.test.d.ts.map new file mode 100644 index 00000000..a4cd1bcd --- /dev/null +++ b/nodejs/node_modules/lib0/sort.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.test.d.ts","sourceRoot":"","sources":["sort.test.js"],"names":[],"mappings":"AAoEO,kCAFI,EAAE,QAAQ,QAqBpB;AAKM,mCAFI,EAAE,QAAQ,QAqBpB;AAKM,mCAFI,EAAE,QAAQ,QAqBpB;AAKM,yCAFI,EAAE,QAAQ,QAoBpB;AAKM,+CAFI,EAAE,QAAQ,QA4BpB;mBA5LkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/statistics.d.ts b/nodejs/node_modules/lib0/statistics.d.ts new file mode 100644 index 00000000..3033ab67 --- /dev/null +++ b/nodejs/node_modules/lib0/statistics.d.ts @@ -0,0 +1,3 @@ +export function median(arr: Array): number; +export function average(arr: Array): number; +//# sourceMappingURL=statistics.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/statistics.d.ts.map b/nodejs/node_modules/lib0/statistics.d.ts.map new file mode 100644 index 00000000..b64b1df2 --- /dev/null +++ b/nodejs/node_modules/lib0/statistics.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"statistics.d.ts","sourceRoot":"","sources":["statistics.js"],"names":[],"mappings":"AAYO,4BAHI,MAAM,MAAM,CAAC,GACZ,MAAM,CAE2K;AAMtL,6BAHI,MAAM,MAAM,CAAC,GACZ,MAAM,CAEgD"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/statistics.js b/nodejs/node_modules/lib0/statistics.js new file mode 100644 index 00000000..64814acb --- /dev/null +++ b/nodejs/node_modules/lib0/statistics.js @@ -0,0 +1,19 @@ +/** + * Utility helpers for generating statistics. + * + * @module statistics + */ + +import * as math from './math.js' + +/** + * @param {Array} arr Array of values + * @return {number} Returns null if the array is empty + */ +export const median = arr => arr.length === 0 ? NaN : (arr.length % 2 === 1 ? arr[(arr.length - 1) / 2] : (arr[math.floor((arr.length - 1) / 2)] + arr[math.ceil((arr.length - 1) / 2)]) / 2) + +/** + * @param {Array} arr + * @return {number} + */ +export const average = arr => arr.reduce(math.add, 0) / arr.length diff --git a/nodejs/node_modules/lib0/statistics.test.d.ts b/nodejs/node_modules/lib0/statistics.test.d.ts new file mode 100644 index 00000000..22230d67 --- /dev/null +++ b/nodejs/node_modules/lib0/statistics.test.d.ts @@ -0,0 +1,3 @@ +export function testMedian(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=statistics.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/statistics.test.d.ts.map b/nodejs/node_modules/lib0/statistics.test.d.ts.map new file mode 100644 index 00000000..d2a4bfb5 --- /dev/null +++ b/nodejs/node_modules/lib0/statistics.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"statistics.test.d.ts","sourceRoot":"","sources":["statistics.test.js"],"names":[],"mappings":"AAOO,+BAFI,EAAE,QAAQ,QASpB;mBAbkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/storage.d.ts b/nodejs/node_modules/lib0/storage.d.ts new file mode 100644 index 00000000..6c69f2e2 --- /dev/null +++ b/nodejs/node_modules/lib0/storage.d.ts @@ -0,0 +1,15 @@ +/** + * This is basically localStorage in browser, or a polyfill in nodejs + */ +export const varStorage: any; +export function onChange(eventHandler: (arg0: { + key: string; + newValue: string; + oldValue: string; +}) => void): true | void; +export function offChange(eventHandler: (arg0: { + key: string; + newValue: string; + oldValue: string; +}) => void): true | void; +//# sourceMappingURL=storage.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/storage.d.ts.map b/nodejs/node_modules/lib0/storage.d.ts.map new file mode 100644 index 00000000..242a6c48 --- /dev/null +++ b/nodejs/node_modules/lib0/storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["storage.js"],"names":[],"mappings":"AAiDA;;GAEG;AAEH,6BAAuC;AAShC,8CAJa;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,KAAG,IAAI,eAIuC;AAS9G,+CAJa;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,KAAG,IAAI,eAI2C"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/storage.js b/nodejs/node_modules/lib0/storage.js new file mode 100644 index 00000000..1920ee47 --- /dev/null +++ b/nodejs/node_modules/lib0/storage.js @@ -0,0 +1,72 @@ +/* eslint-env browser */ + +/** + * Isomorphic variable storage. + * + * Uses LocalStorage in the browser and falls back to in-memory storage. + * + * @module storage + */ + +/* c8 ignore start */ +class VarStoragePolyfill { + constructor () { + this.map = new Map() + } + + /** + * @param {string} key + * @param {any} newValue + */ + setItem (key, newValue) { + this.map.set(key, newValue) + } + + /** + * @param {string} key + */ + getItem (key) { + return this.map.get(key) + } +} +/* c8 ignore stop */ + +/** + * @type {any} + */ +let _localStorage = new VarStoragePolyfill() +let usePolyfill = true + +/* c8 ignore start */ +try { + // if the same-origin rule is violated, accessing localStorage might thrown an error + if (typeof localStorage !== 'undefined' && localStorage) { + _localStorage = localStorage + usePolyfill = false + } +} catch (e) { } +/* c8 ignore stop */ + +/** + * This is basically localStorage in browser, or a polyfill in nodejs + */ +/* c8 ignore next */ +export const varStorage = _localStorage + +/** + * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used. + * + * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler + * @function + */ +/* c8 ignore next */ +export const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler)) + +/** + * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used. + * + * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler + * @function + */ +/* c8 ignore next */ +export const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler)) diff --git a/nodejs/node_modules/lib0/storage.test.d.ts b/nodejs/node_modules/lib0/storage.test.d.ts new file mode 100644 index 00000000..d87bfa9c --- /dev/null +++ b/nodejs/node_modules/lib0/storage.test.d.ts @@ -0,0 +1,3 @@ +export function testStorageModule(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=storage.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/storage.test.d.ts.map b/nodejs/node_modules/lib0/storage.test.d.ts.map new file mode 100644 index 00000000..12a8e54b --- /dev/null +++ b/nodejs/node_modules/lib0/storage.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"storage.test.d.ts","sourceRoot":"","sources":["storage.test.js"],"names":[],"mappings":"AAMO,sCAFI,EAAE,QAAQ,QAapB;mBAhBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/string.d.ts b/nodejs/node_modules/lib0/string.d.ts new file mode 100644 index 00000000..2d1d9e29 --- /dev/null +++ b/nodejs/node_modules/lib0/string.d.ts @@ -0,0 +1,26 @@ +/** + * Utility module to work with strings. + * + * @module string + */ +export const fromCharCode: (...codes: number[]) => string; +export const fromCodePoint: (...codePoints: number[]) => string; +/** + * The largest utf16 character. + * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8) + */ +export const MAX_UTF16_CHARACTER: string; +export function trimLeft(s: string): string; +export function fromCamelCase(s: string, separator: string): string; +export function utf8ByteLength(str: string): number; +export function _encodeUtf8Polyfill(str: string): Uint8Array; +export const utf8TextEncoder: TextEncoder; +export function _encodeUtf8Native(str: string): Uint8Array; +export function encodeUtf8(str: string): Uint8Array; +export function _decodeUtf8Polyfill(buf: Uint8Array): string; +export let utf8TextDecoder: TextDecoder | null; +export function _decodeUtf8Native(buf: Uint8Array): string; +export function decodeUtf8(buf: Uint8Array): string; +export function splice(str: string, index: number, remove: number, insert?: string): string; +export function repeat(source: string, n: number): string; +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/string.d.ts.map b/nodejs/node_modules/lib0/string.d.ts.map new file mode 100644 index 00000000..260583e1 --- /dev/null +++ b/nodejs/node_modules/lib0/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["string.js"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,0DAA+C;AAC/C,gEAAiD;AAEjD;;;GAGG;AACH,yCAAsD;AAc/C,4BAHI,MAAM,GACL,MAAM,CAEuC;AASlD,iCAJI,MAAM,aACN,MAAM,GACL,MAAM,CAEkH;AAO7H,oCAHI,MAAM,GACL,MAAM,CAE2D;AAMtE,yCAHI,MAAM,GACL,UAAU,CAUrB;AAGD,0CAAyH;AAMlH,uCAHI,MAAM,GACL,UAAU,CAE6C;AAjB5D,gCAHI,MAAM,GACL,UAAU,CAUrB;AAsBM,yCAHI,UAAU,GACT,MAAM,CAejB;AAGD,+CAAmI;AAkB5H,uCAHI,UAAU,GACT,MAAM,CAE8E;AAlCzF,gCAHI,UAAU,GACT,MAAM,CAejB;AAoCM,4BALI,MAAM,SACN,MAAM,UACN,MAAM,WACN,MAAM,UAEkG;AAM5G,+BAHI,MAAM,KACN,MAAM,UAE0D"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/string.js b/nodejs/node_modules/lib0/string.js new file mode 100644 index 00000000..3e97eda4 --- /dev/null +++ b/nodejs/node_modules/lib0/string.js @@ -0,0 +1,137 @@ +import * as array from './array.js' + +/** + * Utility module to work with strings. + * + * @module string + */ + +export const fromCharCode = String.fromCharCode +export const fromCodePoint = String.fromCodePoint + +/** + * The largest utf16 character. + * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8) + */ +export const MAX_UTF16_CHARACTER = fromCharCode(65535) + +/** + * @param {string} s + * @return {string} + */ +const toLowerCase = s => s.toLowerCase() + +const trimLeftRegex = /^\s*/g + +/** + * @param {string} s + * @return {string} + */ +export const trimLeft = s => s.replace(trimLeftRegex, '') + +const fromCamelCaseRegex = /([A-Z])/g + +/** + * @param {string} s + * @param {string} separator + * @return {string} + */ +export const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`)) + +/** + * Compute the utf8ByteLength + * @param {string} str + * @return {number} + */ +export const utf8ByteLength = str => unescape(encodeURIComponent(str)).length + +/** + * @param {string} str + * @return {Uint8Array} + */ +export const _encodeUtf8Polyfill = str => { + const encodedString = unescape(encodeURIComponent(str)) + const len = encodedString.length + const buf = new Uint8Array(len) + for (let i = 0; i < len; i++) { + buf[i] = /** @type {number} */ (encodedString.codePointAt(i)) + } + return buf +} + +/* c8 ignore next */ +export const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null) + +/** + * @param {string} str + * @return {Uint8Array} + */ +export const _encodeUtf8Native = str => utf8TextEncoder.encode(str) + +/** + * @param {string} str + * @return {Uint8Array} + */ +/* c8 ignore next */ +export const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill + +/** + * @param {Uint8Array} buf + * @return {string} + */ +export const _decodeUtf8Polyfill = buf => { + let remainingLen = buf.length + let encodedString = '' + let bufPos = 0 + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000 + const bytes = buf.subarray(bufPos, bufPos + nextLen) + bufPos += nextLen + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)) + remainingLen -= nextLen + } + return decodeURIComponent(escape(encodedString)) +} + +/* c8 ignore next */ +export let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) + +/* c8 ignore start */ +if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { + // Safari doesn't handle BOM correctly. + // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called. + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call + // Another issue is that from then on no BOM chars are recognized anymore + /* c8 ignore next */ + utf8TextDecoder = null +} +/* c8 ignore stop */ + +/** + * @param {Uint8Array} buf + * @return {string} + */ +export const _decodeUtf8Native = buf => /** @type {TextDecoder} */ (utf8TextDecoder).decode(buf) + +/** + * @param {Uint8Array} buf + * @return {string} + */ +/* c8 ignore next */ +export const decodeUtf8 = utf8TextDecoder ? _decodeUtf8Native : _decodeUtf8Polyfill + +/** + * @param {string} str The initial string + * @param {number} index Starting position + * @param {number} remove Number of characters to remove + * @param {string} insert New content to insert + */ +export const splice = (str, index, remove, insert = '') => str.slice(0, index) + insert + str.slice(index + remove) + +/** + * @param {string} source + * @param {number} n + */ +export const repeat = (source, n) => array.unfold(n, () => source).join('') diff --git a/nodejs/node_modules/lib0/string.test.d.ts b/nodejs/node_modules/lib0/string.test.d.ts new file mode 100644 index 00000000..af14fca6 --- /dev/null +++ b/nodejs/node_modules/lib0/string.test.d.ts @@ -0,0 +1,8 @@ +export function testUtilities(tc: t.TestCase): void; +export function testLowercaseTransformation(tc: t.TestCase): void; +export function testRepeatStringUtf8Encoding(tc: t.TestCase): void; +export function testRepeatStringUtf8Decoding(tc: t.TestCase): void; +export function testBomEncodingDecoding(tc: t.TestCase): void; +export function testSplice(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=string.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/string.test.d.ts.map b/nodejs/node_modules/lib0/string.test.d.ts.map new file mode 100644 index 00000000..cf94fbb1 --- /dev/null +++ b/nodejs/node_modules/lib0/string.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.test.d.ts","sourceRoot":"","sources":["string.test.js"],"names":[],"mappings":"AAOO,kCAFI,EAAE,QAAQ,QAMpB;AAKM,gDAFI,EAAE,QAAQ,QAOpB;AAKM,iDAFI,EAAE,QAAQ,QAapB;AAKM,iDAFI,EAAE,QAAQ,QAapB;AAKM,4CAFI,EAAE,QAAQ,QAYpB;AAKM,+BAFI,EAAE,QAAQ,QAMpB;mBA3EkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/symbol.d.ts b/nodejs/node_modules/lib0/symbol.d.ts new file mode 100644 index 00000000..d8de71b3 --- /dev/null +++ b/nodejs/node_modules/lib0/symbol.d.ts @@ -0,0 +1,13 @@ +/** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ +/** + * Return fresh symbol. + * + * @return {Symbol} + */ +export const create: SymbolConstructor; +export function isSymbol(s: any): boolean; +//# sourceMappingURL=symbol.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/symbol.d.ts.map b/nodejs/node_modules/lib0/symbol.d.ts.map new file mode 100644 index 00000000..23395075 --- /dev/null +++ b/nodejs/node_modules/lib0/symbol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.d.ts","sourceRoot":"","sources":["symbol.js"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,uCAA4B;AAMrB,4BAHI,GAAG,GACF,OAAO,CAE+B"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/symbol.js b/nodejs/node_modules/lib0/symbol.js new file mode 100644 index 00000000..7ca6a270 --- /dev/null +++ b/nodejs/node_modules/lib0/symbol.js @@ -0,0 +1,18 @@ +/** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ + +/** + * Return fresh symbol. + * + * @return {Symbol} + */ +export const create = Symbol + +/** + * @param {any} s + * @return {boolean} + */ +export const isSymbol = s => typeof s === 'symbol' diff --git a/nodejs/node_modules/lib0/symbol.test.d.ts b/nodejs/node_modules/lib0/symbol.test.d.ts new file mode 100644 index 00000000..3a29f019 --- /dev/null +++ b/nodejs/node_modules/lib0/symbol.test.d.ts @@ -0,0 +1,3 @@ +export function testBasicSymbolFeatures(_tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=symbol.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/symbol.test.d.ts.map b/nodejs/node_modules/lib0/symbol.test.d.ts.map new file mode 100644 index 00000000..bcd6654d --- /dev/null +++ b/nodejs/node_modules/lib0/symbol.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.test.d.ts","sourceRoot":"","sources":["symbol.test.js"],"names":[],"mappings":"AAMO,6CAFI,EAAE,QAAQ,QAQpB;mBAZkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/test.d.ts b/nodejs/node_modules/lib0/test.d.ts new file mode 100644 index 00000000..9bcc4712 --- /dev/null +++ b/nodejs/node_modules/lib0/test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/test.d.ts.map b/nodejs/node_modules/lib0/test.d.ts.map new file mode 100644 index 00000000..5019b824 --- /dev/null +++ b/nodejs/node_modules/lib0/test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"test.d.ts","sourceRoot":"","sources":["test.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/test.html b/nodejs/node_modules/lib0/test.html new file mode 100644 index 00000000..93e723b9 --- /dev/null +++ b/nodejs/node_modules/lib0/test.html @@ -0,0 +1,164 @@ + + + + + Testing lib0 + + + + + + + diff --git a/nodejs/node_modules/lib0/test.js b/nodejs/node_modules/lib0/test.js new file mode 100644 index 00000000..b40ff7be --- /dev/null +++ b/nodejs/node_modules/lib0/test.js @@ -0,0 +1,87 @@ +import { runTests } from './testing.js' +import * as array from './array.test.js' +import * as broadcastchannel from './broadcastchannel.test.js' +import * as crypto from './crypto.test.js' +import * as rabin from './hash/rabin.test.js' +import * as sha256 from './hash/sha256.test.js' +import * as logging from './logging.test.js' +import * as string from './string.test.js' +import * as encoding from './encoding.test.js' +import * as diff from './diff.test.js' +import * as testing from './testing.test.js' +import * as indexeddb from './indexeddb.test.js' +import * as prng from './prng.test.js' +import * as log from 'lib0/logging' +import * as statistics from './statistics.test.js' +import * as binary from './binary.test.js' +import * as random from './random.test.js' +import * as promise from './promise.test.js' +import * as queue from './queue.test.js' +import * as map from './map.test.js' +import * as eventloop from './eventloop.test.js' +import * as time from './time.test.js' +import * as pair from './pair.test.js' +import * as object from './object.test.js' +import * as observable from './observable.test.js' +import * as math from './math.test.js' +import * as number from './number.test.js' +import * as buffer from './buffer.test.js' +import * as set from './set.test.js' +import * as sort from './sort.test.js' +import * as url from './url.test.js' +import * as metric from './metric.test.js' +import * as func from './function.test.js' +import * as storage from './storage.test.js' +import * as list from './list.test.js' +import * as cache from './cache.test.js' +import * as symbol from './symbol.test.js' + +import { isBrowser, isNode } from './environment.js' + +/* c8 ignore next */ +if (isBrowser) { + log.createVConsole(document.body) +} + +runTests({ + array, + broadcastchannel, + crypto, + rabin, + sha256, + logging, + string, + encoding, + diff, + testing, + indexeddb, + prng, + statistics, + binary, + random, + promise, + queue, + map, + eventloop, + time, + pair, + object, + observable, + math, + number, + buffer, + set, + sort, + url, + metric, + func, + storage, + list, + cache, + symbol +}).then(success => { + /* c8 ignore next */ + if (isNode) { + process.exit(success ? 0 : 1) + } +}) diff --git a/nodejs/node_modules/lib0/testing.d.ts b/nodejs/node_modules/lib0/testing.d.ts new file mode 100644 index 00000000..bb1d701f --- /dev/null +++ b/nodejs/node_modules/lib0/testing.d.ts @@ -0,0 +1,64 @@ +export { production } from "./environment.js"; +export const extensive: boolean; +export const envSeed: number | null; +export class TestCase { + /** + * @param {string} moduleName + * @param {string} testName + */ + constructor(moduleName: string, testName: string); + /** + * @type {string} + */ + moduleName: string; + /** + * @type {string} + */ + testName: string; + /** + * This type can store custom information related to the TestCase + * + * @type {Map} + */ + meta: Map; + _seed: number | null; + _prng: prng.PRNG | null; + resetSeed(): void; + /** + * @type {number} + */ + get seed(): number; + /** + * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible. + * + * @type {prng.PRNG} + */ + get prng(): prng.PRNG; +} +export const repetitionTime: number; +export function run(moduleName: string, name: string, f: (arg0: TestCase) => void | Promise, i: number, numberOfTests: number): Promise; +export function describe(description: string, info?: string): void; +export function info(info: string): void; +export const printDom: (_createNode: () => Node) => void; +export const printCanvas: (canvas: HTMLCanvasElement, height: number) => void; +export function group(description: string, f: (...args: any[]) => void): void; +export function groupAsync(description: string, f: (...args: any[]) => Promise): Promise; +export function measureTime(message: string, f: (...args: any[]) => void): number; +export function measureTimeAsync(message: string, f: (...args: any[]) => Promise): Promise; +export function compareArrays(as: T[], bs: T[], m?: string | undefined): boolean; +export function compareStrings(a: string, b: string, m?: string | undefined): void; +export function compareObjects(a: any, b: any, m?: string | undefined): void; +export function compare(a: T, b: T, message?: string | null | undefined, customCompare?: ((arg0: any, arg1: T, arg2: T, arg3: string, arg4: any) => boolean) | undefined): boolean; +export function assert(property: T, message?: string | null | undefined): asserts property is NonNullable; +export function promiseRejected(f: (...args: any[]) => Promise): Promise; +export function fails(f: (...args: any[]) => void): void; +export function failsAsync(f: (...args: any[]) => Promise): Promise; +export function runTests(tests: { + [x: string]: { + [x: string]: (arg0: TestCase) => void | Promise; + }; +}): Promise; +export function fail(reason: string): never; +export function skip(cond?: boolean): void; +import * as prng from './prng.js'; +//# sourceMappingURL=testing.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/testing.d.ts.map b/nodejs/node_modules/lib0/testing.d.ts.map new file mode 100644 index 00000000..fee3643a --- /dev/null +++ b/nodejs/node_modules/lib0/testing.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["testing.js"],"names":[],"mappings":";AA8DA,gCAAiD;AAGjD,oCAAmG;AAEnG;IACE;;;OAGG;IACH,wBAHW,MAAM,YACN,MAAM,EAmBhB;IAhBC;;OAEG;IACH,YAFU,MAAM,CAEY;IAC5B;;OAEG;IACH,UAFU,MAAM,CAEQ;IACxB;;;;OAIG;IACH,MAFU,IAAI,MAAM,EAAC,GAAG,CAAC,CAEJ;IACrB,qBAAiB;IACjB,wBAAiB;IAGnB,kBAGC;IAED;;OAEG;IAEH,mBAOC;IAED;;;;OAIG;IACH,sBAMC;CACF;AAED,oCAA6E;AAgBtE,gCANI,MAAM,QACN,MAAM,YACG,QAAQ,KAAE,IAAI,GAAC,QAAQ,GAAG,CAAC,KACpC,MAAM,iBACN,MAAM,oBA0EhB;AAcM,sCAHI,MAAM,SACN,MAAM,QAEwF;AAYlG,2BAFI,MAAM,QAE6B;AAE9C,yDAAoC;AAEpC,8EAA0C;AAoBnC,mCAHI,MAAM,eACM,GAAG,OAAE,IAAI,QAS/B;AAoBM,wCAHI,MAAM,eACM,GAAG,OAAE,QAAQ,GAAG,CAAC,iBASvC;AAoBM,qCAJI,MAAM,eACM,GAAG,OAAE,IAAI,GACpB,MAAM,CAYjB;AAoBM,0CAJI,MAAM,eACM,GAAG,OAAE,QAAQ,GAAG,CAAC,GAC5B,QAAQ,MAAM,CAAC,CAY1B;AASM,4EAFK,OAAO,CAYlB;AAQM,kCALI,MAAM,KACN,MAAM,gCAUhB;AASM,mFAA2F;AAsH3F,oGAFa,GAAG,0BAAK,MAAM,QAAC,GAAG,KAAE,OAAO,wBAE8E;AAUtH,gHAA8H;AAK9H,6CAFgB,GAAG,OAAE,QAAQ,GAAG,CAAC,iBASvC;AAMM,mCAHgB,GAAG,OAAE,IAAI,QAW/B;AAMM,wCAHgB,GAAG,OAAE,QAAQ,GAAG,CAAC,iBAWvC;AAKM;QAFW,MAAM;YAAS,MAAM,UAAW,QAAQ,KAAE,IAAI,GAAC,QAAQ,GAAG,CAAC;;qBA2C5E;AAQM,6BAHI,MAAM,SAMhB;AAQM,4BAHI,OAAO,QAOjB;sBAvkBqB,WAAW"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/testing.js b/nodejs/node_modules/lib0/testing.js new file mode 100644 index 00000000..fb3ccc90 --- /dev/null +++ b/nodejs/node_modules/lib0/testing.js @@ -0,0 +1,638 @@ +/** + * Testing framework with support for generating tests. + * + * ```js + * // test.js template for creating a test executable + * import { runTests } from 'lib0/testing' + * import * as log from 'lib0/logging' + * import * as mod1 from './mod1.test.js' + * import * as mod2 from './mod2.test.js' + + * import { isBrowser, isNode } from 'lib0/environment.js' + * + * if (isBrowser) { + * // optional: if this is ran in the browser, attach a virtual console to the dom + * log.createVConsole(document.body) + * } + * + * runTests({ + * mod1, + * mod2, + * }).then(success => { + * if (isNode) { + * process.exit(success ? 0 : 1) + * } + * }) + * ``` + * + * ```js + * // mod1.test.js + * /** + * * runTests automatically tests all exported functions that start with "test". + * * The name of the function should be in camelCase and is used for the logging output. + * * + * * @param {t.TestCase} tc + * *\/ + * export const testMyFirstTest = tc => { + * t.compare({ a: 4 }, { a: 4 }, 'objects are equal') + * } + * ``` + * + * Now you can simply run `node test.js` to run your test or run test.js in the browser. + * + * @module testing + */ + +import * as log from 'lib0/logging' +import { simpleDiffString } from './diff.js' +import * as object from './object.js' +import * as string from './string.js' +import * as math from './math.js' +import * as random from './random.js' +import * as prng from './prng.js' +import * as statistics from './statistics.js' +import * as array from './array.js' +import * as env from './environment.js' +import * as json from './json.js' +import * as time from './time.js' +import * as promise from './promise.js' +import * as performance from 'lib0/performance' + +export { production } from './environment.js' + +export const extensive = env.hasConf('extensive') + +/* c8 ignore next */ +export const envSeed = env.hasParam('--seed') ? Number.parseInt(env.getParam('--seed', '0')) : null + +export class TestCase { + /** + * @param {string} moduleName + * @param {string} testName + */ + constructor (moduleName, testName) { + /** + * @type {string} + */ + this.moduleName = moduleName + /** + * @type {string} + */ + this.testName = testName + /** + * This type can store custom information related to the TestCase + * + * @type {Map} + */ + this.meta = new Map() + this._seed = null + this._prng = null + } + + resetSeed () { + this._seed = null + this._prng = null + } + + /** + * @type {number} + */ + /* c8 ignore next */ + get seed () { + /* c8 ignore else */ + if (this._seed === null) { + /* c8 ignore next */ + this._seed = envSeed === null ? random.uint32() : envSeed + } + return this._seed + } + + /** + * A PRNG for this test case. Use only this PRNG for randomness to make the test case reproducible. + * + * @type {prng.PRNG} + */ + get prng () { + /* c8 ignore else */ + if (this._prng === null) { + this._prng = prng.create(this.seed) + } + return this._prng + } +} + +export const repetitionTime = Number(env.getParam('--repetition-time', '50')) +/* c8 ignore next */ +const testFilter = env.hasParam('--filter') ? env.getParam('--filter', '') : null + +/* c8 ignore next */ +const testFilterRegExp = testFilter !== null ? new RegExp(testFilter) : /.*/ + +const repeatTestRegex = /^(repeat|repeating)\s/ + +/** + * @param {string} moduleName + * @param {string} name + * @param {function(TestCase):void|Promise} f + * @param {number} i + * @param {number} numberOfTests + */ +export const run = async (moduleName, name, f, i, numberOfTests) => { + const uncamelized = string.fromCamelCase(name.slice(4), ' ') + const filtered = !testFilterRegExp.test(`[${i + 1}/${numberOfTests}] ${moduleName}: ${uncamelized}`) + /* c8 ignore next 3 */ + if (filtered) { + return true + } + const tc = new TestCase(moduleName, name) + const repeat = repeatTestRegex.test(uncamelized) + const groupArgs = [log.GREY, `[${i + 1}/${numberOfTests}] `, log.PURPLE, `${moduleName}: `, log.BLUE, uncamelized] + /* c8 ignore next 5 */ + if (testFilter === null) { + log.groupCollapsed(...groupArgs) + } else { + log.group(...groupArgs) + } + const times = [] + const start = performance.now() + let lastTime = start + /** + * @type {any} + */ + let err = null + performance.mark(`${name}-start`) + do { + try { + const p = f(tc) + if (promise.isPromise(p)) { + await p + } + } catch (_err) { + err = _err + } + const currTime = performance.now() + times.push(currTime - lastTime) + lastTime = currTime + if (repeat && err === null && (lastTime - start) < repetitionTime) { + tc.resetSeed() + } else { + break + } + } while (err === null && (lastTime - start) < repetitionTime) + performance.mark(`${name}-end`) + /* c8 ignore next 3 */ + if (err !== null && err.constructor !== SkipError) { + log.printError(err) + } + performance.measure(name, `${name}-start`, `${name}-end`) + log.groupEnd() + const duration = lastTime - start + let success = true + times.sort((a, b) => a - b) + /* c8 ignore next 3 */ + const againMessage = env.isBrowser + ? ` - ${window.location.host + window.location.pathname}?filter=\\[${i + 1}/${tc._seed === null ? '' : `&seed=${tc._seed}`}` + : `\nrepeat: npm run test -- --filter "\\[${i + 1}/" ${tc._seed === null ? '' : `--seed ${tc._seed}`}` + const timeInfo = (repeat && err === null) + ? ` - ${times.length} repetitions in ${time.humanizeDuration(duration)} (best: ${time.humanizeDuration(times[0])}, worst: ${time.humanizeDuration(array.last(times))}, median: ${time.humanizeDuration(statistics.median(times))}, average: ${time.humanizeDuration(statistics.average(times))})` + : ` in ${time.humanizeDuration(duration)}` + if (err !== null) { + /* c8 ignore start */ + if (err.constructor === SkipError) { + log.print(log.GREY, log.BOLD, 'Skipped: ', log.UNBOLD, uncamelized) + } else { + success = false + log.print(log.RED, log.BOLD, 'Failure: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage) + } + /* c8 ignore stop */ + } else { + log.print(log.GREEN, log.BOLD, 'Success: ', log.UNBOLD, log.UNCOLOR, uncamelized, log.GREY, timeInfo, againMessage) + } + return success +} + +/** + * Describe what you are currently testing. The message will be logged. + * + * ```js + * export const testMyFirstTest = tc => { + * t.describe('crunching numbers', 'already crunched 4 numbers!') // the optional second argument can describe the state. + * } + * ``` + * + * @param {string} description + * @param {string} info + */ +export const describe = (description, info = '') => log.print(log.BLUE, description, ' ', log.GREY, info) + +/** + * Describe the state of the current computation. + * ```js + * export const testMyFirstTest = tc => { + * t.info(already crunched 4 numbers!') // the optional second argument can describe the state. + * } + * ``` + * + * @param {string} info + */ +export const info = info => describe('', info) + +export const printDom = log.printDom + +export const printCanvas = log.printCanvas + +/** + * Group outputs in a collapsible category. + * + * ```js + * export const testMyFirstTest = tc => { + * t.group('subtest 1', () => { + * t.describe('this message is part of a collapsible section') + * }) + * await t.groupAsync('subtest async 2', async () => { + * await someaction() + * t.describe('this message is part of a collapsible section') + * }) + * } + * ``` + * + * @param {string} description + * @param {function(...any):void} f + */ +export const group = (description, f) => { + log.group(log.BLUE, description) + try { + f() + } finally { + log.groupEnd() + } +} + +/** + * Group outputs in a collapsible category. + * + * ```js + * export const testMyFirstTest = async tc => { + * t.group('subtest 1', () => { + * t.describe('this message is part of a collapsible section') + * }) + * await t.groupAsync('subtest async 2', async () => { + * await someaction() + * t.describe('this message is part of a collapsible section') + * }) + * } + * ``` + * + * @param {string} description + * @param {function(...any):Promise} f + */ +export const groupAsync = async (description, f) => { + log.group(log.BLUE, description) + try { + await f() + } finally { + log.groupEnd() + } +} + +/** + * Measure the time that it takes to calculate something. + * + * ```js + * export const testMyFirstTest = async tc => { + * t.measureTime('measurement', () => { + * heavyCalculation() + * }) + * await t.groupAsync('async measurement', async () => { + * await heavyAsyncCalculation() + * }) + * } + * ``` + * + * @param {string} message + * @param {function(...any):void} f + * @return {number} Returns a promise that resolves the measured duration to apply f + */ +export const measureTime = (message, f) => { + let duration + const start = performance.now() + try { + f() + } finally { + duration = performance.now() - start + log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`) + } + return duration +} + +/** + * Measure the time that it takes to calculate something. + * + * ```js + * export const testMyFirstTest = async tc => { + * t.measureTimeAsync('measurement', async () => { + * await heavyCalculation() + * }) + * await t.groupAsync('async measurement', async () => { + * await heavyAsyncCalculation() + * }) + * } + * ``` + * + * @param {string} message + * @param {function(...any):Promise} f + * @return {Promise} Returns a promise that resolves the measured duration to apply f + */ +export const measureTimeAsync = async (message, f) => { + let duration + const start = performance.now() + try { + await f() + } finally { + duration = performance.now() - start + log.print(log.PURPLE, message, log.GREY, ` ${time.humanizeDuration(duration)}`) + } + return duration +} + +/** + * @template T + * @param {Array} as + * @param {Array} bs + * @param {string} [m] + * @return {boolean} + */ +export const compareArrays = (as, bs, m = 'Arrays match') => { + if (as.length !== bs.length) { + fail(m) + } + for (let i = 0; i < as.length; i++) { + if (as[i] !== bs[i]) { + fail(m) + } + } + return true +} + +/** + * @param {string} a + * @param {string} b + * @param {string} [m] + * @throws {TestError} Throws if tests fails + */ +export const compareStrings = (a, b, m = 'Strings match') => { + if (a !== b) { + const diff = simpleDiffString(a, b) + log.print(log.GREY, a.slice(0, diff.index), log.RED, a.slice(diff.index, diff.remove), log.GREEN, diff.insert, log.GREY, a.slice(diff.index + diff.remove)) + fail(m) + } +} + +/** + * @template K,V + * @param {Object} a + * @param {Object} b + * @param {string} [m] + * @throws {TestError} Throws if test fails + */ +export const compareObjects = (a, b, m = 'Objects match') => { object.equalFlat(a, b) || fail(m) } + +/** + * @param {any} _constructor + * @param {any} a + * @param {any} b + * @param {string} path + * @throws {TestError} + */ +const compareValues = (_constructor, a, b, path) => { + if (a !== b) { + fail(`Values ${json.stringify(a)} and ${json.stringify(b)} don't match (${path})`) + } + return true +} + +/** + * @param {string?} message + * @param {string} reason + * @param {string} path + * @throws {TestError} + */ +const _failMessage = (message, reason, path) => fail( + message === null + ? `${reason} ${path}` + : `${message} (${reason}) ${path}` +) + +/** + * @param {any} a + * @param {any} b + * @param {string} path + * @param {string?} message + * @param {function(any,any,any,string,any):boolean} customCompare + */ +const _compare = (a, b, path, message, customCompare) => { + // we don't use assert here because we want to test all branches (istanbul errors if one branch is not tested) + if (a == null || b == null) { + return compareValues(null, a, b, path) + } + if (a.constructor !== b.constructor) { + _failMessage(message, 'Constructors don\'t match', path) + } + let success = true + switch (a.constructor) { + case ArrayBuffer: + a = new Uint8Array(a) + b = new Uint8Array(b) + // eslint-disable-next-line no-fallthrough + case Uint8Array: { + if (a.byteLength !== b.byteLength) { + _failMessage(message, 'ArrayBuffer lengths match', path) + } + for (let i = 0; success && i < a.length; i++) { + success = success && a[i] === b[i] + } + break + } + case Set: { + if (a.size !== b.size) { + _failMessage(message, 'Sets have different number of attributes', path) + } + // @ts-ignore + a.forEach(value => { + if (!b.has(value)) { + _failMessage(message, `b.${path} does have ${value}`, path) + } + }) + break + } + case Map: { + if (a.size !== b.size) { + _failMessage(message, 'Maps have different number of attributes', path) + } + // @ts-ignore + a.forEach((value, key) => { + if (!b.has(key)) { + _failMessage(message, `Property ${path}["${key}"] does not exist on second argument`, path) + } + _compare(value, b.get(key), `${path}["${key}"]`, message, customCompare) + }) + break + } + case Object: + if (object.length(a) !== object.length(b)) { + _failMessage(message, 'Objects have a different number of attributes', path) + } + object.forEach(a, (value, key) => { + if (!object.hasProperty(b, key)) { + _failMessage(message, `Property ${path} does not exist on second argument`, path) + } + _compare(value, b[key], `${path}["${key}"]`, message, customCompare) + }) + break + case Array: + if (a.length !== b.length) { + _failMessage(message, 'Arrays have a different number of attributes', path) + } + // @ts-ignore + a.forEach((value, i) => _compare(value, b[i], `${path}[${i}]`, message, customCompare)) + break + /* c8 ignore next 4 */ + default: + if (!customCompare(a.constructor, a, b, path, compareValues)) { + _failMessage(message, `Values ${json.stringify(a)} and ${json.stringify(b)} don't match`, path) + } + } + assert(success, message) + return true +} + +/** + * @template T + * @param {T} a + * @param {T} b + * @param {string?} [message] + * @param {function(any,T,T,string,any):boolean} [customCompare] + */ +export const compare = (a, b, message = null, customCompare = compareValues) => _compare(a, b, 'obj', message, customCompare) + +/** + * @template T + * @param {T} property + * @param {string?} [message] + * @return {asserts property is NonNullable} + * @throws {TestError} + */ +/* c8 ignore next */ +export const assert = (property, message = null) => { property || fail(`Assertion failed${message !== null ? `: ${message}` : ''}`) } + +/** + * @param {function(...any):Promise} f + */ +export const promiseRejected = async f => { + try { + await f() + } catch (err) { + return + } + fail('Expected promise to fail') +} + +/** + * @param {function(...any):void} f + * @throws {TestError} + */ +export const fails = f => { + try { + f() + } catch (_err) { + log.print(log.GREEN, '⇖ This Error was expected') + return + } + fail('Expected this to fail') +} + +/** + * @param {function(...any):Promise} f + * @throws {TestError} + */ +export const failsAsync = async f => { + try { + await f() + } catch (_err) { + log.print(log.GREEN, '⇖ This Error was expected') + return + } + fail('Expected this to fail') +} + +/** + * @param {Object>>} tests + */ +export const runTests = async tests => { + /** + * @param {string} testname + */ + const filterTest = testname => testname.startsWith('test') || testname.startsWith('benchmark') + const numberOfTests = object.map(tests, mod => object.map(mod, (f, fname) => /* c8 ignore next */ f && filterTest(fname) ? 1 : 0).reduce(math.add, 0)).reduce(math.add, 0) + let successfulTests = 0 + let testnumber = 0 + const start = performance.now() + for (const modName in tests) { + const mod = tests[modName] + for (const fname in mod) { + const f = mod[fname] + /* c8 ignore else */ + if (f && filterTest(fname)) { + const repeatEachTest = 1 + let success = true + for (let i = 0; success && i < repeatEachTest; i++) { + success = await run(modName, fname, f, testnumber, numberOfTests) + } + testnumber++ + /* c8 ignore else */ + if (success) { + successfulTests++ + } + } + } + } + const end = performance.now() + log.print('') + const success = successfulTests === numberOfTests + /* c8 ignore start */ + if (success) { + log.print(log.GREEN, log.BOLD, 'All tests successful!', log.GREY, log.UNBOLD, ` in ${time.humanizeDuration(end - start)}`) + log.printImgBase64(nyanCatImage, 50) + } else { + const failedTests = numberOfTests - successfulTests + log.print(log.RED, log.BOLD, `> ${failedTests} test${failedTests > 1 ? 's' : ''} failed`) + } + /* c8 ignore stop */ + return success +} + +class TestError extends Error {} + +/** + * @param {string} reason + * @throws {TestError} + */ +export const fail = reason => { + log.print(log.RED, log.BOLD, 'X ', log.UNBOLD, reason) + throw new TestError('Test Failed') +} + +class SkipError extends Error {} + +/** + * @param {boolean} cond If true, this tests will be skipped + * @throws {SkipError} + */ +export const skip = (cond = true) => { + if (cond) { + throw new SkipError('skipping..') + } +} + +// eslint-disable-next-line +const nyanCatImage = 'R0lGODlhjABMAPcAAMiSE0xMTEzMzUKJzjQ0NFsoKPc7//FM/9mH/z9x0HIiIoKCgmBHN+frGSkZLdDQ0LCwsDk71g0KCUzDdrQQEOFz/8yYdelmBdTiHFxcXDU2erR/mLrTHCgoKK5szBQUFNgSCTk6ymfpCB9VZS2Bl+cGBt2N8kWm0uDcGXhZRUvGq94NCFPhDiwsLGVlZTgqIPMDA1g3aEzS5D6xAURERDtG9JmBjJsZGWs2AD1W6Hp6eswyDeJ4CFNTU1LcEoJRmTMzSd14CTg5ser2GmDzBd17/xkZGUzMvoSMDiEhIfKruCwNAJaWlvRzA8kNDXDrCfi0pe1U/+GS6SZrAB4eHpZwVhoabsx9oiYmJt/TGHFxcYyMjOid0+Zl/0rF6j09PeRr/0zU9DxO6j+z0lXtBtp8qJhMAEssLGhoaPL/GVn/AAsWJ/9/AE3Z/zs9/3cAAOlf/+aa2RIyADo85uhh/0i84WtrazQ0UyMlmDMzPwUFBe16BTMmHau0E03X+g8pMEAoS1MBAf++kkzO8pBaqSZoe9uB/zE0BUQ3Sv///4WFheuiyzo880gzNDIyNissBNqF/8RiAOF2qG5ubj0vL1z6Avl5ASsgGkgUSy8vL/8n/z4zJy8lOv96uEssV1csAN5ZCDQ0Wz1a3tbEGHLeDdYKCg4PATE7PiMVFSoqU83eHEi43gUPAOZ8reGogeKU5dBBC8faHEez2lHYF4bQFMukFtl4CzY3kkzBVJfMGZkAAMfSFf27mP0t//g4/9R6Dfsy/1DRIUnSAPRD/0fMAFQ0Q+l7rnbaD0vEntCDD6rSGtO8GNpUCU/MK07LPNEfC7RaABUWWkgtOst+71v9AfD7GfDw8P19ATtA/NJpAONgB9yL+fm6jzIxMdnNGJxht1/2A9x//9jHGOSX3+5tBP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xLLNltqssqMyi+yz1SJLrahNTAvttd8mS2q32pJ6ATTQfCKma10YZ+YGV1wRJIkuzAgkvPKwOQIb/Pbr778AByzwwAQXbPDBBZvxSWNSbBMOrghEAR0CZl7RSSclJlkiheawaEwnZeibxchplJxGAyOP3IDJaaCQchbVsPxyFiyjnPLKJruccswlV/MyCjW/jHPJOo/Mcxo+pwy0yTarbHIfnL2ioGvvaGExxrzaJ+wCdvT3ccgE9TzE2GOzTDbZZp/NcjVnD5G22ia3vbbccZ99dBp0iw13yWdD/10aF5BERx899CzwhQTxxHMP4hL0R08GlxQEDjiVqGG5GtRMPnnll1eiOTjUXK7G5+CInrnmoXf+eeqWf8655adPzroanqN+eeyUm7665TNMsQlnUCgh/PDCu1JFD/6ZqPzyvhJgEOxHRH8EGaITIf0R7oh+/RGiV3I99ZdbL332l2/f/fVEVH/962qYf7k76ItOxhEzuABkBhbkr//++aeQyf0ADKDzDBKGArbhgG3wQwEL6AcEtmGBBnQgBMPgQAUusIEInKADHwjBCkIQgwfUoAQ7iEALMtAPa5iEfbTQIT0YgTxGKJAMvfSFDhDoHgT4AgE6hBA/+GEQ2AgiNvy84EMfekGI2BhEEf1QAyQuEYhCJGIRjyhEJRaxiUJ8IhKlaEQkWtGHWAyiFqO4RC/UIIUl2s4H9PAlw+lrBPHQQ4UCtDU7vJEgbsijHvfIxz768Y+ADKQgB0lIQGJjDdvZjkBstJ3EHCSRRLLRHQnCiEoSJAKVrOQcCCKGTDIiApTMpBgIMgdPbnIgncxkQTw5yoGUMpOnFEgqLRnKSrZSIK/U5Ag+kLjEDaSXCQGmQHzJpWIasyV3OaYyl8nMZi7nLsl0ZkagKc1qWvOa2JxLNLPJzW6+ZZvevAhdwrkStJCTI2gZ5zknos51shOc7oynPOdJz3ra857hDAgAOw==' diff --git a/nodejs/node_modules/lib0/testing.test.d.ts b/nodejs/node_modules/lib0/testing.test.d.ts new file mode 100644 index 00000000..9007956f --- /dev/null +++ b/nodejs/node_modules/lib0/testing.test.d.ts @@ -0,0 +1,9 @@ +export function nottestingNotTested(): void; +export function testAssertTyping(): void; +export function testComparing(_tc: t.TestCase): void; +export function testFailing(): Promise; +export function testSkipping(): void; +export function testAsync(): Promise; +export function testRepeatRepetition(): void; +import * as t from './testing.js'; +//# sourceMappingURL=testing.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/testing.test.d.ts.map b/nodejs/node_modules/lib0/testing.test.d.ts.map new file mode 100644 index 00000000..28a9f188 --- /dev/null +++ b/nodejs/node_modules/lib0/testing.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"testing.test.d.ts","sourceRoot":"","sources":["testing.test.js"],"names":[],"mappings":"AAQO,4CAEN;AAEM,yCAMN;AAKM,mCAFI,EAAE,QAAQ,QA+FpB;AAEM,6CAcN;AAEM,qCAMN;AAEM,2CAIN;AAEM,6CAON;mBA3JkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/time.d.ts b/nodejs/node_modules/lib0/time.d.ts new file mode 100644 index 00000000..5ee1371b --- /dev/null +++ b/nodejs/node_modules/lib0/time.d.ts @@ -0,0 +1,9 @@ +export function getDate(): Date; +/** + * Return current unix time. + * + * @return {number} + */ +export const getUnixTime: () => number; +export function humanizeDuration(d: number): string; +//# sourceMappingURL=time.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/time.d.ts.map b/nodejs/node_modules/lib0/time.d.ts.map new file mode 100644 index 00000000..15c07c21 --- /dev/null +++ b/nodejs/node_modules/lib0/time.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"time.d.ts","sourceRoot":"","sources":["time.js"],"names":[],"mappings":"AAcO,2BAFK,IAAI,CAEuB;AAEvC;;;;GAIG;AACH,uCAAmC;AAQ5B,oCAHI,MAAM,GACL,MAAM,CAoBjB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/time.js b/nodejs/node_modules/lib0/time.js new file mode 100644 index 00000000..07965c6c --- /dev/null +++ b/nodejs/node_modules/lib0/time.js @@ -0,0 +1,48 @@ +/** + * Utility module to work with time. + * + * @module time + */ + +import * as metric from './metric.js' +import * as math from './math.js' + +/** + * Return current time. + * + * @return {Date} + */ +export const getDate = () => new Date() + +/** + * Return current unix time. + * + * @return {number} + */ +export const getUnixTime = Date.now + +/** + * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs. + * + * @param {number} d duration in milliseconds + * @return {string} humanized approximation of time + */ +export const humanizeDuration = d => { + if (d < 60000) { + const p = metric.prefix(d, -1) + return math.round(p.n * 100) / 100 + p.prefix + 's' + } + d = math.floor(d / 1000) + const seconds = d % 60 + const minutes = math.floor(d / 60) % 60 + const hours = math.floor(d / 3600) % 24 + const days = math.floor(d / 86400) + if (days > 0) { + return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '') + } + if (hours > 0) { + /* c8 ignore next */ + return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '') + } + return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '') +} diff --git a/nodejs/node_modules/lib0/time.test.d.ts b/nodejs/node_modules/lib0/time.test.d.ts new file mode 100644 index 00000000..614187b2 --- /dev/null +++ b/nodejs/node_modules/lib0/time.test.d.ts @@ -0,0 +1,4 @@ +export function testTime(tc: t.TestCase): void; +export function testHumanDuration(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=time.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/time.test.d.ts.map b/nodejs/node_modules/lib0/time.test.d.ts.map new file mode 100644 index 00000000..b2f644e0 --- /dev/null +++ b/nodejs/node_modules/lib0/time.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"time.test.d.ts","sourceRoot":"","sources":["time.test.js"],"names":[],"mappings":"AAOO,6BAFI,EAAE,QAAQ,QAMpB;AAKM,sCAFI,EAAE,QAAQ,QAmBpB;mBAhCkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/tree.d.ts b/nodejs/node_modules/lib0/tree.d.ts new file mode 100644 index 00000000..7d4535cf --- /dev/null +++ b/nodejs/node_modules/lib0/tree.d.ts @@ -0,0 +1,96 @@ +/** + * This is a Red Black Tree implementation + * + * @template K,V + */ +export class Tree { + root: any; + length: number; + /** + * @param {K} id + */ + findNext(id: K): V; + /** + * @param {K} id + */ + findPrev(id: K): V; + /** + * @param {K} from + */ + findNodeWithLowerBound(from: K): any; + /** + * @param {K} to + */ + findNodeWithUpperBound(to: K): any; + /** + * @return {V} + */ + findSmallestNode(): V; + /** + * @param {K} from + * @return {V} + */ + findWithLowerBound(from: K): V; + /** + * @param {K} to + * @return {V} + */ + findWithUpperBound(to: K): V; + /** + * @param {K} from + * @param {V} from + * @param {function(V):void} f + */ + iterate(from: K, to: any, f: (arg0: V) => void): void; + /** + * @param {K} id + * @return {V|null} + */ + find(id: K): V | null; + /** + * @param {K} id + * @return {N|null} + */ + findNode(id: K): N | null; + /** + * @param {K} id + */ + delete(id: K): void; + _fixDelete(n: any): void; + put(v: any): any; + _fixInsert(n: any): void; +} +/** + * @template V + */ +declare class N { + /** + * A created node is always red! + * + * @param {V} val + */ + constructor(val: V); + val: V; + color: boolean; + _left: any; + _right: any; + _parent: any; + isRed(): boolean; + isBlack(): boolean; + redden(): N; + blacken(): N; + get grandparent(): any; + get parent(): any; + get sibling(): any; + set left(arg: any); + get left(): any; + set right(arg: any); + get right(): any; + rotateLeft(tree: any): void; + next(): any; + prev(): any; + rotateRight(tree: any): void; + getUncle(): any; +} +export {}; +//# sourceMappingURL=tree.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/tree.d.ts.map b/nodejs/node_modules/lib0/tree.d.ts.map new file mode 100644 index 00000000..b67490a5 --- /dev/null +++ b/nodejs/node_modules/lib0/tree.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tree.d.ts","sourceRoot":"","sources":["tree.js"],"names":[],"mappings":"AAiJA;;;;GAIG;AACH;IAEI,UAAgB;IAChB,eAAe;IAGjB;;OAEG;IACH,aAFW,CAAC,KAMX;IAED;;OAEG;IACH,aAFW,CAAC,KAMX;IAED;;OAEG;IACH,6BAFW,CAAC,OA0BX;IAED;;OAEG;IACH,2BAFW,CAAC,OA6BX;IAED;;OAEG;IACH,oBAFY,CAAC,CAQZ;IAED;;;OAGG;IACH,yBAHW,CAAC,GACA,CAAC,CAKZ;IAED;;;OAGG;IACH,uBAHW,CAAC,GACA,CAAC,CAKZ;IAED;;;;OAIG;IACH,cAJW,CAAC,qBAEQ,CAAC,KAAE,IAAI,QAoB1B;IAED;;;OAGG;IACH,SAHW,CAAC,GACA,CAAC,GAAC,IAAI,CASjB;IAED;;;OAGG;IACH,aAHW,CAAC,GACA,EAAE,CAAC,CAAC,GAAC,IAAI,CAoBpB;IAED;;OAEG;IACH,WAFW,CAAC,QAmEX;IAED,yBAmEC;IAED,iBA+BC;IAED,yBA8CC;CACF;AA7gBD;;GAEG;AACH;IACE;;;;OAIG;IACH,iBAFW,CAAC,EAQX;IALC,OAAc;IACd,eAAiB;IACjB,WAAiB;IACjB,YAAkB;IAClB,aAAmB;IAGrB,iBAA8B;IAC9B,mBAAiC;IACjC,eAA4C;IAC5C,gBAA8C;IAC9C,uBAEC;IAED,kBAEC;IAED,mBAIC;IAUD,mBAKC;IAbD,gBAEC;IAaD,oBAKC;IAhBD,iBAEC;IAgBD,4BAOC;IAED,YAeC;IAED,YAeC;IAED,6BAOC;IAED,gBAOC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/tree.js b/nodejs/node_modules/lib0/tree.js new file mode 100644 index 00000000..330aada5 --- /dev/null +++ b/nodejs/node_modules/lib0/tree.js @@ -0,0 +1,546 @@ +/** + * Red-black-tree implementation. + * + * @module tree + */ +// @ts-nocheck TODO: remove or refactor this file + +const rotate = (tree, parent, newParent, n) => { + if (parent === null) { + tree.root = newParent + newParent._parent = null + } else if (parent.left === n) { + parent.left = newParent + } else if (parent.right === n) { + parent.right = newParent + } else { + throw new Error('The elements are wrongly connected!') + } +} + +/** + * @template V + */ +class N { + /** + * A created node is always red! + * + * @param {V} val + */ + constructor (val) { + this.val = val + this.color = true + this._left = null + this._right = null + this._parent = null + } + + isRed () { return this.color } + isBlack () { return !this.color } + redden () { this.color = true; return this } + blacken () { this.color = false; return this } + get grandparent () { + return this.parent.parent + } + + get parent () { + return this._parent + } + + get sibling () { + return (this === this.parent.left) + ? this.parent.right + : this.parent.left + } + + get left () { + return this._left + } + + get right () { + return this._right + } + + set left (n) { + if (n !== null) { + n._parent = this + } + this._left = n + } + + set right (n) { + if (n !== null) { + n._parent = this + } + this._right = n + } + + rotateLeft (tree) { + const parent = this.parent + const newParent = this.right + const newRight = this.right.left + newParent.left = this + this.right = newRight + rotate(tree, parent, newParent, this) + } + + next () { + if (this.right !== null) { + // search the most left node in the right tree + let o = this.right + while (o.left !== null) { + o = o.left + } + return o + } else { + let p = this + while (p.parent !== null && p !== p.parent.left) { + p = p.parent + } + return p.parent + } + } + + prev () { + if (this.left !== null) { + // search the most right node in the left tree + let o = this.left + while (o.right !== null) { + o = o.right + } + return o + } else { + let p = this + while (p.parent !== null && p !== p.parent.right) { + p = p.parent + } + return p.parent + } + } + + rotateRight (tree) { + const parent = this.parent + const newParent = this.left + const newLeft = this.left.right + newParent.right = this + this.left = newLeft + rotate(tree, parent, newParent, this) + } + + getUncle () { + // we can assume that grandparent exists when this is called! + if (this.parent === this.parent.parent.left) { + return this.parent.parent.right + } else { + return this.parent.parent.left + } + } +} + +const isBlack = node => + node !== null ? node.isBlack() : true + +const isRed = (node) => + node !== null ? node.isRed() : false + +/** + * This is a Red Black Tree implementation + * + * @template K,V + */ +export class Tree { + constructor () { + this.root = null + this.length = 0 + } + + /** + * @param {K} id + */ + findNext (id) { + const nextID = id.clone() + nextID.clock += 1 + return this.findWithLowerBound(nextID) + } + + /** + * @param {K} id + */ + findPrev (id) { + const prevID = id.clone() + prevID.clock -= 1 + return this.findWithUpperBound(prevID) + } + + /** + * @param {K} from + */ + findNodeWithLowerBound (from) { + let o = this.root + if (o === null) { + return null + } else { + while (true) { + if (from === null || (from.lessThan(o.val._id) && o.left !== null)) { + // o is included in the bound + // try to find an element that is closer to the bound + o = o.left + } else if (from !== null && o.val._id.lessThan(from)) { + // o is not within the bound, maybe one of the right elements is.. + if (o.right !== null) { + o = o.right + } else { + // there is no right element. Search for the next bigger element, + // this should be within the bounds + return o.next() + } + } else { + return o + } + } + } + } + + /** + * @param {K} to + */ + findNodeWithUpperBound (to) { + if (to === undefined) { + throw new Error('You must define from!') + } + let o = this.root + if (o === null) { + return null + } else { + while (true) { + if ((to === null || o.val._id.lessThan(to)) && o.right !== null) { + // o is included in the bound + // try to find an element that is closer to the bound + o = o.right + } else if (to !== null && to.lessThan(o.val._id)) { + // o is not within the bound, maybe one of the left elements is.. + if (o.left !== null) { + o = o.left + } else { + // there is no left element. Search for the prev smaller element, + // this should be within the bounds + return o.prev() + } + } else { + return o + } + } + } + } + + /** + * @return {V} + */ + findSmallestNode () { + let o = this.root + while (o != null && o.left != null) { + o = o.left + } + return o + } + + /** + * @param {K} from + * @return {V} + */ + findWithLowerBound (from) { + const n = this.findNodeWithLowerBound(from) + return n == null ? null : n.val + } + + /** + * @param {K} to + * @return {V} + */ + findWithUpperBound (to) { + const n = this.findNodeWithUpperBound(to) + return n == null ? null : n.val + } + + /** + * @param {K} from + * @param {V} from + * @param {function(V):void} f + */ + iterate (from, to, f) { + let o + if (from === null) { + o = this.findSmallestNode() + } else { + o = this.findNodeWithLowerBound(from) + } + while ( + o !== null && + ( + to === null || // eslint-disable-line no-unmodified-loop-condition + o.val._id.lessThan(to) || + o.val._id.equals(to) + ) + ) { + f(o.val) + o = o.next() + } + } + + /** + * @param {K} id + * @return {V|null} + */ + find (id) { + const n = this.findNode(id) + if (n !== null) { + return n.val + } else { + return null + } + } + + /** + * @param {K} id + * @return {N|null} + */ + findNode (id) { + let o = this.root + if (o === null) { + return null + } else { + while (true) { + if (o === null) { + return null + } + if (id.lessThan(o.val._id)) { + o = o.left + } else if (o.val._id.lessThan(id)) { + o = o.right + } else { + return o + } + } + } + } + + /** + * @param {K} id + */ + delete (id) { + let d = this.findNode(id) + if (d == null) { + // throw new Error('Element does not exist!') + return + } + this.length-- + if (d.left !== null && d.right !== null) { + // switch d with the greates element in the left subtree. + // o should have at most one child. + let o = d.left + // find + while (o.right !== null) { + o = o.right + } + // switch + d.val = o.val + d = o + } + // d has at most one child + // let n be the node that replaces d + let isFakeChild + let child = d.left || d.right + if (child === null) { + isFakeChild = true + child = new N(null) + child.blacken() + d.right = child + } else { + isFakeChild = false + } + + if (d.parent === null) { + if (!isFakeChild) { + this.root = child + child.blacken() + child._parent = null + } else { + this.root = null + } + return + } else if (d.parent.left === d) { + d.parent.left = child + } else if (d.parent.right === d) { + d.parent.right = child + } else { + throw new Error('Impossible!') + } + if (d.isBlack()) { + if (child.isRed()) { + child.blacken() + } else { + this._fixDelete(child) + } + } + this.root.blacken() + if (isFakeChild) { + if (child.parent.left === child) { + child.parent.left = null + } else if (child.parent.right === child) { + child.parent.right = null + } else { + throw new Error('Impossible #3') + } + } + } + + _fixDelete (n) { + if (n.parent === null) { + // this can only be called after the first iteration of fixDelete. + return + } + // d was already replaced by the child + // d is not the root + // d and child are black + let sibling = n.sibling + if (isRed(sibling)) { + // make sibling the grandfather + n.parent.redden() + sibling.blacken() + if (n === n.parent.left) { + n.parent.rotateLeft(this) + } else if (n === n.parent.right) { + n.parent.rotateRight(this) + } else { + throw new Error('Impossible #2') + } + sibling = n.sibling + } + // parent, sibling, and children of n are black + if (n.parent.isBlack() && + sibling.isBlack() && + isBlack(sibling.left) && + isBlack(sibling.right) + ) { + sibling.redden() + this._fixDelete(n.parent) + } else if (n.parent.isRed() && + sibling.isBlack() && + isBlack(sibling.left) && + isBlack(sibling.right) + ) { + sibling.redden() + n.parent.blacken() + } else { + if (n === n.parent.left && + sibling.isBlack() && + isRed(sibling.left) && + isBlack(sibling.right) + ) { + sibling.redden() + sibling.left.blacken() + sibling.rotateRight(this) + sibling = n.sibling + } else if (n === n.parent.right && + sibling.isBlack() && + isRed(sibling.right) && + isBlack(sibling.left) + ) { + sibling.redden() + sibling.right.blacken() + sibling.rotateLeft(this) + sibling = n.sibling + } + sibling.color = n.parent.color + n.parent.blacken() + if (n === n.parent.left) { + sibling.right.blacken() + n.parent.rotateLeft(this) + } else { + sibling.left.blacken() + n.parent.rotateRight(this) + } + } + } + + put (v) { + const node = new N(v) + if (this.root !== null) { + let p = this.root // p abbrev. parent + while (true) { + if (node.val._id.lessThan(p.val._id)) { + if (p.left === null) { + p.left = node + break + } else { + p = p.left + } + } else if (p.val._id.lessThan(node.val._id)) { + if (p.right === null) { + p.right = node + break + } else { + p = p.right + } + } else { + p.val = node.val + return p + } + } + this._fixInsert(node) + } else { + this.root = node + } + this.length++ + this.root.blacken() + return node + } + + _fixInsert (n) { + if (n.parent === null) { + n.blacken() + return + } else if (n.parent.isBlack()) { + return + } + const uncle = n.getUncle() + if (uncle !== null && uncle.isRed()) { + // Note: parent: red, uncle: red + n.parent.blacken() + uncle.blacken() + n.grandparent.redden() + this._fixInsert(n.grandparent) + } else { + // Note: parent: red, uncle: black or null + // Now we transform the tree in such a way that + // either of these holds: + // 1) grandparent.left.isRed + // and grandparent.left.left.isRed + // 2) grandparent.right.isRed + // and grandparent.right.right.isRed + if (n === n.parent.right && n.parent === n.grandparent.left) { + n.parent.rotateLeft(this) + // Since we rotated and want to use the previous + // cases, we need to set n in such a way that + // n.parent.isRed again + n = n.left + } else if (n === n.parent.left && n.parent === n.grandparent.right) { + n.parent.rotateRight(this) + // see above + n = n.right + } + // Case 1) or 2) hold from here on. + // Now traverse grandparent, make parent a black node + // on the highest level which holds two red nodes. + n.parent.blacken() + n.grandparent.redden() + if (n === n.parent.left) { + // Case 1 + n.grandparent.rotateRight(this) + } else { + // Case 2 + n.grandparent.rotateLeft(this) + } + } + } +} diff --git a/nodejs/node_modules/lib0/tree.test.d.ts b/nodejs/node_modules/lib0/tree.test.d.ts new file mode 100644 index 00000000..54a03d2c --- /dev/null +++ b/nodejs/node_modules/lib0/tree.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=tree.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/tree.test.d.ts.map b/nodejs/node_modules/lib0/tree.test.d.ts.map new file mode 100644 index 00000000..5fe96687 --- /dev/null +++ b/nodejs/node_modules/lib0/tree.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tree.test.d.ts","sourceRoot":"","sources":["tree.test.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/url.d.ts b/nodejs/node_modules/lib0/url.d.ts new file mode 100644 index 00000000..ed2895c9 --- /dev/null +++ b/nodejs/node_modules/lib0/url.d.ts @@ -0,0 +1,7 @@ +export function decodeQueryParams(url: string): { + [x: string]: string; +}; +export function encodeQueryParams(params: { + [x: string]: string; +}): string; +//# sourceMappingURL=url.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/url.d.ts.map b/nodejs/node_modules/lib0/url.d.ts.map new file mode 100644 index 00000000..069175b6 --- /dev/null +++ b/nodejs/node_modules/lib0/url.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"url.d.ts","sourceRoot":"","sources":["url.js"],"names":[],"mappings":"AAcO,uCAHI,MAAM;QACE,MAAM,GAAC,MAAM;EAiB/B;AAMM;QAHW,MAAM,GAAC,MAAM;IACnB,MAAM,CAGmF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/url.js b/nodejs/node_modules/lib0/url.js new file mode 100644 index 00000000..4419820e --- /dev/null +++ b/nodejs/node_modules/lib0/url.js @@ -0,0 +1,37 @@ +/** + * Utility module to work with urls. + * + * @module url + */ + +import * as object from './object.js' + +/** + * Parse query parameters from an url. + * + * @param {string} url + * @return {Object} + */ +export const decodeQueryParams = url => { + /** + * @type {Object} + */ + const query = {} + const urlQuerySplit = url.split('?') + const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&') + for (let i = 0; i < pairs.length; i++) { + const item = pairs[i] + if (item.length > 0) { + const pair = item.split('=') + query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '') + } + } + return query +} + +/** + * @param {Object} params + * @return {string} + */ +export const encodeQueryParams = params => + object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&') diff --git a/nodejs/node_modules/lib0/url.test.d.ts b/nodejs/node_modules/lib0/url.test.d.ts new file mode 100644 index 00000000..027c9ee7 --- /dev/null +++ b/nodejs/node_modules/lib0/url.test.d.ts @@ -0,0 +1,3 @@ +export function testUrlParamQuery(tc: t.TestCase): void; +import * as t from './testing.js'; +//# sourceMappingURL=url.test.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/url.test.d.ts.map b/nodejs/node_modules/lib0/url.test.d.ts.map new file mode 100644 index 00000000..cbb7f531 --- /dev/null +++ b/nodejs/node_modules/lib0/url.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"url.test.d.ts","sourceRoot":"","sources":["url.test.js"],"names":[],"mappings":"AAcO,sCAFI,EAAE,QAAQ,QAapB;mBAzBkB,cAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.d.ts b/nodejs/node_modules/lib0/webcrypto.d.ts new file mode 100644 index 00000000..ea1852e9 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.d.ts @@ -0,0 +1,3 @@ +export const subtle: SubtleCrypto; +export const getRandomValues: (array: T) => T; +//# sourceMappingURL=webcrypto.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.d.ts.map b/nodejs/node_modules/lib0/webcrypto.d.ts.map new file mode 100644 index 00000000..7071f6b7 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["webcrypto.js"],"names":[],"mappings":"AAEA,kCAAmC;AACnC,gFAAkE"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.deno.d.ts b/nodejs/node_modules/lib0/webcrypto.deno.d.ts new file mode 100644 index 00000000..ec6b5e5a --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.deno.d.ts @@ -0,0 +1,3 @@ +export const subtle: any; +export const getRandomValues: any; +//# sourceMappingURL=webcrypto.deno.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.deno.d.ts.map b/nodejs/node_modules/lib0/webcrypto.deno.d.ts.map new file mode 100644 index 00000000..73ccad26 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.deno.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.deno.d.ts","sourceRoot":"","sources":["webcrypto.deno.js"],"names":[],"mappings":"AACA,yBAAwD;AAExD,kCAAuF"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.deno.js b/nodejs/node_modules/lib0/webcrypto.deno.js new file mode 100644 index 00000000..f94cdac0 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.deno.js @@ -0,0 +1,4 @@ +// eslint-disable-next-line +export const subtle = /** @type {any} */ (crypto).subtle +// eslint-disable-next-line +export const getRandomValues = /** @type {any} */ (crypto).getRandomValues.bind(crypto) diff --git a/nodejs/node_modules/lib0/webcrypto.js b/nodejs/node_modules/lib0/webcrypto.js new file mode 100644 index 00000000..3849bf42 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.js @@ -0,0 +1,4 @@ +/* eslint-env browser */ + +export const subtle = crypto.subtle +export const getRandomValues = crypto.getRandomValues.bind(crypto) diff --git a/nodejs/node_modules/lib0/webcrypto.node.d.ts b/nodejs/node_modules/lib0/webcrypto.node.d.ts new file mode 100644 index 00000000..0026211a --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.node.d.ts @@ -0,0 +1,3 @@ +export const subtle: any; +export const getRandomValues: any; +//# sourceMappingURL=webcrypto.node.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.node.d.ts.map b/nodejs/node_modules/lib0/webcrypto.node.d.ts.map new file mode 100644 index 00000000..5e9eb923 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.node.d.ts","sourceRoot":"","sources":["webcrypto.node.js"],"names":[],"mappings":"AAEA,yBAA2D;AAC3D,kCAA6F"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/webcrypto.node.js b/nodejs/node_modules/lib0/webcrypto.node.js new file mode 100644 index 00000000..f37a1003 --- /dev/null +++ b/nodejs/node_modules/lib0/webcrypto.node.js @@ -0,0 +1,4 @@ +import { webcrypto } from 'node:crypto' + +export const subtle = /** @type {any} */ (webcrypto).subtle +export const getRandomValues = /** @type {any} */ (webcrypto).getRandomValues.bind(webcrypto) diff --git a/nodejs/node_modules/lib0/websocket.d.ts b/nodejs/node_modules/lib0/websocket.d.ts new file mode 100644 index 00000000..2990beda --- /dev/null +++ b/nodejs/node_modules/lib0/websocket.d.ts @@ -0,0 +1,38 @@ +/** + * @deprecated + * @extends Observable + */ +export class WebsocketClient extends Observable { + /** + * @param {string} url + * @param {object} opts + * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType` + */ + constructor(url: string, { binaryType }?: { + binaryType?: "arraybuffer" | "blob" | null | undefined; + }); + url: string; + /** + * @type {WebSocket?} + */ + ws: WebSocket | null; + binaryType: "arraybuffer" | "blob" | null; + connected: boolean; + connecting: boolean; + unsuccessfulReconnects: number; + lastMessageReceived: number; + /** + * Whether to connect to other peers or not + * @type {boolean} + */ + shouldConnect: boolean; + _checkInterval: NodeJS.Timer; + /** + * @param {any} message + */ + send(message: any): void; + disconnect(): void; + connect(): void; +} +import { Observable } from './observable.js'; +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/lib0/websocket.d.ts.map b/nodejs/node_modules/lib0/websocket.d.ts.map new file mode 100644 index 00000000..0e3ab094 --- /dev/null +++ b/nodejs/node_modules/lib0/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["websocket.js"],"names":[],"mappings":"AAwFA;;;GAGG;AACH;IACE;;;;OAIG;IACH,iBAJW,MAAM;QAE+B,UAAU;OA2BzD;IAvBC,YAAc;IACd;;OAEG;IACH,IAFU,SAAS,QAEL;IACd,0CAAoC;IACpC,mBAAsB;IACtB,oBAAuB;IACvB,+BAA+B;IAC/B,4BAA4B;IAC5B;;;OAGG;IACH,eAFU,OAAO,CAEQ;IACzB,6BAM+B;IAIjC;;OAEG;IACH,cAFW,GAAG,QAMb;IAQD,mBAKC;IAED,gBAKC;CACF;2BA/I0B,iBAAiB"} \ No newline at end of file diff --git a/nodejs/node_modules/lib0/websocket.js b/nodejs/node_modules/lib0/websocket.js new file mode 100644 index 00000000..8ce1e8fe --- /dev/null +++ b/nodejs/node_modules/lib0/websocket.js @@ -0,0 +1,154 @@ +/* eslint-env browser */ + +/** + * Tiny websocket connection handler. + * + * Implements exponential backoff reconnects, ping/pong, and a nice event system using [lib0/observable]. + * + * @module websocket + */ + +import { Observable } from './observable.js' +import * as time from './time.js' +import * as math from './math.js' + +const reconnectTimeoutBase = 1200 +const maxReconnectTimeout = 2500 +// @todo - this should depend on awareness.outdatedTime +const messageReconnectTimeout = 30000 + +/** + * @param {WebsocketClient} wsclient + */ +const setupWS = (wsclient) => { + if (wsclient.shouldConnect && wsclient.ws === null) { + const websocket = new WebSocket(wsclient.url) + const binaryType = wsclient.binaryType + /** + * @type {any} + */ + let pingTimeout = null + if (binaryType) { + websocket.binaryType = binaryType + } + wsclient.ws = websocket + wsclient.connecting = true + wsclient.connected = false + websocket.onmessage = event => { + wsclient.lastMessageReceived = time.getUnixTime() + const data = event.data + const message = typeof data === 'string' ? JSON.parse(data) : data + if (message && message.type === 'pong') { + clearTimeout(pingTimeout) + pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2) + } + wsclient.emit('message', [message, wsclient]) + } + /** + * @param {any} error + */ + const onclose = error => { + if (wsclient.ws !== null) { + wsclient.ws = null + wsclient.connecting = false + if (wsclient.connected) { + wsclient.connected = false + wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient]) + } else { + wsclient.unsuccessfulReconnects++ + } + // Start with no reconnect timeout and increase timeout by + // log10(wsUnsuccessfulReconnects). + // The idea is to increase reconnect timeout slowly and have no reconnect + // timeout at the beginning (log(1) = 0) + setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient) + } + clearTimeout(pingTimeout) + } + const sendPing = () => { + if (wsclient.ws === websocket) { + wsclient.send({ + type: 'ping' + }) + } + } + websocket.onclose = () => onclose(null) + websocket.onerror = error => onclose(error) + websocket.onopen = () => { + wsclient.lastMessageReceived = time.getUnixTime() + wsclient.connecting = false + wsclient.connected = true + wsclient.unsuccessfulReconnects = 0 + wsclient.emit('connect', [{ type: 'connect' }, wsclient]) + // set ping + pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2) + } + } +} + +/** + * @deprecated + * @extends Observable + */ +export class WebsocketClient extends Observable { + /** + * @param {string} url + * @param {object} opts + * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType` + */ + constructor (url, { binaryType } = {}) { + super() + this.url = url + /** + * @type {WebSocket?} + */ + this.ws = null + this.binaryType = binaryType || null + this.connected = false + this.connecting = false + this.unsuccessfulReconnects = 0 + this.lastMessageReceived = 0 + /** + * Whether to connect to other peers or not + * @type {boolean} + */ + this.shouldConnect = true + this._checkInterval = setInterval(() => { + if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) { + // no message received in a long time - not even your own awareness + // updates (which are updated every 15 seconds) + /** @type {WebSocket} */ (this.ws).close() + } + }, messageReconnectTimeout / 2) + setupWS(this) + } + + /** + * @param {any} message + */ + send (message) { + if (this.ws) { + this.ws.send(JSON.stringify(message)) + } + } + + destroy () { + clearInterval(this._checkInterval) + this.disconnect() + super.destroy() + } + + disconnect () { + this.shouldConnect = false + if (this.ws !== null) { + this.ws.close() + } + } + + connect () { + this.shouldConnect = true + if (!this.connected && this.ws === null) { + setupWS(this) + } + } +} diff --git a/nodejs/node_modules/lodash.debounce/LICENSE b/nodejs/node_modules/lodash.debounce/LICENSE new file mode 100644 index 00000000..e0c69d56 --- /dev/null +++ b/nodejs/node_modules/lodash.debounce/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/nodejs/node_modules/lodash.debounce/README.md b/nodejs/node_modules/lodash.debounce/README.md new file mode 100644 index 00000000..52e638c7 --- /dev/null +++ b/nodejs/node_modules/lodash.debounce/README.md @@ -0,0 +1,18 @@ +# lodash.debounce v4.0.8 + +The [lodash](https://lodash.com/) method `_.debounce` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.debounce +``` + +In Node.js: +```js +var debounce = require('lodash.debounce'); +``` + +See the [documentation](https://lodash.com/docs#debounce) or [package source](https://github.com/lodash/lodash/blob/4.0.8-npm-packages/lodash.debounce) for more details. diff --git a/nodejs/node_modules/lodash.debounce/index.js b/nodejs/node_modules/lodash.debounce/index.js new file mode 100644 index 00000000..ac5707d7 --- /dev/null +++ b/nodejs/node_modules/lodash.debounce/index.js @@ -0,0 +1,377 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); +}; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = debounce; diff --git a/nodejs/node_modules/lodash.debounce/package.json b/nodejs/node_modules/lodash.debounce/package.json new file mode 100644 index 00000000..2974633c --- /dev/null +++ b/nodejs/node_modules/lodash.debounce/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.debounce", + "version": "4.0.8", + "description": "The lodash method `_.debounce` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, debounce", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/nodejs/node_modules/logform/.babelrc b/nodejs/node_modules/logform/.babelrc new file mode 100644 index 00000000..1320b9a3 --- /dev/null +++ b/nodejs/node_modules/logform/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["@babel/preset-env"] +} diff --git a/nodejs/node_modules/logform/.eslintrc b/nodejs/node_modules/logform/.eslintrc new file mode 100644 index 00000000..39607966 --- /dev/null +++ b/nodejs/node_modules/logform/.eslintrc @@ -0,0 +1,7 @@ +{ + "extends": "@dabh/eslint-config-populist", + "rules": { + "no-undefined": 0, + "strict": 0 + } +} diff --git a/nodejs/node_modules/logform/.gitattributes b/nodejs/node_modules/logform/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/nodejs/node_modules/logform/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/nodejs/node_modules/logform/CHANGELOG.md b/nodejs/node_modules/logform/CHANGELOG.md new file mode 100644 index 00000000..ef91bc4f --- /dev/null +++ b/nodejs/node_modules/logform/CHANGELOG.md @@ -0,0 +1,309 @@ +# CHANGELOG + +### [2.5.1](https://github.com/winstonjs/logform/compare/v2.5.0...v2.5.1) +**2023/02/07** +## Bugfix +The triple-beam types package has been promoted to a full dependency, by first-time contributor @carboneater (Thanks!) +in https://github.com/winstonjs/logform/pull/243 to fix https://github.com/winstonjs/logform/issues/242. + +### [2.5.0](https://github.com/winstonjs/logform/compare/v2.4.2...v2.5.0) +**2023/02/06** +## Most Important: +* Now incompatible with TypeScript < 4.4 due to [PR #240](https://github.com/winstonjs/logform/pull/240), as pointed out in [#244](https://github.com/winstonjs/logform/issues/244). + +## Improvements +All the improvements in this release are from first-time contributors - thanks for your contributions! +* Feature - optionally include Error.cause property by @davidnbooth in https://github.com/winstonjs/logform/pull/226 +* Add triple beam properties to types by @robinpokorny in https://github.com/winstonjs/logform/pull/194 +* TransformableInfo should support symbols as keys by @dancrumb in https://github.com/winstonjs/logform/pull/240 + +## Dependency updates by @dependabot +* Bump @babel/cli from 7.18.6 to 7.19.3 by @dependabot in https://github.com/winstonjs/logform/pull/214 +* Bump @babel/core from 7.18.6 to 7.20.12 by @dependabot in https://github.com/winstonjs/logform/pull/212 +and https://github.com/winstonjs/logform/pull/237 +* Bump @babel/preset-env from 7.18.6 to 7.20.2 by @dependabot in https://github.com/winstonjs/logform/pull/217 +and https://github.com/winstonjs/logform/pull/225 +* Bump eslint from 8.19.0 to 8.33.0 by @dependabot in https://github.com/winstonjs/logform/pull/215 +and https://github.com/winstonjs/logform/pull/241 +* Bump mocha from 10.0.0 to 10.2.0 by @dependabot in https://github.com/winstonjs/logform/pull/218 +and https://github.com/winstonjs/logform/pull/232 +* Bump safe-stable-stringify from 2.3.1 to 2.4.2 by @dependabot in https://github.com/winstonjs/logform/pull/206 +and https://github.com/winstonjs/logform/pull/235 + +### [2.4.2](https://github.com/winstonjs/logform/compare/v2.4.1...v2.4.2) +**2022/07/05** +## Bugfixes +This patch-level release includes a fix for a crash on attempt to uncolorize Symbol. +Thanks to @Alexsey for that first contribution in https://github.com/winstonjs/logform/pull/188. + +## Maintainability updates: +Line break styles were changed to be LF (instead of CRLF) more consistently so that linter warnings +aren't drowned out by notes about that. + +## Dependency updates by @dependabot +* @babel/cli from 7.17.10 to 7.18.6 in https://github.com/winstonjs/logform/pull/187 +* @babel/core from 7.18.5 to 7.18.6 in https://github.com/winstonjs/logform/pull/185 +* @babel/preset-env from 7.18.2 to 7.18.6 in https://github.com/winstonjs/logform/pull/184 +* eslint from 8.18.0 to 8.19.0 in https://github.com/winstonjs/logform/pull/186 + +### 2.4.1 +**2022/06/21** + +- [#178] Change TransformableInfo message prop to any: Loosening types to fix #172 (thanks, @gregbair!) +- [#149] Adopted issue templates for reporting issues, affects GitHub project management only (thanks, @maverick1872!) +- Updated dependencies, from dependabot + +### 2.4.0 +**2022/02/12** + +- Updated all dependencies +- [#135] Use CLI levels (not NPM levels) in `CliFormat` (this was likely a typo originally) +- [#134] Expose `safe-stable-stringify` 2.x options as parameters in `JsonOptions` + +### 2.3.2 +**2022/01/09** + +This update, which also used up version number 2.3.1, pinned the version of the `colors` dependency +due to vandalism by a developer of that package, as noted [here](https://www.bleepingcomputer.com/news/security/dev-corrupts-npm-libs-colors-and-faker-breaking-thousands-of-apps/). +[As discussed in the `winston` package](https://github.com/winstonjs/winston/issues/2011), all users should update to this (or a later version, should one exist) ASAP. + +### 2.3.0 +**2021/09/21** + +- Update dependencies +- Removing some superfluous semicolons & commas lint +- Avoid dynamic requires [#117] +- Replace JSON stringify library "fast-safe-stringify" by "safe-stable-stringify" [#98] +- More correctly format errors even if the “message” property is enumerable [#101] +- Fix errors and ms export for browsers [#106] + +### 2.2.0 +**2020/06/21** + +- [#90], [#91] Add option for using stable stringify when formatting as JSON. +- [#84] Add replacer for BigInt on JSON formatter. +- [#79] Timestamp format type definitions can accept functions. +- Update dependencies and fix most of the oustanding npm audit notices. + +### 2.1.2 +**2019/01/31** + +- [#74] Remove all internal symbols before invoking `util.inspect`. + - Related to [#31]. + +### 2.1.1 +**2019/01/29** + +- [#71] Bump logform to be consistent with winston. + - Fixes https://github.com/winstonjs/winston/issues/1584 + +### 2.1.0 +**2019/01/07** + +- [#59], [#68], [#69] Add error normalizing format. +- [#65] When MESSAGE symbol has a value and `{ all: true }` is set, colorize the entire serialized message. + +### 2.0.0 +**2018/12/23** + +- **BREAKING** [#57] Try better fix for [winston#1485]. See: + [New `splat` behavior`](#new-splat-behavior) below. +- [#54] Fix typo in `README.md` +- [#55] Strip info[LEVEL] in prettyPrint. Fixes [#31]. +- [#56] Document built-in formats. +- [#64] Add TypeScript definitions for all format options. + Relates to [#9] and [#48]. + +#### New `splat` behavior + +Previously `splat` would have added a `meta` property for any additional +`info[SPLAT]` beyond the expected number of tokens. + +**As of `logform@2.0.0`,** `format.splat` assumes additional splat paramters +(aka "metas") are objects and merges enumerable properties into the `info`. +e.g. + +``` js +const { format } = require('logform'); +const { splat } = format; +const { MESSAGE, LEVEL, SPLAT } = require('triple-beam'); + +console.log( + // Expects two tokens, but three splat parameters provided. + splat().transform({ + level: 'info', + message: 'Let us %s for %j', + [LEVEL]: 'info', + [MESSAGE]: 'Let us %s for %j', + [SPLAT]: ['objects', { label: 'sure' }, { thisIsMeta: 'wut' }] + }) +); + +// logform@1.x behavior: +// Added "meta" property. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// meta: { thisIsMeta: 'wut' }, +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } + +// logform@2.x behavior: +// Enumerable properties assigned into `info`. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// thisIsMeta: 'wut', +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } +``` + +The reason for this change is to be consistent with how `winston` itself +handles `meta` objects in its variable-arity conventions. + +**BE ADVISED** previous "metas" that _were not objects_ will very likely lead +to odd behavior. e.g. + +``` js +const { format } = require('logform'); +const { splat } = format; +const { MESSAGE, LEVEL, SPLAT } = require('triple-beam'); + +console.log( + // Expects two tokens, but three splat parameters provided. + splat().transform({ + level: 'info', + message: 'Let us %s for %j', + [LEVEL]: 'info', + [MESSAGE]: 'Let us %s for %j', + // !!NOTICE!! Additional parameters are a string and an Array + [SPLAT]: ['objects', { label: 'sure' }, 'lol', ['ok', 'why']] + }) +); + +// logform@1.x behavior: +// Added "meta" property. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// meta: ['lol', ['ok', 'why']], +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } + +// logform@2.x behavior: Enumerable properties assigned into `info`. +// **Strings and Arrays only have NUMERIC enumerable properties!** +// +// { '0': 'ok', +// '1': 'why', +// '2': 'l', +// level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } +``` + +### 1.10.0 +**2018/09/17** + +- [#52] Add types field in package.json. +- [#46], [#49] Changes for splat when there are no tokens present and no splat present. +- [#47], [#53] Expose transpiled code for Browser-only scenarios. + +### 1.9.1 +**2018/06/26** + +- [#39] Don't break when there are % placeholders but no values. +- [#42] Only set `meta` when non-zero additional `SPLAT` arguments are + provided. (Fixes [winstonjs/winston#1358]). + +### 1.9.0 +**2018/06/12** + +- [#38] Migrate functionality from winston Logger to splat format. +- [#37] Match expectations from `winston@2.x` for padLevels. Create a correct `Cli` format with initial state. (Fixes [#36]). + +### 1.8.0 +**2018/06/11** + +- [#35] Use `fast-safe-stringify` for perf and to support circular refs. +- [#34] Colorize level symbol. + +### 1.7.0 +**2018/05/24** + +- [#28] Use more es6-features across the board. +- [#30] Fix combine return value. +- [#29] Add metadata function to format namespace. + +### 1.6.0 +**2018/04/25** + +- [#25] Implement padLevels format. +- [#26] Update `dependencies` and add `node@10` to the travis build of the project. +- [#27] Refactor logform to use triple-beam. + +### 1.5.0 +**2018/04/22** + +- [#23], (@ChrisAlderson) Add ms format to support '+N ms' format. Fixes #20. +- [#24], (@aneilbaboo) Fix `webpack` warnings. +- Add `.travis.yml`. + +### 1.4.2 +**2018/04/19** + +- [#22], (@Jasu) Fix compilation on Babel 6. + +### 1.4.1 +**2018/04/06** + +- [#21], (@dabh) Add tsconfig.json. Fixes #19. + +### 1.4.0 +**2018/03/23** + +- [#14] @iamkirkbater Added Initial Metadata Support. +- Correct JSDoc for printf.js. Fixes #10. + +### 1.3.0 +**2018/03/16** + +- [#18] Expose browser.js for rollup and the like. Fixes [#5]. +- [#13] @dabh Use new version of colors. +- [#15] @dabh Add Typescript typings (ported from DefinitelyTyped). +- [#17], [#16] Fix error messages other typos. + +### 1.2.2 +**2017/12/05** + +- [#4], [#11] Fix timestamp and replace `date-fns` with `fecha` (with test cases) [`@ChrisAlderson`]. + +### 1.2.1 +**2017/10/01** + +- [#3] Strip `info.splat` in `format.simple` to avoid double inclusion. + +### 1.2.0 +**2017/09/30** + +- Transition from `info.raw` to `info[Symbol.for('message')]`. +- Finish `README.md` except for full list of all built-in formats. +- 100% coverage for everything except for `{ align, cli, padLevels }`. + +### 1.1.0 +**2017/09/29** + +- [#2] Add baseline expected formats that were previously exposed as options to `common.log` in `winston@2.x` and below. +- [#2] Introduce `format.combine` to remove inconsistency in behavior between `format(fn0)` and `format(fn0, ...moreFns)`. +- [#2] `README.md` now covers all of the basics for `logform`. + +### 1.0.0 +**2017/09/26** + +- Initial release. + +[winstonjs/winston#1358]: https://github.com/winstonjs/winston/issues/1358 diff --git a/nodejs/node_modules/logform/LICENSE b/nodejs/node_modules/logform/LICENSE new file mode 100644 index 00000000..c20a4041 --- /dev/null +++ b/nodejs/node_modules/logform/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Charlie Robbins & the Contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/logform/README.md b/nodejs/node_modules/logform/README.md new file mode 100644 index 00000000..f58fe8b8 --- /dev/null +++ b/nodejs/node_modules/logform/README.md @@ -0,0 +1,653 @@ +# logform + +A mutable object-based log format designed for chaining & objectMode streams. + +``` js +const { format } = require('logform'); + +const alignedWithColorsAndTime = format.combine( + format.colorize(), + format.timestamp(), + format.align(), + format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`) +); +``` + +- [`info` Objects](#info-objects) +- [Understanding formats](#understanding-formats) + - [Combining formats](#combining-formats) + - [Filtering `info` objects](#filtering-info-objects) +- [Formats](#formats) + - [Align](#align) + - [CLI](#cli) + - [Colorize](#colorize) + - [Combine](#combine) + - [Errors](#errors) + - [JSON](#json) + - [Label](#label) + - [Logstash](#logstash) + - [Metadata](#metadata) + - [PadLevels](#padlevels) + - [PrettyPrint](#prettyprint) + - [Printf](#printf) + - [Simple](#simple) + - [Splat](#splat) + - [Timestamp](#timestamp) + - [Uncolorize](#uncolorize) + +## `info` Objects + +The `info` parameter provided to a given format represents a single log +message. The object itself is mutable. Every `info` must have at least the +`level` and `message` properties: + +``` js +const info = { + level: 'info', // Level of the logging message + message: 'Hey! Log something?' // Descriptive message being logged. +} +``` + +Properties **besides level and message** are considered as "`meta`". i.e.: + +``` js +const { level, message, ...meta } = info; +``` + +Several of the formats in `logform` itself add additional properties: + +| Property | Format added by | Description | +| ----------- | --------------- | ----------- | +| `splat` | `splat()` | String interpolation splat for `%d %s`-style messages. | +| `timestamp` | `timestamp()` | timestamp the message was received. | +| `label` | `label()` | Custom label associated with each message. | +| `ms` | `ms()` | Number of milliseconds since the previous log message. | + +As a consumer you may add whatever properties you wish – _internal state is +maintained by `Symbol` properties:_ + +- `Symbol.for('level')` _**(READ-ONLY)**:_ equal to `level` property. + **Is treated as immutable by all code.** +- `Symbol.for('message'):` complete string message set by "finalizing formats": + - `json` + - `logstash` + - `printf` + - `prettyPrint` + - `simple` +- `Symbol.for('splat')`: additional string interpolation arguments. _Used + exclusively by `splat()` format._ + +These Symbols are stored in another package: `triple-beam` so that all +consumers of `logform` can have the same Symbol reference. i.e.: + +``` js +const { LEVEL, MESSAGE, SPLAT } = require('triple-beam'); + +console.log(LEVEL === Symbol.for('level')); +// true + +console.log(MESSAGE === Symbol.for('message')); +// true + +console.log(SPLAT === Symbol.for('splat')); +// true +``` + +## Understanding formats + +Formats are prototypal objects (i.e. class instances) that define a single method: `transform(info, opts)` and return the mutated `info` + +- `info`: an object representing the log message. +- `opts`: setting specific to the current instance of the format. + +They are expected to return one of two things: + +- **An `info` Object** representing the modified `info` argument. Object references need not be preserved if immutability is preferred. All current built-in formats consider `info` mutable, but [immutablejs] is being considered for future releases. +- **A falsey value** indicating that the `info` argument should be ignored by the caller. (See: [Filtering `info` Objects](#filtering-info-objects)) below. + +`logform.format` is designed to be as simple as possible. To define a new format simple pass it a `transform(info, opts)` function to get a new `Format`. + +The named `Format` returned can be used to create as many copies of the given `Format` as desired: + +``` js +const { format } = require('logform'); + +const volume = format((info, opts) => { + if (opts.yell) { + info.message = info.message.toUpperCase(); + } else if (opts.whisper) { + info.message = info.message.toLowerCase(); + } + + return info; +}); + +// `volume` is now a function that returns instances of the format. +const scream = volume({ yell: true }); +console.dir(scream.transform({ + level: 'info', + message: `sorry for making you YELL in your head!` +}, scream.options)); +// { +// level: 'info' +// message: 'SORRY FOR MAKING YOU YELL IN YOUR HEAD!' +// } + +// `volume` can be used multiple times to create different formats. +const whisper = volume({ whisper: true }); +console.dir(whisper.transform({ + level: 'info', + message: `WHY ARE THEY MAKING US YELL SO MUCH!` +}), whisper.options); +// { +// level: 'info' +// message: 'why are they making us yell so much!' +// } +``` + +### Combining formats + +Any number of formats may be combined into a single format using `format.combine`. Since `format.combine` takes no `opts`, as a convenience it returns pre-created instance of the combined format. + +``` js +const { format } = require('logform'); +const { combine, timestamp, label } = format; + +const labelTimestamp = combine( + label({ label: 'right meow!' }), + timestamp() +); + +const info = labelTimestamp.transform({ + level: 'info', + message: 'What time is the testing at?' +}); + +console.dir(info); +// { level: 'info', +// message: 'What time is the testing at?', +// label: 'right meow!', +// timestamp: '2017-09-30T03:57:26.875Z' } +``` + +### Filtering `info` Objects + +If you wish to filter out a given `info` Object completely then simply return a falsey value. + +``` js +const ignorePrivate = format((info, opts) => { + if (info.private) { return false; } + return info; +}); + +console.dir(ignorePrivate.transform({ + level: 'error', + message: 'Public error to share' +})); +// { level: 'error', message: 'Public error to share' } + +console.dir(ignorePrivate.transform({ + level: 'error', + private: true, + message: 'This is super secret - hide it.' +})); +// false +``` + +Use of `format.combine` will respect any falsey values return and stop evaluation of later formats in the series. For example: + +``` js +const { format } = require('logform'); +const { combine, timestamp, label } = format; + +const willNeverThrow = format.combine( + format(info => { return false })(), // Ignores everything + format(info => { throw new Error('Never reached') })() +); + +console.dir(willNeverThrow.transform({ + level: 'info', + message: 'wow such testing' +})) +``` + +## Formats + +### Align + +The `align` format adds a `\t` delimiter before the message to align it in the same place. + +```js +const { format } = require('logform'); + +const alignFormat = format.align(); + +const info = alignFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', message: '\tmy message' } +``` + +This was previously exposed as `{ align: true }` in `winston < 3.0.0`. + +### CLI + +The `cli` format is a combination of the `colorize` and the `padLevels` formats. It turns a log `info` object into the same format previously available in `winston.cli()` in `winston < 3.0.0`. + +```js +const { format } = require('logform'); +const LEVEL = Symbol.for('level'); + +const cliFormat = format.cli({ colors: { info: 'blue' }}); + +const info = cliFormat.transform({ + [LEVEL]: 'info', + level: 'info', + message: 'my message' +}, { all: true }); + +console.log(info); +// { level: '\u001b[34minfo\u001b[39m', +// message: '\u001b[34m my message\u001b[39m', +// [Symbol(level)]: 'info', +// [Symbol(message)]: +// '\u001b[34minfo\u001b[39m:\u001b[34m my message\u001b[39m' } +``` + +### Colorize + +The `colorize` format adds different colors depending on the log level to the message and/or level. +It accepts the following options: + +* **level**: If set to `true` the color will be applied to the `level`. +* **all**: If set to `true` the color will be applied to the `message` and `level`. +* **message**: If set to `true` the color will be applied to the `message`. +* **colors**: An object containing the colors for the log levels. For example: `{ info: 'blue', error: 'red' }` + +```js +const { format } = require('logform'); +const LEVEL = Symbol.for('level'); + +const colorizeFormat = format.colorize({ colors: { info: 'blue' }}); + +const info = colorizeFormat.transform({ + [LEVEL]: 'info', + level: 'info', + message: 'my message' +}, { all: true }); + +console.log(info); +// { level: '\u001b[34minfo\u001b[39m', +// message: '\u001b[34mmy message\u001b[39m', +// [Symbol(level)]: 'info' } +``` + +This was previously exposed as `{ colorize: true }` to transports in `winston < 3.0.0`. + +### Combine + +The `combine` Format allows to combine multiple formats: + +```js +const { format } = require('logform'); +const { combine, timestamp, json } = format; + +const jsonWithTimestamp = combine( + timestamp(), + json() +); + +const info = jsonWithTimestamp.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// timestamp: '2018-10-02T15:03:14.230Z', +// [Symbol(message)]: +// '{"level":"info","message":"my message","timestamp":"2018-10-02T15:03:14.230Z"}' } +``` + +### Errors + +The `errors` format allows you to pass in an instance of a JavaScript `Error` +directly to the logger. It allows you to specify whether not to include the +stack-trace. + +```js +const { format } = require('logform'); +const { errors } = format; + +const errorsFormat = errors({ stack: true }) + +const info = errorsFormat.transform(new Error('Oh no!')); + +console.log(info); +// Error: Oh no! +// at repl:1:13 +// at ContextifyScript.Script.runInThisContext (vm.js:50:33) +// at REPLServer.defaultEval (repl.js:240:29) +// at bound (domain.js:301:14) +// at REPLServer.runBound [as eval] (domain.js:314:12) +// at REPLServer.onLine (repl.js:468:10) +// at emitOne (events.js:121:20) +// at REPLServer.emit (events.js:211:7) +// at REPLServer.Interface._onLine (readline.js:282:10) +// at REPLServer.Interface._line (readline.js:631:8) +``` + +It will also handle `{ message }` properties as `Error` instances: + +```js +const { format } = require('logform'); +const { errors } = format; + +const errorsFormat = errors({ stack: true }) + +const info = errorsFormat.transform({ + message: new Error('Oh no!') +}); + +console.log(info); +// Error: Oh no! +// at repl:1:13 +// at ContextifyScript.Script.runInThisContext (vm.js:50:33) +// at REPLServer.defaultEval (repl.js:240:29) +// at bound (domain.js:301:14) +// at REPLServer.runBound [as eval] (domain.js:314:12) +// at REPLServer.onLine (repl.js:468:10) +// at emitOne (events.js:121:20) +// at REPLServer.emit (events.js:211:7) +// at REPLServer.Interface._onLine (readline.js:282:10) +// at REPLServer.Interface._line (readline.js:631:8) +``` + +### JSON + +The `json` format uses `safe-stable-stringify` to finalize the message. +It accepts the following options: + +* **replacer**: A function that influences how the `info` is stringified. +* **space**: The number of white space used to format the json. + +```js +const { format } = require('logform'); + +const jsonFormat = format.json(); + +const info = jsonFormat.transform({ + level: 'info', + message: 'my message', +}); +console.log(info); +// { level: 'info', +// message: 'my message', +// [Symbol(message)]: '{"level":"info","message":"my message"}' } +``` + +This was previously exposed as `{ json: true }` to transports in `winston < 3.0.0`. + +### Label + +The `label` format adds the specified `label` before the message or adds it to the `info` object. +It accepts the following options: + +* **label**: A label to be added before the message. +* **message**: If set to `true` the `label` will be added to `info.message`. If set to `false` the `label` will be added as `info.label`. + +```js +const { format } = require('logform'); + +const labelFormat = format.label(); + +const info = labelFormat.transform({ + level: 'info', + message: 'my message' +}, { label: 'my label', message: true }); + +console.log(info); +// { level: 'info', message: '[my label] my message' } +``` + +This was previously exposed as `{ label: 'my label' }` to transports in `winston < 3.0.0`. + +### Logstash + +The `logstash` Format turns a log `info` object into pure JSON with the appropriate logstash options. + +```js +const { format } = require('logform'); +const { logstash, combine, timestamp } = format; + +const logstashFormat = combine( + timestamp(), + logstash() +); + +const info = logstashFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// [Symbol(message)]: +// '{"@message":"my message","@timestamp":"2018-10-02T11:04:52.915Z","@fields":{"level":"info"}}' } +``` + +This was previously exposed as `{ logstash: true }` to transports in `winston < 3.0.0`. + +### Metadata + +The `metadata` format adds a metadata object to collect extraneous data, similar to the metadata object in winston 2.x. +It accepts the following options: + +* **key**: The name of the key used for the metadata object. Defaults to `metadata`. +* **fillExcept**: An array of keys that should not be added to the metadata object. +* **fillWith**: An array of keys that will be added to the metadata object. + +```js +const { format } = require('logform'); + +const metadataFormat = format.metadata(); + +const info = metadataFormat.transform({ + level: 'info', + message: 'my message', + meta: 42 +}); + +console.log(info); +// { level: 'info', message: 'my message', metadata: { meta: 42 } } +``` + +### PadLevels + +The `padLevels` format pads levels to be the same length. + +```js +const { format } = require('logform'); +const LEVEL = Symbol.for('level'); + +const padLevelsFormat = format.padLevels(); + +const info = padLevelsFormat.transform({ + [LEVEL]: 'info', + message: 'my message' +}); + +console.log(info); +// { message: ' my message', [Symbol(level)]: 'info' } +``` + +This was previously exposed as `{ padLevels: true }` to transports in `winston < 3.0.0`. + +### PrettyPrint + +The `prettyPrint` format finalizes the message using `util.inspect`. +It accepts the following options: + +* **depth**: A `number` that specifies the maximum depth of the `info` object being stringified by `util.inspect`. Defaults to `2`. +* **colorize**: Colorizes the message if set to `true`. Defaults to `false`. + +The `prettyPrint` format should not be used in production because it may impact performance negatively and block the event loop. + +> **NOTE:** the `LEVEL`, `MESSAGE`, and `SPLAT` symbols are stripped from the +> output message _by design._ + +This was previously exposed as `{ prettyPrint: true }` to transports in `winston < 3.0.0`. + +```js +const { format } = require('logform'); + +const prettyPrintFormat = format.prettyPrint(); + +const info = prettyPrintFormat.transform({ + [LEVEL]: 'info', + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// [Symbol(level)]: 'info', +// [Symbol(message)]: '{ level: \'info\', message: \'my message\' }' } +``` + +### Printf + +The `printf` format allows to create a custom logging format: + +```js +const { format } = require('logform'); + +const myFormat = format.printf((info) => { + return `${info.level} ${info.message}`; +}) + +const info = myFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// [Symbol(message)]: 'info my message' } +``` + +### Simple + +The `simple` format finalizes the `info` object using the format: `level: message stringifiedRest`. +```js +const { format } = require('logform'); +const MESSAGE = Symbol.for('message'); + +const simpleFormat = format.simple(); + +const info = simpleFormat.transform({ + level: 'info', + message: 'my message', + number: 123 +}); +console.log(info[MESSAGE]); +// info: my message {number:123} +``` + +### Splat + +The `splat` format transforms the message by using `util.format` to complete any `info.message` provided it has string interpolation tokens. + +```js +const { format } = require('logform'); + +const splatFormat = format.splat(); + +const info = splatFormat.transform({ + level: 'info', + message: 'my message %s', + splat: ['test'] +}); + +console.log(info); +// { level: 'info', message: 'my message test', splat: [ 'test' ] } +``` + +Any additional splat parameters beyond those needed for the `%` tokens +(aka "metas") are assumed to be objects. Their enumerable properties are +merged into the `info`. + +```js +const { format } = require('logform'); + +const splatFormat = format.splat(); + +const info = splatFormat.transform({ + level: 'info', + message: 'my message %s', + splat: ['test', { thisIsMeta: true }] +}); + +console.log(info); +// { level: 'info', +// message: 'my message test', +// thisIsMeta: true, +// splat: [ 'test' ] } +``` + +This was previously exposed implicitly in `winston < 3.0.0`. + +### Timestamp + +The `timestamp` format adds a timestamp to the info. +It accepts the following options: + +* **format**: Either the format as a string accepted by the [fecha](https://github.com/taylorhakes/fecha) module or a function that returns a formatted date. If no format is provided `new Date().toISOString()` will be used. +* **alias**: The name of an alias for the timestamp property, that will be added to the `info` object. + +```js +const { format } = require('logform'); + +const timestampFormat = format.timestamp(); + +const info = timestampFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// timestamp: '2018-10-02T11:47:02.682Z' } +``` + +It was previously available in `winston < 3.0.0` as `{ timestamp: true }` and `{ timestamp: function:String }`. + + +### Uncolorize + +The `uncolorize` format strips colors from `info` objects. +It accepts the following options: + +* **level**: Disables the uncolorize format for `info.level` if set to `false`. +* **message**: Disables the uncolorize format for `info.message` if set to `false`. +* **raw**: Disables the uncolorize format for `info[MESSAGE]` if set to `false`. + +This was previously exposed as `{ stripColors: true }` to transports in `winston < 3.0.0`. + +## Tests + +Tests are written with `mocha`, `assume`, and `nyc`. They can be run with `npm`: + +``` +npm test +``` + +##### LICENSE: MIT +##### AUTHOR: [Charlie Robbins](https://github.com/indexzero) diff --git a/nodejs/node_modules/logform/align.js b/nodejs/node_modules/logform/align.js new file mode 100644 index 00000000..358514b0 --- /dev/null +++ b/nodejs/node_modules/logform/align.js @@ -0,0 +1,14 @@ +'use strict'; + +const format = require('./format'); + +/* + * function align (info) + * Returns a new instance of the align Format which adds a `\t` + * delimiter before the message to properly align it in the same place. + * It was previously { align: true } in winston < 3.0.0 + */ +module.exports = format(info => { + info.message = `\t${info.message}`; + return info; +}); diff --git a/nodejs/node_modules/logform/browser.js b/nodejs/node_modules/logform/browser.js new file mode 100644 index 00000000..843044b1 --- /dev/null +++ b/nodejs/node_modules/logform/browser.js @@ -0,0 +1,38 @@ +'use strict'; + +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ +const format = exports.format = require('././format'); + +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ +exports.levels = require('././levels'); + +// +// Setup all transports as eager-loaded exports +// so that they are static for the bundlers. +// +Object.defineProperty(format, 'align', { value: require('./align') }); +Object.defineProperty(format, 'cli', { value: require('./cli') }); +Object.defineProperty(format, 'colorize', { value: require('./colorize') }); +Object.defineProperty(format, 'combine', { value: require('./combine') }); +Object.defineProperty(format, 'errors', { value: require('./errors') }); +Object.defineProperty(format, 'json', { value: require('./json') }); +Object.defineProperty(format, 'label', { value: require('./label') }); +Object.defineProperty(format, 'logstash', { value: require('./logstash') }); +Object.defineProperty(format, 'metadata', { value: require('./metadata') }); +Object.defineProperty(format, 'ms', { value: require('./ms') }); +Object.defineProperty(format, 'padLevels', { value: require('./pad-levels') }); +Object.defineProperty(format, 'prettyPrint', { value: require('./pretty-print') }); +Object.defineProperty(format, 'printf', { value: require('./printf') }); +Object.defineProperty(format, 'simple', { value: require('./simple') }); +Object.defineProperty(format, 'splat', { value: require('./splat') }); +Object.defineProperty(format, 'timestamp', { value: require('./timestamp') }); +Object.defineProperty(format, 'uncolorize', { value: require('./uncolorize') }); diff --git a/nodejs/node_modules/logform/cli.js b/nodejs/node_modules/logform/cli.js new file mode 100644 index 00000000..4fc74b77 --- /dev/null +++ b/nodejs/node_modules/logform/cli.js @@ -0,0 +1,52 @@ +'use strict'; + +const { Colorizer } = require('./colorize'); +const { Padder } = require('./pad-levels'); +const { configs, MESSAGE } = require('triple-beam'); + + +/** + * Cli format class that handles initial state for a a separate + * Colorizer and Padder instance. + */ +class CliFormat { + constructor(opts = {}) { + if (!opts.levels) { + opts.levels = configs.cli.levels; + } + + this.colorizer = new Colorizer(opts); + this.padder = new Padder(opts); + this.options = opts; + } + + /* + * function transform (info, opts) + * Attempts to both: + * 1. Pad the { level } + * 2. Colorize the { level, message } + * of the given `logform` info object depending on the `opts`. + */ + transform(info, opts) { + this.colorizer.transform( + this.padder.transform(info, opts), + opts + ); + + info[MESSAGE] = `${info.level}:${info.message}`; + return info; + } +} + +/* + * function cli (opts) + * Returns a new instance of the CLI format that turns a log + * `info` object into the same format previously available + * in `winston.cli()` in `winston < 3.0.0`. + */ +module.exports = opts => new CliFormat(opts); + +// +// Attach the CliFormat for registration purposes +// +module.exports.Format = CliFormat; diff --git a/nodejs/node_modules/logform/colorize.js b/nodejs/node_modules/logform/colorize.js new file mode 100644 index 00000000..0186c6ec --- /dev/null +++ b/nodejs/node_modules/logform/colorize.js @@ -0,0 +1,122 @@ +'use strict'; + +const colors = require('@colors/colors/safe'); +const { LEVEL, MESSAGE } = require('triple-beam'); + +// +// Fix colors not appearing in non-tty environments +// +colors.enabled = true; + +/** + * @property {RegExp} hasSpace + * Simple regex to check for presence of spaces. + */ +const hasSpace = /\s+/; + +/* + * Colorizer format. Wraps the `level` and/or `message` properties + * of the `info` objects with ANSI color codes based on a few options. + */ +class Colorizer { + constructor(opts = {}) { + if (opts.colors) { + this.addColors(opts.colors); + } + + this.options = opts; + } + + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + static addColors(clrs) { + const nextColors = Object.keys(clrs).reduce((acc, level) => { + acc[level] = hasSpace.test(clrs[level]) + ? clrs[level].split(hasSpace) + : clrs[level]; + + return acc; + }, {}); + + Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors); + return Colorizer.allColors; + } + + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + addColors(clrs) { + return Colorizer.addColors(clrs); + } + + /* + * function colorize (lookup, level, message) + * Performs multi-step colorization using @colors/colors/safe + */ + colorize(lookup, level, message) { + if (typeof message === 'undefined') { + message = level; + } + + // + // If the color for the level is just a string + // then attempt to colorize the message with it. + // + if (!Array.isArray(Colorizer.allColors[lookup])) { + return colors[Colorizer.allColors[lookup]](message); + } + + // + // If it is an Array then iterate over that Array, applying + // the colors function for each item. + // + for (let i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) { + message = colors[Colorizer.allColors[lookup][i]](message); + } + + return message; + } + + /* + * function transform (info, opts) + * Attempts to colorize the { level, message } of the given + * `logform` info object. + */ + transform(info, opts) { + if (opts.all && typeof info[MESSAGE] === 'string') { + info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); + } + + if (opts.level || opts.all || !opts.message) { + info.level = this.colorize(info[LEVEL], info.level); + } + + if (opts.all || opts.message) { + info.message = this.colorize(info[LEVEL], info.level, info.message); + } + + return info; + } +} + +/* + * function colorize (info) + * Returns a new instance of the colorize Format that applies + * level colors to `info` objects. This was previously exposed + * as { colorize: true } to transports in `winston < 3.0.0`. + */ +module.exports = opts => new Colorizer(opts); + +// +// Attach the Colorizer for registration purposes +// +module.exports.Colorizer + = module.exports.Format + = Colorizer; diff --git a/nodejs/node_modules/logform/combine.js b/nodejs/node_modules/logform/combine.js new file mode 100644 index 00000000..975482c9 --- /dev/null +++ b/nodejs/node_modules/logform/combine.js @@ -0,0 +1,66 @@ +'use strict'; + +const format = require('./format'); + +/* + * function cascade(formats) + * Returns a function that invokes the `._format` function in-order + * for the specified set of `formats`. In this manner we say that Formats + * are "pipe-like", but not a pure pumpify implementation. Since there is no back + * pressure we can remove all of the "readable" plumbing in Node streams. + */ +function cascade(formats) { + if (!formats.every(isValidFormat)) { + return; + } + + return info => { + let obj = info; + for (let i = 0; i < formats.length; i++) { + obj = formats[i].transform(obj, formats[i].options); + if (!obj) { + return false; + } + } + + return obj; + }; +} + +/* + * function isValidFormat(format) + * If the format does not define a `transform` function throw an error + * with more detailed usage. + */ +function isValidFormat(fmt) { + if (typeof fmt.transform !== 'function') { + throw new Error([ + 'No transform function found on format. Did you create a format instance?', + 'const myFormat = format(formatFn);', + 'const instance = myFormat();' + ].join('\n')); + } + + return true; +} + +/* + * function combine (info) + * Returns a new instance of the combine Format which combines the specified + * formats into a new format. This is similar to a pipe-chain in transform streams. + * We choose to combine the prototypes this way because there is no back pressure in + * an in-memory transform chain. + */ +module.exports = (...formats) => { + const combinedFormat = format(cascade(formats)); + const instance = combinedFormat(); + instance.Format = combinedFormat.Format; + return instance; +}; + +// +// Export the cascade method for use in cli and other +// combined formats that should not be assumed to be +// singletons. +// +module.exports.cascade = cascade; diff --git a/nodejs/node_modules/logform/dist/align.js b/nodejs/node_modules/logform/dist/align.js new file mode 100644 index 00000000..b1ef3c09 --- /dev/null +++ b/nodejs/node_modules/logform/dist/align.js @@ -0,0 +1,14 @@ +'use strict'; + +var format = require('./format'); + +/* + * function align (info) + * Returns a new instance of the align Format which adds a `\t` + * delimiter before the message to properly align it in the same place. + * It was previously { align: true } in winston < 3.0.0 + */ +module.exports = format(function (info) { + info.message = "\t".concat(info.message); + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/browser.js b/nodejs/node_modules/logform/dist/browser.js new file mode 100644 index 00000000..064b19b4 --- /dev/null +++ b/nodejs/node_modules/logform/dist/browser.js @@ -0,0 +1,72 @@ +'use strict'; + +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ +var format = exports.format = require('././format'); + +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ +exports.levels = require('././levels'); + +// +// Setup all transports as eager-loaded exports +// so that they are static for the bundlers. +// +Object.defineProperty(format, 'align', { + value: require('./align') +}); +Object.defineProperty(format, 'cli', { + value: require('./cli') +}); +Object.defineProperty(format, 'colorize', { + value: require('./colorize') +}); +Object.defineProperty(format, 'combine', { + value: require('./combine') +}); +Object.defineProperty(format, 'errors', { + value: require('./errors') +}); +Object.defineProperty(format, 'json', { + value: require('./json') +}); +Object.defineProperty(format, 'label', { + value: require('./label') +}); +Object.defineProperty(format, 'logstash', { + value: require('./logstash') +}); +Object.defineProperty(format, 'metadata', { + value: require('./metadata') +}); +Object.defineProperty(format, 'ms', { + value: require('./ms') +}); +Object.defineProperty(format, 'padLevels', { + value: require('./pad-levels') +}); +Object.defineProperty(format, 'prettyPrint', { + value: require('./pretty-print') +}); +Object.defineProperty(format, 'printf', { + value: require('./printf') +}); +Object.defineProperty(format, 'simple', { + value: require('./simple') +}); +Object.defineProperty(format, 'splat', { + value: require('./splat') +}); +Object.defineProperty(format, 'timestamp', { + value: require('./timestamp') +}); +Object.defineProperty(format, 'uncolorize', { + value: require('./uncolorize') +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/cli.js b/nodejs/node_modules/logform/dist/cli.js new file mode 100644 index 00000000..d852e36d --- /dev/null +++ b/nodejs/node_modules/logform/dist/cli.js @@ -0,0 +1,63 @@ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('./colorize'), + Colorizer = _require.Colorizer; +var _require2 = require('./pad-levels'), + Padder = _require2.Padder; +var _require3 = require('triple-beam'), + configs = _require3.configs, + MESSAGE = _require3.MESSAGE; + +/** + * Cli format class that handles initial state for a a separate + * Colorizer and Padder instance. + */ +var CliFormat = /*#__PURE__*/function () { + function CliFormat() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, CliFormat); + if (!opts.levels) { + opts.levels = configs.cli.levels; + } + this.colorizer = new Colorizer(opts); + this.padder = new Padder(opts); + this.options = opts; + } + + /* + * function transform (info, opts) + * Attempts to both: + * 1. Pad the { level } + * 2. Colorize the { level, message } + * of the given `logform` info object depending on the `opts`. + */ + _createClass(CliFormat, [{ + key: "transform", + value: function transform(info, opts) { + this.colorizer.transform(this.padder.transform(info, opts), opts); + info[MESSAGE] = "".concat(info.level, ":").concat(info.message); + return info; + } + }]); + return CliFormat; +}(); +/* + * function cli (opts) + * Returns a new instance of the CLI format that turns a log + * `info` object into the same format previously available + * in `winston.cli()` in `winston < 3.0.0`. + */ +module.exports = function (opts) { + return new CliFormat(opts); +}; + +// +// Attach the CliFormat for registration purposes +// +module.exports.Format = CliFormat; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/colorize.js b/nodejs/node_modules/logform/dist/colorize.js new file mode 100644 index 00000000..527e664d --- /dev/null +++ b/nodejs/node_modules/logform/dist/colorize.js @@ -0,0 +1,132 @@ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var colors = require('@colors/colors/safe'); +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; + +// +// Fix colors not appearing in non-tty environments +// +colors.enabled = true; + +/** + * @property {RegExp} hasSpace + * Simple regex to check for presence of spaces. + */ +var hasSpace = /\s+/; + +/* + * Colorizer format. Wraps the `level` and/or `message` properties + * of the `info` objects with ANSI color codes based on a few options. + */ +var Colorizer = /*#__PURE__*/function () { + function Colorizer() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, Colorizer); + if (opts.colors) { + this.addColors(opts.colors); + } + this.options = opts; + } + + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + _createClass(Colorizer, [{ + key: "addColors", + value: + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + function addColors(clrs) { + return Colorizer.addColors(clrs); + } + + /* + * function colorize (lookup, level, message) + * Performs multi-step colorization using @colors/colors/safe + */ + }, { + key: "colorize", + value: function colorize(lookup, level, message) { + if (typeof message === 'undefined') { + message = level; + } + + // + // If the color for the level is just a string + // then attempt to colorize the message with it. + // + if (!Array.isArray(Colorizer.allColors[lookup])) { + return colors[Colorizer.allColors[lookup]](message); + } + + // + // If it is an Array then iterate over that Array, applying + // the colors function for each item. + // + for (var i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) { + message = colors[Colorizer.allColors[lookup][i]](message); + } + return message; + } + + /* + * function transform (info, opts) + * Attempts to colorize the { level, message } of the given + * `logform` info object. + */ + }, { + key: "transform", + value: function transform(info, opts) { + if (opts.all && typeof info[MESSAGE] === 'string') { + info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); + } + if (opts.level || opts.all || !opts.message) { + info.level = this.colorize(info[LEVEL], info.level); + } + if (opts.all || opts.message) { + info.message = this.colorize(info[LEVEL], info.level, info.message); + } + return info; + } + }], [{ + key: "addColors", + value: function addColors(clrs) { + var nextColors = Object.keys(clrs).reduce(function (acc, level) { + acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level]; + return acc; + }, {}); + Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors); + return Colorizer.allColors; + } + }]); + return Colorizer; +}(); +/* + * function colorize (info) + * Returns a new instance of the colorize Format that applies + * level colors to `info` objects. This was previously exposed + * as { colorize: true } to transports in `winston < 3.0.0`. + */ +module.exports = function (opts) { + return new Colorizer(opts); +}; + +// +// Attach the Colorizer for registration purposes +// +module.exports.Colorizer = module.exports.Format = Colorizer; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/combine.js b/nodejs/node_modules/logform/dist/combine.js new file mode 100644 index 00000000..d513b60f --- /dev/null +++ b/nodejs/node_modules/logform/dist/combine.js @@ -0,0 +1,62 @@ +'use strict'; + +var format = require('./format'); + +/* + * function cascade(formats) + * Returns a function that invokes the `._format` function in-order + * for the specified set of `formats`. In this manner we say that Formats + * are "pipe-like", but not a pure pumpify implementation. Since there is no back + * pressure we can remove all of the "readable" plumbing in Node streams. + */ +function cascade(formats) { + if (!formats.every(isValidFormat)) { + return; + } + return function (info) { + var obj = info; + for (var i = 0; i < formats.length; i++) { + obj = formats[i].transform(obj, formats[i].options); + if (!obj) { + return false; + } + } + return obj; + }; +} + +/* + * function isValidFormat(format) + * If the format does not define a `transform` function throw an error + * with more detailed usage. + */ +function isValidFormat(fmt) { + if (typeof fmt.transform !== 'function') { + throw new Error(['No transform function found on format. Did you create a format instance?', 'const myFormat = format(formatFn);', 'const instance = myFormat();'].join('\n')); + } + return true; +} + +/* + * function combine (info) + * Returns a new instance of the combine Format which combines the specified + * formats into a new format. This is similar to a pipe-chain in transform streams. + * We choose to combine the prototypes this way because there is no back pressure in + * an in-memory transform chain. + */ +module.exports = function () { + for (var _len = arguments.length, formats = new Array(_len), _key = 0; _key < _len; _key++) { + formats[_key] = arguments[_key]; + } + var combinedFormat = format(cascade(formats)); + var instance = combinedFormat(); + instance.Format = combinedFormat.Format; + return instance; +}; + +// +// Export the cascade method for use in cli and other +// combined formats that should not be assumed to be +// singletons. +// +module.exports.cascade = cascade; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/errors.js b/nodejs/node_modules/logform/dist/errors.js new file mode 100644 index 00000000..d86106f9 --- /dev/null +++ b/nodejs/node_modules/logform/dist/errors.js @@ -0,0 +1,45 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var format = require('./format'); +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; + +/* + * function errors (info) + * If the `message` property of the `info` object is an instance of `Error`, + * replace the `Error` object its own `message` property. + * + * Optionally, the Error's `stack` and/or `cause` properties can also be appended to the `info` object. + */ +module.exports = format(function (einfo, _ref) { + var stack = _ref.stack, + cause = _ref.cause; + if (einfo instanceof Error) { + var _Object$assign; + var info = Object.assign({}, einfo, (_Object$assign = { + level: einfo.level + }, _defineProperty(_Object$assign, LEVEL, einfo[LEVEL] || einfo.level), _defineProperty(_Object$assign, "message", einfo.message), _defineProperty(_Object$assign, MESSAGE, einfo[MESSAGE] || einfo.message), _Object$assign)); + if (stack) info.stack = einfo.stack; + if (cause) info.cause = einfo.cause; + return info; + } + if (!(einfo.message instanceof Error)) return einfo; + + // Assign all enumerable properties and the + // message property from the error provided. + var err = einfo.message; + Object.assign(einfo, err); + einfo.message = err.message; + einfo[MESSAGE] = err.message; + + // Assign the stack and/or cause if requested. + if (stack) einfo.stack = err.stack; + if (cause) einfo.cause = err.cause; + return einfo; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/format.js b/nodejs/node_modules/logform/dist/format.js new file mode 100644 index 00000000..73ee4c65 --- /dev/null +++ b/nodejs/node_modules/logform/dist/format.js @@ -0,0 +1,71 @@ +'use strict'; + +/* + * Displays a helpful message and the source of + * the format when it is invalid. + */ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { return typeof fn === "function"; } } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var InvalidFormatError = /*#__PURE__*/function (_Error) { + _inherits(InvalidFormatError, _Error); + var _super = _createSuper(InvalidFormatError); + function InvalidFormatError(formatFn) { + var _this; + _classCallCheck(this, InvalidFormatError); + _this = _super.call(this, "Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ".concat(formatFn.toString().split('\n')[0], "\n")); + Error.captureStackTrace(_assertThisInitialized(_this), InvalidFormatError); + return _this; + } + return _createClass(InvalidFormatError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); +/* + * function format (formatFn) + * Returns a create function for the `formatFn`. + */ +module.exports = function (formatFn) { + if (formatFn.length > 2) { + throw new InvalidFormatError(formatFn); + } + + /* + * function Format (options) + * Base prototype which calls a `_format` + * function and pushes the result. + */ + function Format() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + this.options = options; + } + Format.prototype.transform = formatFn; + + // + // Create a function which returns new instances of + // FormatWrap for simple syntax like: + // + // require('winston').formats.json(); + // + function createFormatWrap(opts) { + return new Format(opts); + } + + // + // Expose the FormatWrap through the create function + // for testability. + // + createFormatWrap.Format = Format; + return createFormatWrap; +}; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/index.js b/nodejs/node_modules/logform/dist/index.js new file mode 100644 index 00000000..9d5087f3 --- /dev/null +++ b/nodejs/node_modules/logform/dist/index.js @@ -0,0 +1,86 @@ +'use strict'; + +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ +var format = exports.format = require('./format'); + +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ +exports.levels = require('./levels'); + +/* + * @api private + * method {function} exposeFormat + * Exposes a sub-format on the main format object + * as a lazy-loaded getter. + */ +function exposeFormat(name, requireFormat) { + Object.defineProperty(format, name, { + get: function get() { + return requireFormat(); + }, + configurable: true + }); +} + +// +// Setup all transports as lazy-loaded getters. +// +exposeFormat('align', function () { + return require('./align'); +}); +exposeFormat('errors', function () { + return require('./errors'); +}); +exposeFormat('cli', function () { + return require('./cli'); +}); +exposeFormat('combine', function () { + return require('./combine'); +}); +exposeFormat('colorize', function () { + return require('./colorize'); +}); +exposeFormat('json', function () { + return require('./json'); +}); +exposeFormat('label', function () { + return require('./label'); +}); +exposeFormat('logstash', function () { + return require('./logstash'); +}); +exposeFormat('metadata', function () { + return require('./metadata'); +}); +exposeFormat('ms', function () { + return require('./ms'); +}); +exposeFormat('padLevels', function () { + return require('./pad-levels'); +}); +exposeFormat('prettyPrint', function () { + return require('./pretty-print'); +}); +exposeFormat('printf', function () { + return require('./printf'); +}); +exposeFormat('simple', function () { + return require('./simple'); +}); +exposeFormat('splat', function () { + return require('./splat'); +}); +exposeFormat('timestamp', function () { + return require('./timestamp'); +}); +exposeFormat('uncolorize', function () { + return require('./uncolorize'); +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/json.js b/nodejs/node_modules/logform/dist/json.js new file mode 100644 index 00000000..f1e91bbe --- /dev/null +++ b/nodejs/node_modules/logform/dist/json.js @@ -0,0 +1,30 @@ +'use strict'; + +var format = require('./format'); +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +var stringify = require('safe-stable-stringify'); + +/* + * function replacer (key, value) + * Handles proper stringification of Buffer and bigint output. + */ +function replacer(key, value) { + // safe-stable-stringify does support BigInt, however, it doesn't wrap the value in quotes. + // Leading to a loss in fidelity if the resulting string is parsed. + // It would also be a breaking change for logform. + if (typeof value === 'bigint') return value.toString(); + return value; +} + +/* + * function json (info) + * Returns a new instance of the JSON format that turns a log `info` + * object into pure JSON. This was previously exposed as { json: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format(function (info, opts) { + var jsonStringify = stringify.configure(opts); + info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space); + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/label.js b/nodejs/node_modules/logform/dist/label.js new file mode 100644 index 00000000..8786b002 --- /dev/null +++ b/nodejs/node_modules/logform/dist/label.js @@ -0,0 +1,18 @@ +'use strict'; + +var format = require('./format'); + +/* + * function label (info) + * Returns a new instance of the label Format which adds the specified + * `opts.label` before the message. This was previously exposed as + * { label: 'my label' } to transports in `winston < 3.0.0`. + */ +module.exports = format(function (info, opts) { + if (opts.message) { + info.message = "[".concat(opts.label, "] ").concat(info.message); + return info; + } + info.label = opts.label; + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/levels.js b/nodejs/node_modules/logform/dist/levels.js new file mode 100644 index 00000000..6d83cf11 --- /dev/null +++ b/nodejs/node_modules/logform/dist/levels.js @@ -0,0 +1,13 @@ +'use strict'; + +var _require = require('./colorize'), + Colorizer = _require.Colorizer; + +/* + * Simple method to register colors with a simpler require + * path within the module. + */ +module.exports = function (config) { + Colorizer.addColors(config.colors || config); + return config; +}; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/logstash.js b/nodejs/node_modules/logform/dist/logstash.js new file mode 100644 index 00000000..37b211fd --- /dev/null +++ b/nodejs/node_modules/logform/dist/logstash.js @@ -0,0 +1,28 @@ +'use strict'; + +var format = require('./format'); +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +var jsonStringify = require('safe-stable-stringify'); + +/* + * function logstash (info) + * Returns a new instance of the LogStash Format that turns a + * log `info` object into pure JSON with the appropriate logstash + * options. This was previously exposed as { logstash: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format(function (info) { + var logstash = {}; + if (info.message) { + logstash['@message'] = info.message; + delete info.message; + } + if (info.timestamp) { + logstash['@timestamp'] = info.timestamp; + delete info.timestamp; + } + logstash['@fields'] = info; + info[MESSAGE] = jsonStringify(logstash); + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/metadata.js b/nodejs/node_modules/logform/dist/metadata.js new file mode 100644 index 00000000..f6652182 --- /dev/null +++ b/nodejs/node_modules/logform/dist/metadata.js @@ -0,0 +1,56 @@ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var format = require('./format'); +function fillExcept(info, fillExceptKeys, metadataKey) { + var savedKeys = fillExceptKeys.reduce(function (acc, key) { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + var metadata = Object.keys(info).reduce(function (acc, key) { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + Object.assign(info, savedKeys, _defineProperty({}, metadataKey, metadata)); + return info; +} +function fillWith(info, fillWithKeys, metadataKey) { + info[metadataKey] = fillWithKeys.reduce(function (acc, key) { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + return info; +} + +/** + * Adds in a "metadata" object to collect extraneous data, similar to the metadata + * object in winston 2.x. + */ +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var metadataKey = 'metadata'; + if (opts.key) { + metadataKey = opts.key; + } + var fillExceptKeys = []; + if (!opts.fillExcept && !opts.fillWith) { + fillExceptKeys.push('level'); + fillExceptKeys.push('message'); + } + if (opts.fillExcept) { + fillExceptKeys = opts.fillExcept; + } + if (fillExceptKeys.length > 0) { + return fillExcept(info, fillExceptKeys, metadataKey); + } + if (opts.fillWith) { + return fillWith(info, opts.fillWith, metadataKey); + } + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/ms.js b/nodejs/node_modules/logform/dist/ms.js new file mode 100644 index 00000000..4d808890 --- /dev/null +++ b/nodejs/node_modules/logform/dist/ms.js @@ -0,0 +1,18 @@ +'use strict'; + +var _this = void 0; +var format = require('./format'); +var ms = require('ms'); + +/* + * function ms (info) + * Returns an `info` with a `ms` property. The `ms` property holds the Value + * of the time difference between two calls in milliseconds. + */ +module.exports = format(function (info) { + var curr = +new Date(); + _this.diff = curr - (_this.prevTime || curr); + _this.prevTime = curr; + info.ms = "+".concat(ms(_this.diff)); + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/pad-levels.js b/nodejs/node_modules/logform/dist/pad-levels.js new file mode 100644 index 00000000..adc1180e --- /dev/null +++ b/nodejs/node_modules/logform/dist/pad-levels.js @@ -0,0 +1,111 @@ +/* eslint no-unused-vars: 0 */ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('triple-beam'), + configs = _require.configs, + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; +var Padder = /*#__PURE__*/function () { + function Padder() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + levels: configs.npm.levels + }; + _classCallCheck(this, Padder); + this.paddings = Padder.paddingForLevels(opts.levels, opts.filler); + this.options = opts; + } + + /** + * Returns the maximum length of keys in the specified `levels` Object. + * @param {Object} levels Set of all levels to calculate longest level against. + * @returns {Number} Maximum length of the longest level string. + */ + _createClass(Padder, [{ + key: "transform", + value: + /** + * Prepends the padding onto the `message` based on the `LEVEL` of + * the `info`. This is based on the behavior of `winston@2` which also + * prepended the level onto the message. + * + * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 + * + * @param {Info} info Logform info object + * @param {Object} opts Options passed along to this instance. + * @returns {Info} Modified logform info object. + */ + function transform(info, opts) { + info.message = "".concat(this.paddings[info[LEVEL]]).concat(info.message); + if (info[MESSAGE]) { + info[MESSAGE] = "".concat(this.paddings[info[LEVEL]]).concat(info[MESSAGE]); + } + return info; + } + }], [{ + key: "getLongestLevel", + value: function getLongestLevel(levels) { + var lvls = Object.keys(levels).map(function (level) { + return level.length; + }); + return Math.max.apply(Math, _toConsumableArray(lvls)); + } + + /** + * Returns the padding for the specified `level` assuming that the + * maximum length of all levels it's associated with is `maxLength`. + * @param {String} level Level to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @param {Number} maxLength Length of the longest level + * @returns {String} Padding string for the `level` + */ + }, { + key: "paddingForLevel", + value: function paddingForLevel(level, filler, maxLength) { + var targetLen = maxLength + 1 - level.length; + var rep = Math.floor(targetLen / filler.length); + var padding = "".concat(filler).concat(filler.repeat(rep)); + return padding.slice(0, targetLen); + } + + /** + * Returns an object with the string paddings for the given `levels` + * using the specified `filler`. + * @param {Object} levels Set of all levels to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @returns {Object} Mapping of level to desired padding. + */ + }, { + key: "paddingForLevels", + value: function paddingForLevels(levels) { + var filler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' '; + var maxLength = Padder.getLongestLevel(levels); + return Object.keys(levels).reduce(function (acc, level) { + acc[level] = Padder.paddingForLevel(level, filler, maxLength); + return acc; + }, {}); + } + }]); + return Padder; +}(); +/* + * function padLevels (info) + * Returns a new instance of the padLevels Format which pads + * levels to be the same length. This was previously exposed as + * { padLevels: true } to transports in `winston < 3.0.0`. + */ +module.exports = function (opts) { + return new Padder(opts); +}; +module.exports.Padder = module.exports.Format = Padder; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/pretty-print.js b/nodejs/node_modules/logform/dist/pretty-print.js new file mode 100644 index 00000000..3161e6dc --- /dev/null +++ b/nodejs/node_modules/logform/dist/pretty-print.js @@ -0,0 +1,32 @@ +'use strict'; + +var inspect = require('util').inspect; +var format = require('./format'); +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE, + SPLAT = _require.SPLAT; + +/* + * function prettyPrint (info) + * Returns a new instance of the prettyPrint Format that "prettyPrint" + * serializes `info` objects. This was previously exposed as + * { prettyPrint: true } to transports in `winston < 3.0.0`. + */ +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + // + // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they + // are internal, we remove them before util.inspect so they + // are not printed. + // + var stripped = Object.assign({}, info); + + // Remark (indexzero): update this technique in April 2019 + // when node@6 is EOL + delete stripped[LEVEL]; + delete stripped[MESSAGE]; + delete stripped[SPLAT]; + info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/printf.js b/nodejs/node_modules/logform/dist/printf.js new file mode 100644 index 00000000..e03801c8 --- /dev/null +++ b/nodejs/node_modules/logform/dist/printf.js @@ -0,0 +1,34 @@ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +var Printf = /*#__PURE__*/function () { + function Printf(templateFn) { + _classCallCheck(this, Printf); + this.template = templateFn; + } + _createClass(Printf, [{ + key: "transform", + value: function transform(info) { + info[MESSAGE] = this.template(info); + return info; + } + }]); + return Printf; +}(); +/* + * function printf (templateFn) + * Returns a new instance of the printf Format that creates an + * intermediate prototype to store the template string-based formatter + * function. + */ +module.exports = function (opts) { + return new Printf(opts); +}; +module.exports.Printf = module.exports.Format = Printf; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/simple.js b/nodejs/node_modules/logform/dist/simple.js new file mode 100644 index 00000000..48514fbb --- /dev/null +++ b/nodejs/node_modules/logform/dist/simple.js @@ -0,0 +1,32 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +var format = require('./format'); +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +var jsonStringify = require('safe-stable-stringify'); + +/* + * function simple (info) + * Returns a new instance of the simple format TransformStream + * which writes a simple representation of logs. + * + * const { level, message, splat, ...rest } = info; + * + * ${level}: ${message} if rest is empty + * ${level}: ${message} ${JSON.stringify(rest)} otherwise + */ +module.exports = format(function (info) { + var stringifiedRest = jsonStringify(Object.assign({}, info, { + level: undefined, + message: undefined, + splat: undefined + })); + var padding = info.padding && info.padding[info.level] || ''; + if (stringifiedRest !== '{}') { + info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message, " ").concat(stringifiedRest); + } else { + info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message); + } + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/splat.js b/nodejs/node_modules/logform/dist/splat.js new file mode 100644 index 00000000..a89277e2 --- /dev/null +++ b/nodejs/node_modules/logform/dist/splat.js @@ -0,0 +1,144 @@ +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var util = require('util'); +var _require = require('triple-beam'), + SPLAT = _require.SPLAT; + +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ +var formatRegExp = /%[scdjifoO%]/g; + +/** + * Captures the number of escaped % signs in a format string (i.e. %s strings). + * @type {RegExp} + */ +var escapedPercent = /%%/g; +var Splatter = /*#__PURE__*/function () { + function Splatter(opts) { + _classCallCheck(this, Splatter); + this.options = opts; + } + + /** + * Check to see if tokens <= splat.length, assign { splat, meta } into the + * `info` accordingly, and write to this instance. + * + * @param {Info} info Logform info message. + * @param {String[]} tokens Set of string interpolation tokens. + * @returns {Info} Modified info message + * @private + */ + _createClass(Splatter, [{ + key: "_splat", + value: function _splat(info, tokens) { + var msg = info.message; + var splat = info[SPLAT] || info.splat || []; + var percents = msg.match(escapedPercent); + var escapes = percents && percents.length || 0; + + // The expected splat is the number of tokens minus the number of escapes + // e.g. + // - { expectedSplat: 3 } '%d %s %j' + // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j' + // + // Any "meta" will be arugments in addition to the expected splat size + // regardless of type. e.g. + // + // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true }); + // would result in splat of four (4), but only three (3) are expected. Therefore: + // + // extraSplat = 3 - 4 = -1 + // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1); + // splat = [100, 'wow', { such: 'js' }] + var expectedSplat = tokens.length - escapes; + var extraSplat = expectedSplat - splat.length; + var metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; + + // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + var metalen = metas.length; + if (metalen) { + for (var i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + info.message = util.format.apply(util, [msg].concat(_toConsumableArray(splat))); + return info; + } + + /** + * Transforms the `info` message by using `util.format` to complete + * any `info.message` provided it has string interpolation tokens. + * If no tokens exist then `info` is immutable. + * + * @param {Info} info Logform info message. + * @param {Object} opts Options for this instance. + * @returns {Info} Modified info message + */ + }, { + key: "transform", + value: function transform(info) { + var msg = info.message; + var splat = info[SPLAT] || info.splat; + + // No need to process anything if splat is undefined + if (!splat || !splat.length) { + return info; + } + + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + var tokens = msg && msg.match && msg.match(formatRegExp); + + // This condition will take care of inputs with info[SPLAT] + // but no tokens present + if (!tokens && (splat || splat.length)) { + var metas = splat.length > 1 ? splat.splice(0) : splat; + + // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + var metalen = metas.length; + if (metalen) { + for (var i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + return info; + } + if (tokens) { + return this._splat(info, tokens); + } + return info; + } + }]); + return Splatter; +}(); +/* + * function splat (info) + * Returns a new instance of the splat format TransformStream + * which performs string interpolation from `info` objects. This was + * previously exposed implicitly in `winston < 3.0.0`. + */ +module.exports = function (opts) { + return new Splatter(opts); +}; \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/timestamp.js b/nodejs/node_modules/logform/dist/timestamp.js new file mode 100644 index 00000000..247b377c --- /dev/null +++ b/nodejs/node_modules/logform/dist/timestamp.js @@ -0,0 +1,26 @@ +'use strict'; + +var fecha = require('fecha'); +var format = require('./format'); + +/* + * function timestamp (info) + * Returns a new instance of the timestamp Format which adds a timestamp + * to the info. It was previously available in winston < 3.0.0 as: + * + * - { timestamp: true } // `new Date.toISOString()` + * - { timestamp: function:String } // Value returned by `timestamp()` + */ +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (opts.format) { + info.timestamp = typeof opts.format === 'function' ? opts.format() : fecha.format(new Date(), opts.format); + } + if (!info.timestamp) { + info.timestamp = new Date().toISOString(); + } + if (opts.alias) { + info[opts.alias] = info.timestamp; + } + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/dist/uncolorize.js b/nodejs/node_modules/logform/dist/uncolorize.js new file mode 100644 index 00000000..9b2625b4 --- /dev/null +++ b/nodejs/node_modules/logform/dist/uncolorize.js @@ -0,0 +1,25 @@ +'use strict'; + +var colors = require('@colors/colors/safe'); +var format = require('./format'); +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +/* + * function uncolorize (info) + * Returns a new instance of the uncolorize Format that strips colors + * from `info` objects. This was previously exposed as { stripColors: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format(function (info, opts) { + if (opts.level !== false) { + info.level = colors.strip(info.level); + } + if (opts.message !== false) { + info.message = colors.strip(String(info.message)); + } + if (opts.raw !== false && info[MESSAGE]) { + info[MESSAGE] = colors.strip(String(info[MESSAGE])); + } + return info; +}); \ No newline at end of file diff --git a/nodejs/node_modules/logform/errors.js b/nodejs/node_modules/logform/errors.js new file mode 100644 index 00000000..b1d163b1 --- /dev/null +++ b/nodejs/node_modules/logform/errors.js @@ -0,0 +1,41 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +const format = require('./format'); +const { LEVEL, MESSAGE } = require('triple-beam'); + +/* + * function errors (info) + * If the `message` property of the `info` object is an instance of `Error`, + * replace the `Error` object its own `message` property. + * + * Optionally, the Error's `stack` and/or `cause` properties can also be appended to the `info` object. + */ +module.exports = format((einfo, { stack, cause }) => { + if (einfo instanceof Error) { + const info = Object.assign({}, einfo, { + level: einfo.level, + [LEVEL]: einfo[LEVEL] || einfo.level, + message: einfo.message, + [MESSAGE]: einfo[MESSAGE] || einfo.message + }); + + if (stack) info.stack = einfo.stack; + if (cause) info.cause = einfo.cause; + return info; + } + + if (!(einfo.message instanceof Error)) return einfo; + + // Assign all enumerable properties and the + // message property from the error provided. + const err = einfo.message; + Object.assign(einfo, err); + einfo.message = err.message; + einfo[MESSAGE] = err.message; + + // Assign the stack and/or cause if requested. + if (stack) einfo.stack = err.stack; + if (cause) einfo.cause = err.cause; + return einfo; +}); diff --git a/nodejs/node_modules/logform/examples/combine.js b/nodejs/node_modules/logform/examples/combine.js new file mode 100644 index 00000000..71a70bec --- /dev/null +++ b/nodejs/node_modules/logform/examples/combine.js @@ -0,0 +1,14 @@ +const { format } = require('../'); +const { combine, timestamp, label } = format; + +const labelTimestamp = combine( + label({ label: 'right meow!' }), + timestamp() +); + +const info = labelTimestamp.transform({ + level: 'info', + message: 'What time is the testing at?' +}); + +console.dir(info); diff --git a/nodejs/node_modules/logform/examples/filter.js b/nodejs/node_modules/logform/examples/filter.js new file mode 100644 index 00000000..89a16788 --- /dev/null +++ b/nodejs/node_modules/logform/examples/filter.js @@ -0,0 +1,30 @@ +/* eslint no-unused-vars: 0 */ + +const { format } = require('../'); +const { combine, timestamp, label } = format; + +const ignorePrivate = format((info, opts) => { + if (info.private) { return false; } + return info; +})(); + +console.dir(ignorePrivate.transform({ + level: 'error', + message: 'Public error to share' +})); + +console.dir(ignorePrivate.transform({ + level: 'error', + private: true, + message: 'This is super secret - hide it.' +})); + +const willNeverThrow = format.combine( + format(info => { return false; })(), // Ignores everything + format(info => { throw new Error('Never reached'); })() +); + +console.dir(willNeverThrow.transform({ + level: 'info', + message: 'wow such testing' +})); diff --git a/nodejs/node_modules/logform/examples/invalid.js b/nodejs/node_modules/logform/examples/invalid.js new file mode 100644 index 00000000..bd2b4087 --- /dev/null +++ b/nodejs/node_modules/logform/examples/invalid.js @@ -0,0 +1,6 @@ +/* eslint no-unused-vars: 0 */ +const { format } = require('../'); + +const invalid = format(function invalid(just, too, many, args) { + return just; +}); diff --git a/nodejs/node_modules/logform/examples/metadata.js b/nodejs/node_modules/logform/examples/metadata.js new file mode 100644 index 00000000..4846f74f --- /dev/null +++ b/nodejs/node_modules/logform/examples/metadata.js @@ -0,0 +1,78 @@ +const { format } = require('../'); +const { combine, json, metadata, timestamp } = format; + +// Default Functionality (no options passed) +const defaultFormatter = combine( + timestamp(), + metadata(), + json() +); + +const defaultMessage = defaultFormatter.transform({ + level: 'info', + message: 'This should be a message.', + application: 'Microsoft Office', + store: 'Big Box Store', + purchaseAmount: '9.99' +}); + +console.dir(defaultMessage); + + +// Fill all keys into metadata except those provided +const formattedLogger = combine( + timestamp(), + metadata({ fillExcept: ['message', 'level', 'timestamp'] }), + json() +); + +const fillExceptMessage = formattedLogger.transform({ + level: 'info', + message: 'This should have attached metadata', + category: 'movies', + subCategory: 'action' +}); + +console.dir(fillExceptMessage); + + +// Fill only the keys provided into the object, and also give it a different key +const customMetadataLogger = combine( + timestamp(), + metadata({ fillWith: ['publisher', 'author', 'book'], key: 'bookInfo' }), + json() +); + +const fillWithMessage = customMetadataLogger.transform({ + level: 'debug', + message: 'This message should be outside of the bookInfo object', + publisher: 'Lorem Press', + author: 'Albert Einstein', + book: '4D Chess for Dummies', + label: 'myCustomLabel' +}); + +console.dir(fillWithMessage); + +// Demonstrates Metadata 'chaining' to combine multiple datapoints. +const chainedMetadata = combine( + timestamp(), + metadata({ fillWith: ['publisher', 'author', 'book'], key: 'bookInfo' }), + metadata({ fillWith: ['purchasePrice', 'purchaseDate', 'transactionId'], key: 'transactionInfo' }), + metadata({ fillExcept: ['level', 'message', 'label', 'timestamp'] }), + json() +); + +const chainedMessage = chainedMetadata.transform({ + level: 'debug', + message: 'This message should be outside of the bookInfo object', + publisher: 'Lorem Press', + author: 'Albert Einstein', + book: '4D Chess for Dummies', + label: 'myCustomLabel', + purchasePrice: '9.99', + purchaseDate: '2.10.2018', + transactionId: '123ABC' +}); + +console.dir(chainedMessage); diff --git a/nodejs/node_modules/logform/examples/padLevels.js b/nodejs/node_modules/logform/examples/padLevels.js new file mode 100644 index 00000000..568964da --- /dev/null +++ b/nodejs/node_modules/logform/examples/padLevels.js @@ -0,0 +1,39 @@ +const { format } = require('../'); +const { combine, padLevels, simple } = format; + +const { MESSAGE } = require('triple-beam'); + +const paddedFormat = combine( + padLevels({ + // Uncomment for a custom filler for the padding, defaults to ' '. + // filler: 'foo', + // Levels has to be defined, same as `winston.createLoggers({ levels })`. + levels: { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 + } + }), + simple() +); + +const info = paddedFormat.transform({ + level: 'info', + message: 'This is an info level message.' +}); +const error = paddedFormat.transform({ + level: 'error', + message: 'This is an error level message.' +}); +const verbose = paddedFormat.transform({ + level: 'verbose', + message: 'This is a verbose level message.' +}); + +console.dir(info[MESSAGE]); +console.dir(error[MESSAGE]); +console.dir(verbose[MESSAGE]); diff --git a/nodejs/node_modules/logform/examples/volume.js b/nodejs/node_modules/logform/examples/volume.js new file mode 100644 index 00000000..cce36f60 --- /dev/null +++ b/nodejs/node_modules/logform/examples/volume.js @@ -0,0 +1,25 @@ +const { format } = require('../'); + +const volume = format((info, opts) => { + if (opts.yell) { + info.message = info.message.toUpperCase(); + } else if (opts.whisper) { + info.message = info.message.toLowerCase(); + } + + return info; +}); + +// `volume` is now a function that returns instances of the format. +const scream = volume({ yell: true }); +console.dir(scream.transform({ + level: 'info', + message: `sorry for making you YELL in your head!` +}, scream.options)); + +// `volume` can be used multiple times to create different formats. +const whisper = volume({ whisper: true }); +console.dir(whisper.transform({ + level: 'info', + message: `WHY ARE THEY MAKING US YELL SO MUCH!` +}, whisper.options)); diff --git a/nodejs/node_modules/logform/format.js b/nodejs/node_modules/logform/format.js new file mode 100644 index 00000000..c2294b6c --- /dev/null +++ b/nodejs/node_modules/logform/format.js @@ -0,0 +1,52 @@ +'use strict'; + +/* + * Displays a helpful message and the source of + * the format when it is invalid. + */ +class InvalidFormatError extends Error { + constructor(formatFn) { + super(`Format functions must be synchronous taking a two arguments: (info, opts) +Found: ${formatFn.toString().split('\n')[0]}\n`); + + Error.captureStackTrace(this, InvalidFormatError); + } +} + +/* + * function format (formatFn) + * Returns a create function for the `formatFn`. + */ +module.exports = formatFn => { + if (formatFn.length > 2) { + throw new InvalidFormatError(formatFn); + } + + /* + * function Format (options) + * Base prototype which calls a `_format` + * function and pushes the result. + */ + function Format(options = {}) { + this.options = options; + } + + Format.prototype.transform = formatFn; + + // + // Create a function which returns new instances of + // FormatWrap for simple syntax like: + // + // require('winston').formats.json(); + // + function createFormatWrap(opts) { + return new Format(opts); + } + + // + // Expose the FormatWrap through the create function + // for testability. + // + createFormatWrap.Format = Format; + return createFormatWrap; +}; diff --git a/nodejs/node_modules/logform/index.d.ts b/nodejs/node_modules/logform/index.d.ts new file mode 100644 index 00000000..9331ccbe --- /dev/null +++ b/nodejs/node_modules/logform/index.d.ts @@ -0,0 +1,201 @@ +// Type definitions for logform 2.x +// Project: https://github.com/winstonjs/logform +// Definitions by: DABH +// Definitions: https://github.com/winstonjs/logform +// TypeScript Version: 2.2 +import {LEVEL, MESSAGE, SPLAT} from 'triple-beam' + +export interface TransformableInfo { + level: string; + message: any; + [LEVEL]?: string; + [MESSAGE]?: any; + [SPLAT]?: any; + [key: string | symbol]: any; +} + +export type TransformFunction = (info: TransformableInfo, opts?: any) => TransformableInfo | boolean; +export type Colors = { [key: string]: string | string[] }; // tslint:disable-line interface-over-type-literal +export type FormatWrap = (opts?: any) => Format; + +export class Format { + constructor(opts?: object); + + options?: object; + transform: TransformFunction; +} + +export class Colorizer extends Format { + constructor(opts?: object); + + createColorize: (opts?: object) => Colorizer; + addColors: (colors: Colors) => Colors; + colorize: (level: string, message: string) => string; +} + +export function format(transform: TransformFunction): FormatWrap; + +export function levels(config: object): object; + +export namespace format { + function align(): Format; + function cli(opts?: CliOptions): Format; + function colorize(opts?: ColorizeOptions): Colorizer; + function combine(...formats: Format[]): Format; + function errors(opts?: object): Format; + function json(opts?: JsonOptions): Format; + function label(opts?: LabelOptions): Format; + function logstash(): Format; + function metadata(opts?: MetadataOptions): Format; + function ms(): Format; + function padLevels(opts?: PadLevelsOptions): Format; + function prettyPrint(opts?: PrettyPrintOptions): Format; + function printf(templateFunction: (info: TransformableInfo) => string): Format; + function simple(): Format; + function splat(): Format; + function timestamp(opts?: TimestampOptions): Format; + function uncolorize(opts?: UncolorizeOptions): Format; +} + +export interface CliOptions extends ColorizeOptions, PadLevelsOptions { } + +export interface ColorizeOptions { + /** + * If set to `true` the color will be applied to the `level`. + */ + level?: boolean; + /** + * If set to `true` the color will be applied to the `message` and `level`. + */ + all?: boolean; + /** + * If set to `true` the color will be applied to the `message`. + */ + message?: boolean; + /** + * An object containing the colors for the log levels. For example: `{ info: 'blue', error: 'red' }`. + */ + colors?: Record; +} + +export interface JsonOptions { + /** + * A function that influences how the `info` is stringified. + */ + replacer?: (this: any, key: string, value: any) => any; + /** + * The number of white space used to format the json. + */ + space?: number; + + // The following options come from safe-stable-stringify + // https://github.com/BridgeAR/safe-stable-stringify/blob/main/index.d.ts + + /** + * If `true`, bigint values are converted to a number. Otherwise, they are ignored. + * This option is ignored by default as Logform stringifies BigInt in the default replacer. + * @default true + */ + bigint?: boolean, + /** + * Defines the value for circular references. + * Set to `undefined`, circular properties are not serialized (array entries are replaced with null). + * Set to `Error`, to throw on circular references. + * @default "[Circular]" + */ + circularValue?: string | null | TypeErrorConstructor | ErrorConstructor, + /** + * If `true`, guarantee a deterministic key order instead of relying on the insertion order. + * @default true + */ + deterministic?: boolean, + /** + * Maximum number of entries to serialize per object (at least one). + * The serialized output contains information about how many entries have not been serialized. + * Ignored properties are counted as well (e.g., properties with symbol values). + * Using the array replacer overrules this option. + * @default Infinity + */ + maximumBreadth?: number, + /** + * Maximum number of object nesting levels (at least 1) that will be serialized. + * Objects at the maximum level are serialized as `"[Object]"` and arrays as `"[Array]"`. + * @default Infinity + */ + maximumDepth?: number, +} + +export interface LabelOptions { + /** + * A label to be added before the message. + */ + label?: string; + /** + * If set to `true` the `label` will be added to `info.message`. If set to `false` the `label` + * will be added as `info.label`. + */ + message?: boolean; +} + +export interface MetadataOptions { + /** + * The name of the key used for the metadata object. Defaults to `metadata`. + */ + key?: string; + /** + * An array of keys that should not be added to the metadata object. + */ + fillExcept?: string[]; + /** + * An array of keys that will be added to the metadata object. + */ + fillWith?: string[]; +} + +export interface PadLevelsOptions { + /** + * Log levels. Defaults to `configs.npm.levels` from [triple-beam](https://github.com/winstonjs/triple-beam) + * module. + */ + levels?: Record; +} + +export interface PrettyPrintOptions { + /** + * A `number` that specifies the maximum depth of the `info` object being stringified by + * `util.inspect`. Defaults to `2`. + */ + depth?: number; + /** + * Colorizes the message if set to `true`. Defaults to `false`. + */ + colorize?: boolean; +} + +export interface TimestampOptions { + /** + * Either the format as a string accepted by the [fecha](https://github.com/taylorhakes/fecha) + * module or a function that returns a formatted date. If no format is provided `new + * Date().toISOString()` will be used. + */ + format?: string | (() => string); + /** + * The name of an alias for the timestamp property, that will be added to the `info` object. + */ + alias?: string; +} + +export interface UncolorizeOptions { + /** + * Disables the uncolorize format for `info.level` if set to `false`. + */ + level?: boolean; + /** + * Disables the uncolorize format for `info.message` if set to `false`. + */ + message?: boolean; + /** + * Disables the uncolorize format for `info[MESSAGE]` if set to `false`. + */ + raw?: boolean; +} diff --git a/nodejs/node_modules/logform/index.js b/nodejs/node_modules/logform/index.js new file mode 100644 index 00000000..0edfc050 --- /dev/null +++ b/nodejs/node_modules/logform/index.js @@ -0,0 +1,52 @@ +'use strict'; + +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ +const format = exports.format = require('./format'); + +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ +exports.levels = require('./levels'); + +/* + * @api private + * method {function} exposeFormat + * Exposes a sub-format on the main format object + * as a lazy-loaded getter. + */ +function exposeFormat(name, requireFormat) { + Object.defineProperty(format, name, { + get() { + return requireFormat(); + }, + configurable: true + }); +} + +// +// Setup all transports as lazy-loaded getters. +// +exposeFormat('align', function () { return require('./align'); }); +exposeFormat('errors', function () { return require('./errors'); }); +exposeFormat('cli', function () { return require('./cli'); }); +exposeFormat('combine', function () { return require('./combine'); }); +exposeFormat('colorize', function () { return require('./colorize'); }); +exposeFormat('json', function () { return require('./json'); }); +exposeFormat('label', function () { return require('./label'); }); +exposeFormat('logstash', function () { return require('./logstash'); }); +exposeFormat('metadata', function () { return require('./metadata'); }); +exposeFormat('ms', function () { return require('./ms'); }); +exposeFormat('padLevels', function () { return require('./pad-levels'); }); +exposeFormat('prettyPrint', function () { return require('./pretty-print'); }); +exposeFormat('printf', function () { return require('./printf'); }); +exposeFormat('simple', function () { return require('./simple'); }); +exposeFormat('splat', function () { return require('./splat'); }); +exposeFormat('timestamp', function () { return require('./timestamp'); }); +exposeFormat('uncolorize', function () { return require('./uncolorize'); }); diff --git a/nodejs/node_modules/logform/json.js b/nodejs/node_modules/logform/json.js new file mode 100644 index 00000000..fb91c976 --- /dev/null +++ b/nodejs/node_modules/logform/json.js @@ -0,0 +1,30 @@ +'use strict'; + +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); +const stringify = require('safe-stable-stringify'); + +/* + * function replacer (key, value) + * Handles proper stringification of Buffer and bigint output. + */ +function replacer(key, value) { + // safe-stable-stringify does support BigInt, however, it doesn't wrap the value in quotes. + // Leading to a loss in fidelity if the resulting string is parsed. + // It would also be a breaking change for logform. + if (typeof value === 'bigint') + return value.toString(); + return value; +} + +/* + * function json (info) + * Returns a new instance of the JSON format that turns a log `info` + * object into pure JSON. This was previously exposed as { json: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts) => { + const jsonStringify = stringify.configure(opts); + info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space); + return info; +}); diff --git a/nodejs/node_modules/logform/label.js b/nodejs/node_modules/logform/label.js new file mode 100644 index 00000000..e6127fd0 --- /dev/null +++ b/nodejs/node_modules/logform/label.js @@ -0,0 +1,19 @@ +'use strict'; + +const format = require('./format'); + +/* + * function label (info) + * Returns a new instance of the label Format which adds the specified + * `opts.label` before the message. This was previously exposed as + * { label: 'my label' } to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts) => { + if (opts.message) { + info.message = `[${opts.label}] ${info.message}`; + return info; + } + + info.label = opts.label; + return info; +}); diff --git a/nodejs/node_modules/logform/levels.js b/nodejs/node_modules/logform/levels.js new file mode 100644 index 00000000..5a7345cc --- /dev/null +++ b/nodejs/node_modules/logform/levels.js @@ -0,0 +1,12 @@ +'use strict'; + +const { Colorizer } = require('./colorize'); + +/* + * Simple method to register colors with a simpler require + * path within the module. + */ +module.exports = config => { + Colorizer.addColors(config.colors || config); + return config; +}; diff --git a/nodejs/node_modules/logform/logstash.js b/nodejs/node_modules/logform/logstash.js new file mode 100644 index 00000000..3493733d --- /dev/null +++ b/nodejs/node_modules/logform/logstash.js @@ -0,0 +1,29 @@ +'use strict'; + +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); +const jsonStringify = require('safe-stable-stringify'); + +/* + * function logstash (info) + * Returns a new instance of the LogStash Format that turns a + * log `info` object into pure JSON with the appropriate logstash + * options. This was previously exposed as { logstash: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format(info => { + const logstash = {}; + if (info.message) { + logstash['@message'] = info.message; + delete info.message; + } + + if (info.timestamp) { + logstash['@timestamp'] = info.timestamp; + delete info.timestamp; + } + + logstash['@fields'] = info; + info[MESSAGE] = jsonStringify(logstash); + return info; +}); diff --git a/nodejs/node_modules/logform/metadata.js b/nodejs/node_modules/logform/metadata.js new file mode 100644 index 00000000..dc796db2 --- /dev/null +++ b/nodejs/node_modules/logform/metadata.js @@ -0,0 +1,61 @@ +'use strict'; + +const format = require('./format'); + +function fillExcept(info, fillExceptKeys, metadataKey) { + const savedKeys = fillExceptKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + const metadata = Object.keys(info).reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + + Object.assign(info, savedKeys, { + [metadataKey]: metadata + }); + return info; +} + +function fillWith(info, fillWithKeys, metadataKey) { + info[metadataKey] = fillWithKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + return info; +} + +/** + * Adds in a "metadata" object to collect extraneous data, similar to the metadata + * object in winston 2.x. + */ +module.exports = format((info, opts = {}) => { + let metadataKey = 'metadata'; + if (opts.key) { + metadataKey = opts.key; + } + + let fillExceptKeys = []; + if (!opts.fillExcept && !opts.fillWith) { + fillExceptKeys.push('level'); + fillExceptKeys.push('message'); + } + + if (opts.fillExcept) { + fillExceptKeys = opts.fillExcept; + } + + if (fillExceptKeys.length > 0) { + return fillExcept(info, fillExceptKeys, metadataKey); + } + + if (opts.fillWith) { + return fillWith(info, opts.fillWith, metadataKey); + } + + return info; +}); diff --git a/nodejs/node_modules/logform/ms.js b/nodejs/node_modules/logform/ms.js new file mode 100644 index 00000000..88830faa --- /dev/null +++ b/nodejs/node_modules/logform/ms.js @@ -0,0 +1,18 @@ +'use strict'; + +const format = require('./format'); +const ms = require('ms'); + +/* + * function ms (info) + * Returns an `info` with a `ms` property. The `ms` property holds the Value + * of the time difference between two calls in milliseconds. + */ +module.exports = format(info => { + const curr = +new Date(); + this.diff = curr - (this.prevTime || curr); + this.prevTime = curr; + info.ms = `+${ms(this.diff)}`; + + return info; +}); diff --git a/nodejs/node_modules/logform/package.json b/nodejs/node_modules/logform/package.json new file mode 100644 index 00000000..de36aa02 --- /dev/null +++ b/nodejs/node_modules/logform/package.json @@ -0,0 +1,53 @@ +{ + "name": "logform", + "version": "2.6.0", + "description": "An mutable object-based log format designed for chaining & objectMode streams.", + "main": "index.js", + "browser": "dist/browser.js", + "scripts": { + "lint": "eslint *.js test/*.js examples/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", + "pretest": "npm run lint && npm run build", + "test": "nyc mocha test/*.test.js", + "build": "rimraf dist && babel *.js -d ./dist", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/winstonjs/logform.git" + }, + "keywords": [ + "winston", + "logging", + "format", + "winstonjs" + ], + "author": "Charlie Robbins ", + "license": "MIT", + "bugs": { + "url": "https://github.com/winstonjs/logform/issues" + }, + "homepage": "https://github.com/winstonjs/logform#readme", + "dependencies": { + "@colors/colors": "1.6.0", + "@types/triple-beam": "^1.3.2", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "safe-stable-stringify": "^2.3.1", + "triple-beam": "^1.3.0" + }, + "devDependencies": { + "@babel/cli": "^7.10.3", + "@babel/core": "^7.10.3", + "@babel/preset-env": "^7.10.3", + "@dabh/eslint-config-populist": "^5.0.0", + "assume": "^2.2.0", + "eslint": "^8.8.0", + "mocha": "^10.0.0", + "nyc": "^15.1.0", + "rimraf": "^5.0.5" + }, + "types": "./index.d.ts", + "engines": { + "node": ">= 12.0.0" + } +} diff --git a/nodejs/node_modules/logform/pad-levels.js b/nodejs/node_modules/logform/pad-levels.js new file mode 100644 index 00000000..7db5a9d6 --- /dev/null +++ b/nodejs/node_modules/logform/pad-levels.js @@ -0,0 +1,83 @@ +/* eslint no-unused-vars: 0 */ +'use strict'; + +const { configs, LEVEL, MESSAGE } = require('triple-beam'); + +class Padder { + constructor(opts = { levels: configs.npm.levels }) { + this.paddings = Padder.paddingForLevels(opts.levels, opts.filler); + this.options = opts; + } + + /** + * Returns the maximum length of keys in the specified `levels` Object. + * @param {Object} levels Set of all levels to calculate longest level against. + * @returns {Number} Maximum length of the longest level string. + */ + static getLongestLevel(levels) { + const lvls = Object.keys(levels).map(level => level.length); + return Math.max(...lvls); + } + + /** + * Returns the padding for the specified `level` assuming that the + * maximum length of all levels it's associated with is `maxLength`. + * @param {String} level Level to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @param {Number} maxLength Length of the longest level + * @returns {String} Padding string for the `level` + */ + static paddingForLevel(level, filler, maxLength) { + const targetLen = maxLength + 1 - level.length; + const rep = Math.floor(targetLen / filler.length); + const padding = `${filler}${filler.repeat(rep)}`; + return padding.slice(0, targetLen); + } + + /** + * Returns an object with the string paddings for the given `levels` + * using the specified `filler`. + * @param {Object} levels Set of all levels to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @returns {Object} Mapping of level to desired padding. + */ + static paddingForLevels(levels, filler = ' ') { + const maxLength = Padder.getLongestLevel(levels); + return Object.keys(levels).reduce((acc, level) => { + acc[level] = Padder.paddingForLevel(level, filler, maxLength); + return acc; + }, {}); + } + + /** + * Prepends the padding onto the `message` based on the `LEVEL` of + * the `info`. This is based on the behavior of `winston@2` which also + * prepended the level onto the message. + * + * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 + * + * @param {Info} info Logform info object + * @param {Object} opts Options passed along to this instance. + * @returns {Info} Modified logform info object. + */ + transform(info, opts) { + info.message = `${this.paddings[info[LEVEL]]}${info.message}`; + if (info[MESSAGE]) { + info[MESSAGE] = `${this.paddings[info[LEVEL]]}${info[MESSAGE]}`; + } + + return info; + } +} + +/* + * function padLevels (info) + * Returns a new instance of the padLevels Format which pads + * levels to be the same length. This was previously exposed as + * { padLevels: true } to transports in `winston < 3.0.0`. + */ +module.exports = opts => new Padder(opts); + +module.exports.Padder + = module.exports.Format + = Padder; diff --git a/nodejs/node_modules/logform/pretty-print.js b/nodejs/node_modules/logform/pretty-print.js new file mode 100644 index 00000000..2ad3dbea --- /dev/null +++ b/nodejs/node_modules/logform/pretty-print.js @@ -0,0 +1,29 @@ +'use strict'; + +const inspect = require('util').inspect; +const format = require('./format'); +const { LEVEL, MESSAGE, SPLAT } = require('triple-beam'); + +/* + * function prettyPrint (info) + * Returns a new instance of the prettyPrint Format that "prettyPrint" + * serializes `info` objects. This was previously exposed as + * { prettyPrint: true } to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts = {}) => { + // + // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they + // are internal, we remove them before util.inspect so they + // are not printed. + // + const stripped = Object.assign({}, info); + + // Remark (indexzero): update this technique in April 2019 + // when node@6 is EOL + delete stripped[LEVEL]; + delete stripped[MESSAGE]; + delete stripped[SPLAT]; + + info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); + return info; +}); diff --git a/nodejs/node_modules/logform/printf.js b/nodejs/node_modules/logform/printf.js new file mode 100644 index 00000000..4e60bbce --- /dev/null +++ b/nodejs/node_modules/logform/printf.js @@ -0,0 +1,26 @@ +'use strict'; + +const { MESSAGE } = require('triple-beam'); + +class Printf { + constructor(templateFn) { + this.template = templateFn; + } + + transform(info) { + info[MESSAGE] = this.template(info); + return info; + } +} + +/* + * function printf (templateFn) + * Returns a new instance of the printf Format that creates an + * intermediate prototype to store the template string-based formatter + * function. + */ +module.exports = opts => new Printf(opts); + +module.exports.Printf + = module.exports.Format + = Printf; diff --git a/nodejs/node_modules/logform/simple.js b/nodejs/node_modules/logform/simple.js new file mode 100644 index 00000000..af3254ba --- /dev/null +++ b/nodejs/node_modules/logform/simple.js @@ -0,0 +1,33 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); +const jsonStringify = require('safe-stable-stringify'); + +/* + * function simple (info) + * Returns a new instance of the simple format TransformStream + * which writes a simple representation of logs. + * + * const { level, message, splat, ...rest } = info; + * + * ${level}: ${message} if rest is empty + * ${level}: ${message} ${JSON.stringify(rest)} otherwise + */ +module.exports = format(info => { + const stringifiedRest = jsonStringify(Object.assign({}, info, { + level: undefined, + message: undefined, + splat: undefined + })); + + const padding = info.padding && info.padding[info.level] || ''; + if (stringifiedRest !== '{}') { + info[MESSAGE] = `${info.level}:${padding} ${info.message} ${stringifiedRest}`; + } else { + info[MESSAGE] = `${info.level}:${padding} ${info.message}`; + } + + return info; +}); diff --git a/nodejs/node_modules/logform/splat.js b/nodejs/node_modules/logform/splat.js new file mode 100644 index 00000000..08ff6f7f --- /dev/null +++ b/nodejs/node_modules/logform/splat.js @@ -0,0 +1,132 @@ +'use strict'; + +const util = require('util'); +const { SPLAT } = require('triple-beam'); + +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ +const formatRegExp = /%[scdjifoO%]/g; + +/** + * Captures the number of escaped % signs in a format string (i.e. %s strings). + * @type {RegExp} + */ +const escapedPercent = /%%/g; + +class Splatter { + constructor(opts) { + this.options = opts; + } + + /** + * Check to see if tokens <= splat.length, assign { splat, meta } into the + * `info` accordingly, and write to this instance. + * + * @param {Info} info Logform info message. + * @param {String[]} tokens Set of string interpolation tokens. + * @returns {Info} Modified info message + * @private + */ + _splat(info, tokens) { + const msg = info.message; + const splat = info[SPLAT] || info.splat || []; + const percents = msg.match(escapedPercent); + const escapes = percents && percents.length || 0; + + // The expected splat is the number of tokens minus the number of escapes + // e.g. + // - { expectedSplat: 3 } '%d %s %j' + // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j' + // + // Any "meta" will be arugments in addition to the expected splat size + // regardless of type. e.g. + // + // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true }); + // would result in splat of four (4), but only three (3) are expected. Therefore: + // + // extraSplat = 3 - 4 = -1 + // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1); + // splat = [100, 'wow', { such: 'js' }] + const expectedSplat = tokens.length - escapes; + const extraSplat = expectedSplat - splat.length; + const metas = extraSplat < 0 + ? splat.splice(extraSplat, -1 * extraSplat) + : []; + + // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + + info.message = util.format(msg, ...splat); + return info; + } + + /** + * Transforms the `info` message by using `util.format` to complete + * any `info.message` provided it has string interpolation tokens. + * If no tokens exist then `info` is immutable. + * + * @param {Info} info Logform info message. + * @param {Object} opts Options for this instance. + * @returns {Info} Modified info message + */ + transform(info) { + const msg = info.message; + const splat = info[SPLAT] || info.splat; + + // No need to process anything if splat is undefined + if (!splat || !splat.length) { + return info; + } + + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + const tokens = msg && msg.match && msg.match(formatRegExp); + + // This condition will take care of inputs with info[SPLAT] + // but no tokens present + if (!tokens && (splat || splat.length)) { + const metas = splat.length > 1 + ? splat.splice(0) + : splat; + + // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + + return info; + } + + if (tokens) { + return this._splat(info, tokens); + } + + return info; + } +} + +/* + * function splat (info) + * Returns a new instance of the splat format TransformStream + * which performs string interpolation from `info` objects. This was + * previously exposed implicitly in `winston < 3.0.0`. + */ +module.exports = opts => new Splatter(opts); diff --git a/nodejs/node_modules/logform/timestamp.js b/nodejs/node_modules/logform/timestamp.js new file mode 100644 index 00000000..706e4881 --- /dev/null +++ b/nodejs/node_modules/logform/timestamp.js @@ -0,0 +1,30 @@ +'use strict'; + +const fecha = require('fecha'); +const format = require('./format'); + +/* + * function timestamp (info) + * Returns a new instance of the timestamp Format which adds a timestamp + * to the info. It was previously available in winston < 3.0.0 as: + * + * - { timestamp: true } // `new Date.toISOString()` + * - { timestamp: function:String } // Value returned by `timestamp()` + */ +module.exports = format((info, opts = {}) => { + if (opts.format) { + info.timestamp = typeof opts.format === 'function' + ? opts.format() + : fecha.format(new Date(), opts.format); + } + + if (!info.timestamp) { + info.timestamp = new Date().toISOString(); + } + + if (opts.alias) { + info[opts.alias] = info.timestamp; + } + + return info; +}); diff --git a/nodejs/node_modules/logform/tsconfig.json b/nodejs/node_modules/logform/tsconfig.json new file mode 100644 index 00000000..1d494cf6 --- /dev/null +++ b/nodejs/node_modules/logform/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/nodejs/node_modules/logform/uncolorize.js b/nodejs/node_modules/logform/uncolorize.js new file mode 100644 index 00000000..c3c020f2 --- /dev/null +++ b/nodejs/node_modules/logform/uncolorize.js @@ -0,0 +1,27 @@ +'use strict'; + +const colors = require('@colors/colors/safe'); +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); + +/* + * function uncolorize (info) + * Returns a new instance of the uncolorize Format that strips colors + * from `info` objects. This was previously exposed as { stripColors: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts) => { + if (opts.level !== false) { + info.level = colors.strip(info.level); + } + + if (opts.message !== false) { + info.message = colors.strip(String(info.message)); + } + + if (opts.raw !== false && info[MESSAGE]) { + info[MESSAGE] = colors.strip(String(info[MESSAGE])); + } + + return info; +}); diff --git a/nodejs/node_modules/ltgt/.travis.yml b/nodejs/node_modules/ltgt/.travis.yml new file mode 100644 index 00000000..895dbd36 --- /dev/null +++ b/nodejs/node_modules/ltgt/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/nodejs/node_modules/ltgt/LICENSE b/nodejs/node_modules/ltgt/LICENSE new file mode 100644 index 00000000..9c825b19 --- /dev/null +++ b/nodejs/node_modules/ltgt/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dominic Tarr + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/ltgt/README.md b/nodejs/node_modules/ltgt/README.md new file mode 100644 index 00000000..1fdfeb0e --- /dev/null +++ b/nodejs/node_modules/ltgt/README.md @@ -0,0 +1,150 @@ +# ltgt + +implement correct ranges for level-* + +[![build status](https://secure.travis-ci.org/dominictarr/ltgt.png)](http://travis-ci.org/dominictarr/ltgt) +[![testling badge](https://ci.testling.com/dominictarr/ltgt.png)](https://ci.testling.com/dominictarr/ltgt) + +# example + + +``` js +var ltgt = require('ltgt') + +ltgt.start(range) //the start of the range +ltgt.end(range) //the end of the range + +//returns the lower/upper bound, whether it's inclusive or not. +ltgt.lowerBound(range) +ltgt.upperBound(range) + +ltgt.lt(range) +ltgt.gt(range) +ltgt.lte(range) +ltgt.gte(range) + +//return wether this is a reversed order +//(this is significant for start/end ranges +ltgt.reverse(range) +var filter = ltgt.filter(range) + +filter(key) == true //if key contained in range. + +ltgt.contains(range, key) + +``` + +# ways to specify ranges + +there have been a variety of ways to specify ranges in level-*. +this module supports them all. + +# gt/gte, lt/lte + +specify a range between a lower bound (gt, gte) and an upper bound (lt, lte) + +if `gte` and `gt` is undefined, read from the start of the database, +if `lte` and `lt` is undefined, read until the end of the database, + + +# min, max + +legacy level-sublevel style, +synonym for `gte`, `lte`. + +# start, end, reverse + +legacy levelup style. + +The range is from `start` -> `end`, `start` does not specify the lowest +record, instead it specifies the first record to be read. However, +`reverse` must also be passed correctly. This is way to specify a range is +confusing if you need to read in reverse, +so it's strongly recommended to use `gt/gte,lt/lte`. + +If `reverse` is `true`, +`start` *must* be `undefined` or less than `end`, +unless `end` is `undefined`. + +if `reverse` is `false` +`end` *must* be `undefined` or greater than `start`, +unless `start` is `undefined`. + +if start is undefined, read from the first record in the database +if end is undefined read until the last record in the database. + +# api + +## ltgt.contains(range, key, compare) + +using the provided compare method, return `true` if `key` +is within `range`. compare defaults to `ltgt.compare` + +## ltgt.filter(range, compare) + +return a function that returns true if it's argument is within range. +can be passed to `Array.filter` + +``` js +[1,2,3,4,5].filter(ltgt.filter({gt: 2, lte: 4}) +// => [3, 4] +``` + +## ltgt.lowerBound(range) + +return the lower bound of `range`. +Incase the lower bound is specified with `gt`, +check `ltgt.lowerBoundExclusive` + +## ltgt.upperBound(range) + +return the upperBound of `range`. +Incase the upper bound is specified with `gt`, +check `ltgt.upperBoundExclusive` + +## ltgt.lowerBoundExclusive(range) + +return true if upper bound is exclusive. + +## ltgt.upperBoundExclusive(range) + +return true if lower bound is exclusive. + +## ltgt.start(range, default) + +The start of the range. This takes into account direction (reverse) +If a `start` is not provided, `default` is used. + +## ltgt.end(range, default) + +The end of the range. This takes into account direction (reverse) +If a `end` is not provided, `default` is used. + +## ltgt.startInclusive(range) + +returns true if the range should start at the exact value returned +by `start(range)` otherwise, it should skip one input. + +## ltgt.endInclusive(range) + +returns true if the range should include the exact value returned +by `end(range)` otherwise, it should end on that value. + +## ltgt.toLtgt(range, _range, map, lowerBound, upperBound) + +convert a range to a new ltgt range. `_range` +is the object to return - if you want to mutate `range` +call `ltgt.toLtgt(range, range, map)` + +`map` gets called on each key in the range, and wether it's an upper or lower bound - +so can be used as an encode function. + +`map(value, isUpperBound)` if `isUpperBound` is false, this is the lower bound. + +## License + +MIT + + + + diff --git a/nodejs/node_modules/ltgt/index.js b/nodejs/node_modules/ltgt/index.js new file mode 100644 index 00000000..0724e69d --- /dev/null +++ b/nodejs/node_modules/ltgt/index.js @@ -0,0 +1,165 @@ + +exports.compare = function (a, b) { + + if(Buffer.isBuffer(a)) { + var l = Math.min(a.length, b.length) + for(var i = 0; i < l; i++) { + var cmp = a[i] - b[i] + if(cmp) return cmp + } + return a.length - b.length + } + + return a < b ? -1 : a > b ? 1 : 0 +} + +// to be compatible with the current abstract-leveldown tests +// nullish or empty strings. +// I could use !!val but I want to permit numbers and booleans, +// if possible. + +function isDef (val) { + return val !== undefined && val !== '' +} + +function has (range, name) { + return Object.hasOwnProperty.call(range, name) +} + +function hasKey(range, name) { + return Object.hasOwnProperty.call(range, name) && name +} + +var lowerBoundKey = exports.lowerBoundKey = function (range) { + return ( + hasKey(range, 'gt') + || hasKey(range, 'gte') + || hasKey(range, 'min') + || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start')) + || undefined + ) +} + +var lowerBound = exports.lowerBound = function (range, def) { + var k = lowerBoundKey(range) + return k ? range[k] : def +} + +var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) { + return has(range, 'gt') ? false : true +} + +var upperBoundInclusive = exports.upperBoundInclusive = + function (range) { + return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true + } + +var lowerBoundExclusive = exports.lowerBoundExclusive = + function (range) { + return !lowerBoundInclusive(range) + } + +var upperBoundExclusive = exports.upperBoundExclusive = + function (range) { + return !upperBoundInclusive(range) + } + +var upperBoundKey = exports.upperBoundKey = function (range) { + return ( + hasKey(range, 'lt') + || hasKey(range, 'lte') + || hasKey(range, 'max') + || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end')) + || undefined + ) +} + +var upperBound = exports.upperBound = function (range, def) { + var k = upperBoundKey(range) + return k ? range[k] : def +} + +exports.start = function (range, def) { + return range.reverse ? upperBound(range, def) : lowerBound(range, def) +} +exports.end = function (range, def) { + return range.reverse ? lowerBound(range, def) : upperBound(range, def) +} +exports.startInclusive = function (range) { + return ( + range.reverse + ? upperBoundInclusive(range) + : lowerBoundInclusive(range) + ) +} +exports.endInclusive = function (range) { + return ( + range.reverse + ? lowerBoundInclusive(range) + : upperBoundInclusive(range) + ) +} + +function id (e) { return e } + +exports.toLtgt = function (range, _range, map, lower, upper) { + _range = _range || {} + map = map || id + var defaults = arguments.length > 3 + var lb = exports.lowerBoundKey(range) + var ub = exports.upperBoundKey(range) + if(lb) { + if(lb === 'gt') _range.gt = map(range.gt, false) + else _range.gte = map(range[lb], false) + } + else if(defaults) + _range.gte = map(lower, false) + + if(ub) { + if(ub === 'lt') _range.lt = map(range.lt, true) + else _range.lte = map(range[ub], true) + } + else if(defaults) + _range.lte = map(upper, true) + + if(range.reverse != null) + _range.reverse = !!range.reverse + + //if range was used mutably + //(in level-sublevel it's part of an options object + //that has more properties on it.) + if(has(_range, 'max')) delete _range.max + if(has(_range, 'min')) delete _range.min + if(has(_range, 'start')) delete _range.start + if(has(_range, 'end')) delete _range.end + + return _range +} + +exports.contains = function (range, key, compare) { + compare = compare || exports.compare + + var lb = lowerBound(range) + if(isDef(lb)) { + var cmp = compare(key, lb) + if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range))) + return false + } + + var ub = upperBound(range) + if(isDef(ub)) { + var cmp = compare(key, ub) + if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range)) + return false + } + + return true +} + +exports.filter = function (range, compare) { + return function (key) { + return exports.contains(range, key, compare) + } +} + + diff --git a/nodejs/node_modules/ltgt/package.json b/nodejs/node_modules/ltgt/package.json new file mode 100644 index 00000000..944fbbe3 --- /dev/null +++ b/nodejs/node_modules/ltgt/package.json @@ -0,0 +1,36 @@ +{ + "name": "ltgt", + "description": "", + "version": "2.2.1", + "homepage": "https://github.com/dominictarr/ltgt", + "repository": { + "type": "git", + "url": "git://github.com/dominictarr/ltgt.git" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.1" + }, + "scripts": { + "prepublish": "npm ls && node test.js", + "test": "node test.js" + }, + "author": "Dominic Tarr (http://dominictarr.com)", + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/nodejs/node_modules/ltgt/test.js b/nodejs/node_modules/ltgt/test.js new file mode 100644 index 00000000..18e70439 --- /dev/null +++ b/nodejs/node_modules/ltgt/test.js @@ -0,0 +1,380 @@ +var tape = require('tape') +var ltgt = require('./') + +function clone (o) { + var O = {} + for(var k in o) + O[k] = o[k] + return O +} + +var elements = [ + 1, 2, 3, 4, 5 +] + +var ranges = [ + //default + { range: + {}, + selection: + elements + }, + { range: + {reverse: true }, + selection: + elements.slice().reverse() + }, + + //start/end - this has a lot of semantics because reverse is significant. + { range: + {start: 2}, + selection: + [2, 3, 4, 5] + }, + { range: + {start: 2, reverse: true}, + selection: + [2, 1] + }, + { range: + {end: 2}, + selection: + [1, 2] + }, + { range: + {end: 2, reverse: true}, + selection: + [2, 3, 4, 5].reverse() + }, + { range: + {start: 2.5}, + selection: + [3, 4, 5] + }, + { range: + {start: 2.5, reverse: true}, + selection: + [2, 1] + }, + { range: + {end: 2.5, reverse: true}, + selection: + [5, 4, 3] + }, + { range: + {start: 5}, + selection: + [5] + }, + { range: + {start: 5.5}, + selection: + [] + }, + { range: + {end: 0.5}, + selection: + [] + }, + { range: + {start: 5.5, reverse: true}, + selection: + [5, 4, 3, 2, 1] + }, + { range: + {end: 0.5, reverse: true}, + selection: + [5, 4, 3, 2, 1] + }, + + //nullish and empty strings signify are streated like null! + { range: + {end: null, reverse: true}, + selection: + [5, 4, 3, 2, 1] + }, + { range: + {end: undefined, reverse: true}, + selection: + [5, 4, 3, 2, 1] + }, + { range: + {end: '', reverse: true}, + selection: + [5, 4, 3, 2, 1] + }, + + //lt/gt/lte/gte + + { range: + {lt: 2.5}, + selection: + [1, 2] + }, + { range: + {gt: 2.5}, + selection: + [3, 4, 5] + }, + { range: + {lt: 2}, + selection: + [1] + }, + { range: + {gt: 2}, + selection: + [3, 4, 5] + }, + + { range: + {lte: 2.5}, + selection: + [1, 2] + }, + { range: + {gte: 2.5}, + selection: + [3, 4, 5] + }, + { range: + {lte: 2}, + selection: + [1, 2] + }, + { range: + {gte: 2}, + selection: + [2, 3, 4, 5] + }, + + { range: + {gt: 2.5, lt: 5}, + selection: + [3, 4] + }, + { range: + {gte: 2, lt: 3.5}, + selection: + [2, 3] + }, + { range: + {gt: 2.5, lte: 4}, + selection: + [3, 4] + }, + { range: + {gte: 2, lte: 4}, + selection: + [2, 3, 4] + }, + + //min/max - used by sublevel, equiv to gte, lte + + { range: + {min: 2, max: 4}, + selection: + [2, 3, 4] + }, + + { range: + {max: 2.5}, + selection: + [1, 2] + }, + { range: + {min: 2.5}, + selection: + [3, 4, 5] + }, + { range: + {max: 2}, + selection: + [1, 2] + }, + { range: + {min: 2}, + selection: + [2, 3, 4, 5] + } + +] + + +tape('upperBound', function (t) { + t.equal('b', ltgt.upperBound({start: 'b', reverse: true})) + t.equal('b', ltgt.upperBound({end: 'b', reverse: false})) + t.equal(undefined, ltgt.lowerBound({start: 'b', reverse: true})) + t.equal(undefined, ltgt.lowerBound({end: 'b', reverse: false})) + t.end() +}) + +tape('bounds and inclusive', function (t) { +// t.equal(ltgt.upperBound({start: 'b', reverse: true}), 'b') +// t.equal(ltgt.upperBoundInclusive({start: 'b', reverse: true}), true) +// t.equal(ltgt.upperBound({end: 'b', reverse: false}), 'b') +// +// t.equal(ltgt.lowerBound({start: 'b', reverse: true}), undefined) +// t.equal(ltgt.lowerBound({end: 'b', reverse: false}), undefined) +// t.equal(ltgt.upperBoundInclusive({start: 'b', reverse: true}), true) +// t.equal(ltgt.upperBoundInclusive({end: 'b', reverse: false}), true) +// + t.equal(ltgt.upperBound({lt: 'b', reverse: true}), 'b') + t.equal(ltgt.upperBound({lte: 'b', reverse: true}), 'b') + + t.equal(ltgt.upperBound({lt: 'b'}), 'b') + t.equal(ltgt.upperBound({lte: 'b'}), 'b') + + t.equal(ltgt.upperBoundInclusive({lt: 'b'}), false) + + t.equal(ltgt.upperBoundInclusive({lte: 'b'}), true) + + t.equal(ltgt.lowerBoundInclusive({gt: 'b'}), false) + t.equal(ltgt.lowerBoundInclusive({gte: 'b'}), true) + + + t.end() +}) + + +tape('start, end', function (t) { +// t.equal(ltgt.upperBound({start: 'b', reverse: true}), 'b') +// t.equal(ltgt.upperBoundInclusive({start: 'b', reverse: true}), true) +// t.equal(ltgt.upperBound({end: 'b', reverse: false}), 'b') +// +// t.equal(ltgt.lowerBound({start: 'b', reverse: true}), undefined) +// t.equal(ltgt.lowerBound({end: 'b', reverse: false}), undefined) +// t.equal(ltgt.upperBoundInclusive({start: 'b', reverse: true}), true) +// t.equal(ltgt.upperBoundInclusive({end: 'b', reverse: false}), true) + + t.equal(ltgt.start({lt: 'b', reverse: true}), 'b') + t.equal(ltgt.start({lte: 'b', reverse: true}), 'b') + t.equal(ltgt.end({lt: 'b', reverse: true}, null), null) + t.equal(ltgt.end({lte: 'b', reverse: true}, null), null) + + t.equal(ltgt.end({lt: 'b'}), 'b') + t.equal(ltgt.end({lte: 'b'}), 'b') + t.equal(ltgt.start({lt: 'b'}, undefined), undefined) + t.equal(ltgt.start({lte: 'b'}, undefined), undefined) + + t.equal(ltgt.endInclusive({lt: 'b'}), false) + + t.equal(ltgt.endInclusive({lte: 'b'}), true) + + t.equal(ltgt.startInclusive({gt: 'b'}), false) + t.equal(ltgt.startInclusive({gte: 'b'}), true) + + + t.end() +}) + + +var strings = ['00', '01', '02'] +var sranges = [ + {range: + {start: '00'}, + selection: + ['00', '01', '02'] + }, + {range: + {start: '03', reverse: true}, + selection: + ['02', '01', '00'] + }, + +] +function compare (a, b) { + return a - b +} + +make(elements, ranges) + +make(strings, sranges) +make(elements.map(String), ranges.map(function (e) { + var r = {} + for(var k in e.range) + if('number' === typeof e.range[k]) + r[k] = e.range.toString() + return {range: e.range, selection: e.selection.map(String)} +})) + +function make (elements, ranges) { + + ranges.forEach(function (e) { + + tape(JSON.stringify(e.range) + ' => '+ JSON.stringify(e.selection), + function (t) { + var actual = elements.filter(ltgt.filter(e.range)) + if(e.range.reverse) + actual.reverse() + t.deepEqual(actual, e.selection, 'test range:' + JSON.stringify(e.range)) + + var range = ltgt.toLtgt(e.range) + //should not just return the same thing. + t.notOk(range.min || range.max || range.start || range.end) + + var actual2 = elements.filter(ltgt.filter(range)) + if(e.range.reverse) + actual2.reverse() + t.deepEqual(actual2, e.selection) + + t.end() + }) + }) +} + + +function createLtgtTests(mutate) { + return function (t) { + function map (key) { + return 'foo!' + key + } + + function T (expected, input) { + input = clone(input) + t.deepEqual( + expected, + ltgt.toLtgt(input, mutate ? input : null, map, '!', '~') + ) + } + + //start, end + + T({gte: 'foo!a', lte: 'foo!b'}, {start: 'a', end:'b'}) + T({gte: 'foo!a', lte: 'foo!~'}, {start: 'a'}) + T({gte: 'foo!!', lte: 'foo!b'}, {end: 'b'}) + + T({gte: 'foo!a', lte: 'foo!b', reverse: true}, + {start: 'b', end: 'a', reverse: true}) + + // min, max + + T({gte: 'foo!a', lte: 'foo!b'}, {min: 'a', max:'b'}) + T({gte: 'foo!a', lte: 'foo!~'}, {min: 'a'}) + T({gte: 'foo!!', lte: 'foo!b'}, {max: 'b'}) + T({gte: 'foo!!', lte: 'foo!~'}, {}) + + // lt, gt + + T({gt: 'foo!a', lt: 'foo!b'}, {gt: 'a', lt:'b'}) + T({gt: 'foo!a', lte: 'foo!~'}, {gt: 'a'}) + T({gte: 'foo!!', lt: 'foo!b'}, {lt: 'b'}) + T({gte: 'foo!!', lte: 'foo!~'}, {}) + + // lt, gt + + T({gte: 'foo!a', lte: 'foo!b'}, {gte: 'a', lte:'b'}) + T({gte: 'foo!a', lte: 'foo!~'}, {gte: 'a'}) + T({gte: 'foo!!', lte: 'foo!b'}, {lte: 'b'}) + T({gte: 'foo!!', lte: 'foo!~'}, {}) + + t.end() + } +} + +tape('toLtgt - immutable', createLtgtTests(false)) +tape('toLtgt - mutable', createLtgtTests(true)) + + + + diff --git a/nodejs/node_modules/memory-pager/.travis.yml b/nodejs/node_modules/memory-pager/.travis.yml new file mode 100644 index 00000000..1c4ab31e --- /dev/null +++ b/nodejs/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/nodejs/node_modules/memory-pager/LICENSE b/nodejs/node_modules/memory-pager/LICENSE new file mode 100644 index 00000000..56fce089 --- /dev/null +++ b/nodejs/node_modules/memory-pager/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/memory-pager/README.md b/nodejs/node_modules/memory-pager/README.md new file mode 100644 index 00000000..aed17614 --- /dev/null +++ b/nodejs/node_modules/memory-pager/README.md @@ -0,0 +1,65 @@ +# memory-pager + +Access memory using small fixed sized buffers instead of allocating a huge buffer. +Useful if you are implementing sparse data structures (such as large bitfield). + +![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) + +``` +npm install memory-pager +``` + +## Usage + +``` js +var pager = require('paged-memory') + +var pages = pager(1024) // use 1kb per page + +var page = pages.get(10) // get page #10 + +console.log(page.offset) // 10240 +console.log(page.buffer) // a blank 1kb buffer +``` + +## API + +#### `var pages = pager(pageSize)` + +Create a new pager. `pageSize` defaults to `1024`. + +#### `var page = pages.get(pageNumber, [noAllocate])` + +Get a page. The page will be allocated at first access. + +Optionally you can set the `noAllocate` flag which will make the +method return undefined if no page has been allocated already + +A page looks like this + +``` js +{ + offset: byteOffset, + buffer: bufferWithPageSize +} +``` + +#### `pages.set(pageNumber, buffer)` + +Explicitly set the buffer for a page. + +#### `pages.updated(page)` + +Mark a page as updated. + +#### `pages.lastUpdate()` + +Get the last page that was updated. + +#### `var buf = pages.toBuffer()` + +Concat all pages allocated pages into a single buffer + +## License + +MIT diff --git a/nodejs/node_modules/memory-pager/index.js b/nodejs/node_modules/memory-pager/index.js new file mode 100644 index 00000000..687f346f --- /dev/null +++ b/nodejs/node_modules/memory-pager/index.js @@ -0,0 +1,160 @@ +module.exports = Pager + +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) + + 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 = pageSize || 1024 + this.deduplicate = opts ? opts.deduplicate : null + this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null +} + +Pager.prototype.updated = function (page) { + while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { + page.deduplicate++ + if (page.deduplicate === this.deduplicate.length) { + page.deduplicate = 0 + if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate + break + } + } + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype._array = function (i, noAllocate) { + if (i >= this.maxPages) { + if (noAllocate) return + grow(this, i) + } + + factor(i, this.path) + + var arr = this.pages + + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] + + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } + + arr = next + } + + return arr +} + +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] + + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] + + if (i >= this.length) this.length = i + 1 + + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } + + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } + + var page = arr[first] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 + + while (ptr < list.length) { + var arr = this._array(ptr, true) + for (var i = 0; i < 32768 && ptr < list.length; i++) { + list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty + } + } + + return Buffer.concat(list) +} + +function grow (pager, index) { + while (pager.maxPages < index) { + var old = pager.pages + pager.pages = new Array(32768) + pager.pages[0] = old + pager.level++ + pager.maxPages *= 32768 + } +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function copy (buf) { + var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) + buf.copy(cpy) + return cpy +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false + this.deduplicate = 0 +} + +function factor (n, out) { + n = (n - (out[0] = (n & 32767))) / 32768 + n = (n - (out[1] = (n & 32767))) / 32768 + out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 +} diff --git a/nodejs/node_modules/memory-pager/package.json b/nodejs/node_modules/memory-pager/package.json new file mode 100644 index 00000000..f4847e8c --- /dev/null +++ b/nodejs/node_modules/memory-pager/package.json @@ -0,0 +1,24 @@ +{ + "name": "memory-pager", + "version": "1.5.0", + "description": "Access memory using small fixed sized buffers", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/memory-pager.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/memory-pager/issues" + }, + "homepage": "https://github.com/mafintosh/memory-pager" +} diff --git a/nodejs/node_modules/memory-pager/test.js b/nodejs/node_modules/memory-pager/test.js new file mode 100644 index 00000000..16382100 --- /dev/null +++ b/nodejs/node_modules/memory-pager/test.js @@ -0,0 +1,80 @@ +var tape = require('tape') +var pager = require('./') + +tape('get page', function (t) { + var pages = pager(1024) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.end() +}) + +tape('get page twice', function (t) { + var pages = pager(1024) + t.same(pages.length, 0) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1) + + var other = pages.get(0) + + t.same(other, page) + t.end() +}) + +tape('get no mutable page', function (t) { + var pages = pager(1024) + + t.ok(!pages.get(141, true)) + t.ok(pages.get(141)) + t.ok(pages.get(141, true)) + + t.end() +}) + +tape('get far out page', function (t) { + var pages = pager(1024) + + var page = pages.get(1000000) + + t.same(page.offset, 1000000 * 1024) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + + var other = pages.get(1) + + t.same(other.offset, 1024) + t.same(other.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + t.ok(other !== page) + + t.end() +}) + +tape('updates', function (t) { + var pages = pager(1024) + + t.same(pages.lastUpdate(), null) + + var page = pages.get(10) + + page.buffer[42] = 1 + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + page.buffer[42] = 2 + pages.updated(page) + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + t.end() +}) diff --git a/nodejs/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs b/nodejs/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs new file mode 100644 index 00000000..a0f5be52 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs @@ -0,0 +1,6 @@ +import mod from "./lib/index.js"; + +export default mod["default"]; +export const CommaAndColonSeparatedRecord = mod.CommaAndColonSeparatedRecord; +export const ConnectionString = mod.ConnectionString; +export const redactConnectionString = mod.redactConnectionString; diff --git a/nodejs/node_modules/mongodb-connection-string-url/LICENSE b/nodejs/node_modules/mongodb-connection-string-url/LICENSE new file mode 100644 index 00000000..d57f55f4 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/LICENSE @@ -0,0 +1,192 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2020 MongoDB Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/nodejs/node_modules/mongodb-connection-string-url/README.md b/nodejs/node_modules/mongodb-connection-string-url/README.md new file mode 100644 index 00000000..0eb65d00 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/README.md @@ -0,0 +1,25 @@ +# mongodb-connection-string-url + +MongoDB connection strings, based on the WhatWG URL API + +```js +import ConnectionString from 'mongodb-connection-string-url'; + +const cs = new ConnectionString('mongodb://localhost'); +cs.searchParams.set('readPreference', 'secondary'); +console.log(cs.href); // 'mongodb://localhost/?readPreference=secondary' +``` + +## Deviations from the WhatWG URL package + +- URL parameters are case-insensitive +- The `.host`, `.hostname` and `.port` properties cannot be set, and reading + them does not return meaningful results (and are typed as `never`in TypeScript) +- The `.hosts` property contains a list of all hosts in the connection string +- The `.href` property cannot be set, only read +- There is an additional `.isSRV` property, set to `true` for `mongodb+srv://` +- There is an additional `.clone()` utility method on the prototype + +## LICENSE + +Apache-2.0 diff --git a/nodejs/node_modules/mongodb-connection-string-url/lib/index.d.ts b/nodejs/node_modules/mongodb-connection-string-url/lib/index.d.ts new file mode 100644 index 00000000..49c18ea2 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/lib/index.d.ts @@ -0,0 +1,62 @@ +import { URL } from 'whatwg-url'; +import { redactConnectionString, ConnectionStringRedactionOptions } from './redact'; +export { redactConnectionString, ConnectionStringRedactionOptions }; +declare class CaseInsensitiveMap extends Map { + delete(name: K): boolean; + get(name: K): string | undefined; + has(name: K): boolean; + set(name: K, value: any): this; + _normalizeKey(name: any): K; +} +declare abstract class URLWithoutHost extends URL { + abstract get host(): never; + abstract set host(value: never); + abstract get hostname(): never; + abstract set hostname(value: never); + abstract get port(): never; + abstract set port(value: never); + abstract get href(): string; + abstract set href(value: string); +} +export interface ConnectionStringParsingOptions { + looseValidation?: boolean; +} +export declare class ConnectionString extends URLWithoutHost { + _hosts: string[]; + constructor(uri: string, options?: ConnectionStringParsingOptions); + get host(): never; + set host(_ignored: never); + get hostname(): never; + set hostname(_ignored: never); + get port(): never; + set port(_ignored: never); + get href(): string; + set href(_ignored: string); + get isSRV(): boolean; + get hosts(): string[]; + set hosts(list: string[]); + toString(): string; + clone(): ConnectionString; + redact(options?: ConnectionStringRedactionOptions): ConnectionString; + typedSearchParams(): { + append(name: keyof T & string, value: any): void; + delete(name: keyof T & string): void; + get(name: keyof T & string): string | null; + getAll(name: keyof T & string): string[]; + has(name: keyof T & string): boolean; + set(name: keyof T & string, value: any): void; + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[keyof T & string, string]>; + _normalizeKey(name: keyof T & string): string; + [Symbol.iterator](): IterableIterator<[keyof T & string, string]>; + sort(): void; + forEach(callback: (this: THIS_ARG, value: string, name: string, searchParams: any) => void, thisArg?: THIS_ARG | undefined): void; + readonly [Symbol.toStringTag]: "URLSearchParams"; + }; +} +export declare class CommaAndColonSeparatedRecord> extends CaseInsensitiveMap { + constructor(from?: string | null); + toString(): string; +} +export default ConnectionString; diff --git a/nodejs/node_modules/mongodb-connection-string-url/lib/index.js b/nodejs/node_modules/mongodb-connection-string-url/lib/index.js new file mode 100644 index 00000000..8e4864d2 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/lib/index.js @@ -0,0 +1,213 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommaAndColonSeparatedRecord = exports.ConnectionString = exports.redactConnectionString = void 0; +const whatwg_url_1 = require("whatwg-url"); +const redact_1 = require("./redact"); +Object.defineProperty(exports, "redactConnectionString", { enumerable: true, get: function () { return redact_1.redactConnectionString; } }); +const DUMMY_HOSTNAME = '__this_is_a_placeholder__'; +function connectionStringHasValidScheme(connectionString) { + return (connectionString.startsWith('mongodb://') || + connectionString.startsWith('mongodb+srv://')); +} +const HOSTS_REGEX = /^(?[^/]+):\/\/(?:(?[^:@]*)(?::(?[^@]*))?@)?(?(?!:)[^/?@]*)(?.*)/; +class CaseInsensitiveMap extends Map { + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + _normalizeKey(name) { + name = `${name}`; + for (const key of this.keys()) { + if (key.toLowerCase() === name.toLowerCase()) { + name = key; + break; + } + } + return name; + } +} +function caseInsenstiveURLSearchParams(Ctor) { + return class CaseInsenstiveURLSearchParams extends Ctor { + append(name, value) { + return super.append(this._normalizeKey(name), value); + } + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + getAll(name) { + return super.getAll(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + keys() { + return super.keys(); + } + values() { + return super.values(); + } + entries() { + return super.entries(); + } + [Symbol.iterator]() { + return super[Symbol.iterator](); + } + _normalizeKey(name) { + return CaseInsensitiveMap.prototype._normalizeKey.call(this, name); + } + }; +} +class URLWithoutHost extends whatwg_url_1.URL { +} +class MongoParseError extends Error { + get name() { + return 'MongoParseError'; + } +} +class ConnectionString extends URLWithoutHost { + constructor(uri, options = {}) { + var _a; + const { looseValidation } = options; + if (!looseValidation && !connectionStringHasValidScheme(uri)) { + throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"'); + } + const match = uri.match(HOSTS_REGEX); + if (!match) { + throw new MongoParseError(`Invalid connection string "${uri}"`); + } + const { protocol, username, password, hosts, rest } = (_a = match.groups) !== null && _a !== void 0 ? _a : {}; + if (!looseValidation) { + if (!protocol || !hosts) { + throw new MongoParseError(`Protocol and host list are required in "${uri}"`); + } + try { + decodeURIComponent(username !== null && username !== void 0 ? username : ''); + decodeURIComponent(password !== null && password !== void 0 ? password : ''); + } + catch (err) { + throw new MongoParseError(err.message); + } + const illegalCharacters = /[:/?#[\]@]/gi; + if (username === null || username === void 0 ? void 0 : username.match(illegalCharacters)) { + throw new MongoParseError(`Username contains unescaped characters ${username}`); + } + if (!username || !password) { + const uriWithoutProtocol = uri.replace(`${protocol}://`, ''); + if (uriWithoutProtocol.startsWith('@') || uriWithoutProtocol.startsWith(':')) { + throw new MongoParseError('URI contained empty userinfo section'); + } + } + if (password === null || password === void 0 ? void 0 : password.match(illegalCharacters)) { + throw new MongoParseError('Password contains unescaped characters'); + } + } + let authString = ''; + if (typeof username === 'string') + authString += username; + if (typeof password === 'string') + authString += `:${password}`; + if (authString) + authString += '@'; + try { + super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`); + } + catch (err) { + if (looseValidation) { + new ConnectionString(uri, { + ...options, + looseValidation: false + }); + } + if (typeof err.message === 'string') { + err.message = err.message.replace(DUMMY_HOSTNAME, hosts); + } + throw err; + } + this._hosts = hosts.split(','); + if (!looseValidation) { + if (this.isSRV && this.hosts.length !== 1) { + throw new MongoParseError('mongodb+srv URI cannot have multiple service names'); + } + if (this.isSRV && this.hosts.some(host => host.includes(':'))) { + throw new MongoParseError('mongodb+srv URI cannot have port number'); + } + } + if (!this.pathname) { + this.pathname = '/'; + } + Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype); + } + get host() { return DUMMY_HOSTNAME; } + set host(_ignored) { throw new Error('No single host for connection string'); } + get hostname() { return DUMMY_HOSTNAME; } + set hostname(_ignored) { throw new Error('No single host for connection string'); } + get port() { return ''; } + set port(_ignored) { throw new Error('No single host for connection string'); } + get href() { return this.toString(); } + set href(_ignored) { throw new Error('Cannot set href for connection strings'); } + get isSRV() { + return this.protocol.includes('srv'); + } + get hosts() { + return this._hosts; + } + set hosts(list) { + this._hosts = list; + } + toString() { + return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(',')); + } + clone() { + return new ConnectionString(this.toString(), { + looseValidation: true + }); + } + redact(options) { + return (0, redact_1.redactValidConnectionString)(this, options); + } + typedSearchParams() { + const sametype = false && new (caseInsenstiveURLSearchParams(whatwg_url_1.URLSearchParams))(); + return this.searchParams; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this; + return { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash }; + } +} +exports.ConnectionString = ConnectionString; +class CommaAndColonSeparatedRecord extends CaseInsensitiveMap { + constructor(from) { + super(); + for (const entry of (from !== null && from !== void 0 ? from : '').split(',')) { + if (!entry) + continue; + const colonIndex = entry.indexOf(':'); + if (colonIndex === -1) { + this.set(entry, ''); + } + else { + this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1)); + } + } + } + toString() { + return [...this].map(entry => entry.join(':')).join(','); + } +} +exports.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord; +exports.default = ConnectionString; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb-connection-string-url/lib/index.js.map b/nodejs/node_modules/mongodb-connection-string-url/lib/index.js.map new file mode 100644 index 00000000..d325062a --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,2CAAkD;AAClD,qCAIkB;AACT,uGAHP,+BAAsB,OAGO;AAE/B,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,SAAS,8BAA8B,CAAC,gBAAwB;IAC9D,OAAO,CACL,gBAAgB,CAAC,UAAU,CAAC,YAAY,CAAC;QACzC,gBAAgB,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAC9C,CAAC;AACJ,CAAC;AAID,MAAM,WAAW,GACf,4GAA4G,CAAC;AAE/G,MAAM,kBAA8C,SAAQ,GAAc;IACxE,MAAM,CAAC,IAAO;QACZ,OAAO,KAAK,CAAC,M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;gBACL,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAuB,EAAE,KAAK,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;aACzF;SACF;IACH,CAAC;IAED,QAAQ;QACN,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3D,CAAC;CACF;AAlBD,oEAkBC;AAED,kBAAe,gBAAgB,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb-connection-string-url/lib/redact.d.ts b/nodejs/node_modules/mongodb-connection-string-url/lib/redact.d.ts new file mode 100644 index 00000000..94a64def --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/lib/redact.d.ts @@ -0,0 +1,7 @@ +import ConnectionString from './index'; +export interface ConnectionStringRedactionOptions { + redactUsernames?: boolean; + replacementString?: string; +} +export declare function redactValidConnectionString(inputUrl: Readonly, options?: ConnectionStringRedactionOptions): ConnectionString; +export declare function redactConnectionString(uri: string, options?: ConnectionStringRedactionOptions): string; diff --git a/nodejs/node_modules/mongodb-connection-string-url/lib/redact.js b/nodejs/node_modules/mongodb-connection-string-url/lib/redact.js new file mode 100644 index 00000000..62c7ba71 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/lib/redact.js @@ -0,0 +1,86 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.redactConnectionString = exports.redactValidConnectionString = void 0; +const index_1 = __importStar(require("./index")); +function redactValidConnectionString(inputUrl, options) { + var _a, _b; + const url = inputUrl.clone(); + const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : '_credentials_'; + const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; + if ((url.username || url.password) && redactUsernames) { + url.username = replacementString; + url.password = ''; + } + else if (url.password) { + url.password = replacementString; + } + if (url.searchParams.has('authMechanismProperties')) { + const props = new index_1.CommaAndColonSeparatedRecord(url.searchParams.get('authMechanismProperties')); + if (props.get('AWS_SESSION_TOKEN')) { + props.set('AWS_SESSION_TOKEN', replacementString); + url.searchParams.set('authMechanismProperties', props.toString()); + } + } + if (url.searchParams.has('tlsCertificateKeyFilePassword')) { + url.searchParams.set('tlsCertificateKeyFilePassword', replacementString); + } + if (url.searchParams.has('proxyUsername') && redactUsernames) { + url.searchParams.set('proxyUsername', replacementString); + } + if (url.searchParams.has('proxyPassword')) { + url.searchParams.set('proxyPassword', replacementString); + } + return url; +} +exports.redactValidConnectionString = redactValidConnectionString; +function redactConnectionString(uri, options) { + var _a, _b; + const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : ''; + const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; + let parsed; + try { + parsed = new index_1.default(uri); + } + catch (_c) { } + if (parsed) { + options = { ...options, replacementString: '___credentials___' }; + return parsed.redact(options).toString().replace(/___credentials___/g, replacementString); + } + const R = replacementString; + const replacements = [ + uri => uri.replace(redactUsernames ? /(\/\/)(.*)(@)/g : /(\/\/[^@]*:)(.*)(@)/g, `$1${R}$3`), + uri => uri.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, `$1${R}`), + uri => uri.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi, `$1${R}`), + uri => redactUsernames ? uri.replace(/(proxyUsername=)([^&]+)/gi, `$1${R}`) : uri, + uri => uri.replace(/(proxyPassword=)([^&]+)/gi, `$1${R}`) + ]; + for (const replacer of replacements) { + uri = replacer(uri); + } + return uri; +} +exports.redactConnectionString = redactConnectionString; +//# sourceMappingURL=redact.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb-connection-string-url/lib/redact.js.map b/nodejs/node_modules/mongodb-connection-string-url/lib/redact.js.map new file mode 100644 index 00000000..24a282b9 --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/lib/redact.js.map @@ -0,0 +1 @@ +{"version":3,"file":"redact.js","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAyE;AAOzE,SAAgB,2BAA2B,CACzC,QAAoC,EACpC,OAA0C;;IAC1C,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;IAC7B,MAAM,iBAAiB,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB,mCAAI,eAAe,CAAC;IACxE,MAAM,eAAe,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,eAAe,mCAAI,IAAI,CAAC;IAEzD,IAAI,CAAC,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,eAAe,EAAE;QACrD,GAAG,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QACjC,GAAG,CAAC,QAAQ,GAAG,EAAE,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I,IAAI,CAAC;IAEzD,IAAI,MAAoC,CAAC;IACzC,IAAI;QACF,MAAM,GAAG,IAAI,eAAgB,CAAC,GAAG,CAAC,CAAC;KACpC;IAAC,WAAM,GAAE;IACV,IAAI,MAAM,EAAE;QAGV,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,CAAC;QACjE,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,oBAAoB,EAAE,iBAAiB,CAAC,CAAC;KAC3F;IAID,MAAM,CAAC,GAAG,iBAAiB,CAAC;IAC5B,MAAM,YAAY,GAAgC;QAEhD,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,sBAAsB,EAAE,KAAK,CAAC,IAAI,CAAC;QAE3F,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,sCAAsC,EAAE,KAAK,CAAC,EAAE,CAAC;QAEpE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,2CAA2C,EAAE,KAAK,CAAC,EAAE,CAAC;QAEzE,GAAG,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,2BAA2B,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG;QAEjF,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,2BAA2B,EAAE,KAAK,CAAC,EAAE,CAAC;KAC1D,CAAC;IACF,KAAK,MAAM,QAAQ,IAAI,YAAY,EAAE;QACnC,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;KACrB;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AApCD,wDAoCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb-connection-string-url/package.json b/nodejs/node_modules/mongodb-connection-string-url/package.json new file mode 100644 index 00000000..457eadce --- /dev/null +++ b/nodejs/node_modules/mongodb-connection-string-url/package.json @@ -0,0 +1,62 @@ +{ + "name": "mongodb-connection-string-url", + "version": "3.0.0", + "description": "MongoDB connection strings, based on the WhatWG URL API", + "keywords": [ + "password", + "prompt", + "tty" + ], + "homepage": "https://github.com/mongodb-js/mongodb-connection-string-url", + "repository": { + "type": "git", + "url": "https://github.com/mongodb-js/mongodb-connection-string-url.git" + }, + "bugs": { + "url": "https://github.com/mongodb-js/mongodb-connection-string-url/issues" + }, + "main": "lib/index.js", + "exports": { + "require": "./lib/index.js", + "import": "./.esm-wrapper.mjs" + }, + "files": [ + "LICENSE", + "lib", + "package.json", + "README.md", + ".esm-wrapper.mjs" + ], + "scripts": { + "lint": "eslint \"{src,test}/**/*.ts\"", + "test": "npm run lint && npm run build && nyc mocha --colors -r ts-node/register test/*.ts", + "build": "npm run compile-ts && gen-esm-wrapper . ./.esm-wrapper.mjs", + "prepack": "npm run build", + "compile-ts": "tsc -p tsconfig.json" + }, + "license": "Apache-2.0", + "devDependencies": { + "@types/chai": "^4.2.5", + "@types/mocha": "^8.0.3", + "@types/node": "^14.11.1", + "@typescript-eslint/eslint-plugin": "^4.2.0", + "@typescript-eslint/parser": "^4.2.0", + "chai": "^4.2.0", + "eslint": "^7.9.0", + "eslint-config-semistandard": "^15.0.1", + "eslint-config-standard": "^14.1.1", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^4.2.1", + "eslint-plugin-standard": "^4.0.1", + "gen-esm-wrapper": "^1.1.3", + "mocha": "^8.1.3", + "nyc": "^15.1.0", + "ts-node": "^10.9.1", + "typescript": "^4.7.4" + }, + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } +} diff --git a/nodejs/node_modules/mongodb/LICENSE.md b/nodejs/node_modules/mongodb/LICENSE.md new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/nodejs/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/README.md b/nodejs/node_modules/mongodb/README.md new file mode 100644 index 00000000..d58a969e --- /dev/null +++ b/nodejs/node_modules/mongodb/README.md @@ -0,0 +1,323 @@ +# MongoDB Node.js Driver + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. + +**Upgrading to version 6? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_6.0.0.md)!** + +## Quick Links + +| Site | Link | +| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | +| Documentation | [www.mongodb.com/docs/drivers/node](https://www.mongodb.com/docs/drivers/node) | +| API Docs | [mongodb.github.io/node-mongodb-native](https://mongodb.github.io/node-mongodb-native) | +| `npm` package | [www.npmjs.com/package/mongodb](https://www.npmjs.com/package/mongodb) | +| MongoDB | [www.mongodb.com](https://www.mongodb.com) | +| MongoDB University | [learn.mongodb.com](https://learn.mongodb.com/catalog?labels=%5B%22Language%22%5D&values=%5B%22Node.js%22%5D) | +| MongoDB Developer Center | [www.mongodb.com/developer](https://www.mongodb.com/developer/languages/javascript/) | +| Stack Overflow | [stackoverflow.com](https://stackoverflow.com/search?q=%28%5Btypescript%5D+or+%5Bjavascript%5D+or+%5Bnode.js%5D%29+and+%5Bmongodb%5D) | +| Source Code | [github.com/mongodb/node-mongodb-native](https://github.com/mongodb/node-mongodb-native) | +| Upgrade to v6 | [etc/notes/CHANGES_6.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_6.0.0.md) | +| Contributing | [CONTRIBUTING.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTING.md) | +| Changelog | [HISTORY.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md) | + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a +case in our issue management tool, JIRA: + +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Support / Feedback + +For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://www.mongodb.com/docs/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver). + +### Change Log + +Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md). + +### Compatibility + +For server and runtime version compatibility matrices, please refer to the following links: + +- [MongoDB](https://www.mongodb.com/docs/drivers/node/current/compatibility/#mongodb-compatibility) +- [NodeJS](https://www.mongodb.com/docs/drivers/node/current/compatibility/#language-compatibility) + +#### Component Support Matrix + +The following table describes add-on component version compatibility for the Node.js driver. Only packages with versions in these supported ranges are stable when used in combination. + +| Component | `mongodb@3.x` | `mongodb@4.x` | `mongodb@5.x` | `mongodb@6.x` | +| ------------------------------------------------------------------------------------ | ------------------ | ------------------ | ------------------ | ------------- | +| [bson](https://www.npmjs.com/package/bson) | ^1.0.0 | ^4.0.0 | ^5.0.0 | ^6.0.0 | +| [bson-ext](https://www.npmjs.com/package/bson-ext) | ^1.0.0 \|\| ^2.0.0 | ^4.0.0 | N/A | N/A | +| [kerberos](https://www.npmjs.com/package/kerberos) | ^1.0.0 | ^1.0.0 \|\| ^2.0.0 | ^1.0.0 \|\| ^2.0.0 | ^2.0.1 | +| [mongodb-client-encryption](https://www.npmjs.com/package/mongodb-client-encryption) | ^1.0.0 | ^1.0.0 \|\| ^2.0.0 | ^2.3.0 | ^6.0.0 | +| [mongodb-legacy](https://www.npmjs.com/package/mongodb-legacy) | N/A | ^4.0.0 | ^5.0.0 | ^6.0.0 | +| [@mongodb-js/zstd](https://www.npmjs.com/package/@mongodb-js/zstd) | N/A | ^1.0.0 | ^1.0.0 | ^1.1.0 | + +#### Typescript Version + +We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against `typescript@4.1.6`. +This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk. +Since typescript [does not restrict breaking changes to major versions](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes) we consider this support best effort. +If you run into any unexpected compiler failures against our supported TypeScript versions please let us know by filing an issue on our [JIRA](https://jira.mongodb.org/browse/NODE). + +## Installation + +The recommended way to get started using the Node.js 5.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +After you've created your own project using `npm init`, you can run: + +```bash +npm install mongodb +# or ... +yarn add mongodb +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions: + +```sh +npm install -D @types/node +``` + +## Driver Extensions + +The MongoDB driver can optionally be enhanced by the following feature packages: + +Maintained by MongoDB: + +- Zstd network compression - [@mongodb-js/zstd](https://github.com/mongodb-js/zstd) +- MongoDB field level and queryable encryption - [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme) +- GSSAPI / SSPI / Kerberos authentication - [kerberos](https://github.com/mongodb-js/kerberos) + +Some of these packages include native C++ extensions. +Consult the [trouble shooting guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/native-extensions.md) if you run into compilation issues. + +Third party: + +- Snappy network compression - [snappy](https://github.com/Brooooooklyn/snappy) +- AWS authentication - [@aws-sdk/credential-providers](https://github.com/aws/aws-sdk-js-v3/tree/main/packages/credential-providers) + +## Quick Start + +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [official documentation](https://www.mongodb.com/docs/drivers/node/). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myProject +cd myProject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init -y +``` + +Next, install the driver as a dependency. + +```bash +npm install mongodb +``` + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://www.mongodb.com/docs/manual/installation/). + +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a `mongod` process. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myProject**: + +> **NOTE:** Resolving DNS Connection issues +> +> Node.js 18 changed the default DNS resolution ordering from always prioritizing ipv4 to the ordering +> returned by the DNS provider. In some environments, this can result in `localhost` resolving to +> an ipv6 address instead of ipv4 and a consequent failure to connect to the server. +> +> This can be resolved by: +> +> - specifying the ip address family using the MongoClient `family` option (`MongoClient(, { family: 4 } )`) +> - launching mongod or mongos with the ipv6 flag enabled ([--ipv6 mongod option documentation](https://www.mongodb.com/docs/manual/reference/program/mongod/#std-option-mongod.--ipv6)) +> - using a host of `127.0.0.1` in place of localhost +> - specifying the DNS resolution ordering with the `--dns-resolution-order` Node.js command line argument (e.g. `node --dns-resolution-order=ipv4first`) + +```js +const { MongoClient } = require('mongodb'); +// or as an es module: +// import { MongoClient } from 'mongodb' + +// Connection URL +const url = 'mongodb://localhost:27017'; +const client = new MongoClient(url); + +// Database Name +const dbName = 'myProject'; + +async function main() { + // Use connect method to connect to the server + await client.connect(); + console.log('Connected successfully to server'); + const db = client.db(dbName); + const collection = db.collection('documents'); + + // the following code examples can be pasted here... + + return 'done.'; +} + +main() + .then(console.log) + .catch(console.error) + .finally(() => client.close()); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]); +console.log('Inserted documents =>', insertResult); +``` + +The **insertMany** command returns an object with information about the insert operations. + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findResult = await collection.find({}).toArray(); +console.log('Found documents =>', findResult); +``` + +This query returns all the documents in the **documents** collection. +If you add this below the insertMany example you'll see the document's you've inserted. + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const filteredDocs = await collection.find({ a: 3 }).toArray(); +console.log('Found documents filtered by { a: 3 } =>', filteredDocs); +``` + +Only the documents which match `'a' : 3` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } }); +console.log('Updated documents =>', updateResult); +``` + +The method updates the first document where the field **a** is equal to **3** by adding a new field **b** to the document set to **1**. `updateResult` contains information about whether there was a matching document to update or not. + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const deleteResult = await collection.deleteMany({ a: 3 }); +console.log('Deleted documents =>', deleteResult); +``` + +### Index a Collection + +[Indexes](https://www.mongodb.com/docs/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. + +```js +const indexName = await collection.createIndex({ a: 1 }); +console.log('index name =', indexName); +``` + +For more detailed information, see the [indexing strategies page](https://www.mongodb.com/docs/manual/applications/indexes/). + +## Error Handling + +If you need to filter certain errors from our driver we have a helpful tree of errors described in [etc/notes/errors.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/errors.md). + +It is our recommendation to use `instanceof` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. +We guarantee `instanceof` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors. + +Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. +This means `instanceof` will always be able to accurately capture the errors that our driver throws. + +```typescript +const client = new MongoClient(url); +await client.connect(); +const collection = client.db().collection('collection'); + +try { + await collection.insertOne({ _id: 1 }); + await collection.insertOne({ _id: 1 }); // duplicate key error +} catch (error) { + if (error instanceof MongoServerError) { + console.log(`Error worth logging: ${error}`); // special case for some reason + } + throw error; // still want to crash +} +``` + +## Nightly releases + +If you need to test with a change from the latest `main` branch our `mongodb` npm package has nightly versions released under the `nightly` tag. + +```sh +npm install mongodb@nightly +``` + +Nightly versions are published regardless of testing outcome. +This means there could be sematic breakages or partially implemented features. +The nightly build is not suitable for production use. + +## Next Steps + +- [MongoDB Documentation](https://www.mongodb.com/docs/manual/) +- [MongoDB Node Driver Documentation](https://www.mongodb.com/docs/drivers/node/) +- [Read about Schemas](https://www.mongodb.com/docs/manual/core/data-modeling-introduction/) +- [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) + +## License + +[Apache 2.0](LICENSE.md) + +© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTORS.md) \ +© 2009-2012 Christian Amor Kvalheim diff --git a/nodejs/node_modules/mongodb/etc/prepare.js b/nodejs/node_modules/mongodb/etc/prepare.js new file mode 100755 index 00000000..2039d0b3 --- /dev/null +++ b/nodejs/node_modules/mongodb/etc/prepare.js @@ -0,0 +1,12 @@ +#! /usr/bin/env node +var cp = require('child_process'); +var fs = require('fs'); +var os = require('os'); + +if (fs.existsSync('src')) { + cp.spawn('npm', ['run', 'build:dts'], { stdio: 'inherit', shell: os.platform() === 'win32' }); +} else { + if (!fs.existsSync('lib')) { + console.warn('MongoDB: No compiled javascript present, the driver is not installed correctly.'); + } +} diff --git a/nodejs/node_modules/mongodb/lib/admin.js b/nodejs/node_modules/mongodb/lib/admin.js new file mode 100644 index 00000000..bab543b9 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/admin.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Admin = void 0; +const bson_1 = require("./bson"); +const execute_operation_1 = require("./operations/execute_operation"); +const list_databases_1 = require("./operations/list_databases"); +const remove_user_1 = require("./operations/remove_user"); +const run_command_1 = require("./operations/run_command"); +const validate_collection_1 = require("./operations/validate_collection"); +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +class Admin { + /** + * Create a new Admin instance + * @internal + */ + constructor(db) { + this.s = { db }; + } + /** + * Execute a command + * + * The driver will ensure the following fields are attached to the command sent to the server: + * - `lsid` - sourced from an implicit session or options.session + * - `$readPreference` - defaults to primary or can be configured by options.readPreference + * - `$db` - sourced from the name of this database + * + * If the client has a serverApi setting: + * - `apiVersion` + * - `apiStrict` + * - `apiDeprecationErrors` + * + * When in a transaction: + * - `readConcern` - sourced from readConcern set on the TransactionOptions + * - `writeConcern` - sourced from writeConcern set on the TransactionOptions + * + * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. + * + * @param command - The command to execute + * @param options - Optional settings for the command + */ + async command(command, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunAdminCommandOperation(command, { + ...(0, bson_1.resolveBSONOptions)(options), + session: options?.session, + readPreference: options?.readPreference + })); + } + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async buildInfo(options) { + return this.command({ buildinfo: 1 }, options); + } + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async serverInfo(options) { + return this.command({ buildinfo: 1 }, options); + } + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + async serverStatus(options) { + return this.command({ serverStatus: 1 }, options); + } + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + async ping(options) { + return this.command({ ping: 1 }, options); + } + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: 'admin', ...options })); + } + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + async validateCollection(collectionName, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options)); + } + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + async listDatabases(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, options)); + } + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + async replSetGetStatus(options) { + return this.command({ replSetGetStatus: 1 }, options); + } +} +exports.Admin = Admin; +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/admin.js.map b/nodejs/node_modules/mongodb/lib/admin.js.map new file mode 100644 index 00000000..939b4b49 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/admin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":";;;AAAA,iCAA2D;AAG3D,sEAAkE;AAClE,gEAIqC;AACrC,0DAAuF;AACvF,0DAA4F;AAC5F,0EAG0C;AAO1C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,KAAK;IAIhB;;;OAGG;IACH,YAAY,EAAM;QAChB,IAAI,CAAC,CAAC,GA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AM,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC,CAC9E,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,kBAAkB,CACtB,cAAsB,EACtB,UAAqC,EAAE;QAEvC,OAAO,IAAA,oCAAgB,EACrB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,EAChB,IAAI,iDAA2B,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,CAAC,CAC/D,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,aAAa,CAAC,OAA8B;QAChD,OAAO,IAAA,oCAAgB,EAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,EAAE,IAAI,uCAAsB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAC5F,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,gBAAgB,CAAC,OAAiC;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;CACF;AA/HD,sBA+HC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bson.js b/nodejs/node_modules/mongodb/lib/bson.js new file mode 100644 index 00000000..53e805b5 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bson.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.UUID = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.EJSON = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSON = exports.Binary = void 0; +var bson_1 = require("bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_1.Binary; } }); +Object.defineProperty(exports, "BSON", { enumerable: true, get: function () { return bson_1.BSON; } }); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return bson_1.BSONRegExp; } }); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return bson_1.BSONSymbol; } }); +Object.defineProperty(exports, "BSONType", { enumerable: true, get: function () { return bson_1.BSONType; } }); +Object.defineProperty(exports, "calculateObjectSize", { enumerable: true, get: function () { return bson_1.calculateObjectSize; } }); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return bson_1.Code; } }); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return bson_1.DBRef; } }); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return bson_1.Decimal128; } }); +Object.defineProperty(exports, "deserialize", { enumerable: true, get: function () { return bson_1.deserialize; } }); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return bson_1.Double; } }); +Object.defineProperty(exports, "EJSON", { enumerable: true, get: function () { return bson_1.EJSON; } }); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return bson_1.Int32; } }); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return bson_1.Long; } }); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return bson_1.MaxKey; } }); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return bson_1.MinKey; } }); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return bson_1.ObjectId; } }); +Object.defineProperty(exports, "serialize", { enumerable: true, get: function () { return bson_1.serialize; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_1.Timestamp; } }); +Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return bson_1.UUID; } }); +function pluckBSONSerializeOptions(options) { + const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options; + return { + fieldsAsRaw, + useBigInt64, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + }; +} +exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions; +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +function resolveBSONOptions(options, parent) { + const parentOptions = parent?.bsonOptions; + return { + raw: options?.raw ?? parentOptions?.raw ?? false, + useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? false, + promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, + promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, + promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, + ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, + bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, + serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, + fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {}, + enableUtf8Validation: options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true + }; +} +exports.resolveBSONOptions = resolveBSONOptions; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bson.js.map b/nodejs/node_modules/mongodb/lib/bson.js.map new file mode 100644 index 00000000..90fc867b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;AAEA,6BAuBc;AAtBZ,8FAAA,MAAM,OAAA;AACN,4FAAA,IAAI,OAAA;AACJ,kGAAA,UAAU,OAAA;AACV,kGAAA,UAAU,OAAA;AACV,gGAAA,QAAQ,OAAA;AACR,2GAAA,mBAAmB,OAAA;AACnB,4FAAA,IAAI,OAAA;AACJ,6FAAA,KAAK,OAAA;AACL,kGAAA,UAAU,OAAA;AACV,mGAAA,WAAW,OAAA;A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;QACrE,kBAAkB,EAAE,OAAO,EAAE,kBAAkB,IAAI,aAAa,EAAE,kBAAkB,IAAI,KAAK;QAC7F,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,aAAa,EAAE,WAAW,IAAI,EAAE;QACrE,oBAAoB,EAClB,OAAO,EAAE,oBAAoB,IAAI,aAAa,EAAE,oBAAoB,IAAI,IAAI;KAC/E,CAAC;AACJ,CAAC;AAlBD,gDAkBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bulk/common.js b/nodejs/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 00000000..92594fb2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,867 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkOperationBase = exports.BulkWriteShimOperation = exports.FindOperators = exports.MongoBulkWriteError = exports.mergeBatchResults = exports.WriteError = exports.WriteConcernError = exports.BulkWriteResult = exports.Batch = exports.BatchType = void 0; +const util_1 = require("util"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const common_functions_1 = require("../operations/common_functions"); +const delete_1 = require("../operations/delete"); +const execute_operation_1 = require("../operations/execute_operation"); +const insert_1 = require("../operations/insert"); +const operation_1 = require("../operations/operation"); +const update_1 = require("../operations/update"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +/** @internal */ +const kServerError = Symbol('serverError'); +/** @public */ +exports.BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +}); +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} +exports.Batch = Batch; +/** + * @public + * The result of a bulk write. + */ +class BulkWriteResult { + static generateIdMap(ids) { + const idMap = {}; + for (const doc of ids) { + idMap[doc.index] = doc._id; + } + return idMap; + } + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult, isOrdered) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap(this.getSuccessfullyInsertedIds(bulkResult, isOrdered)); + Object.defineProperty(this, 'result', { value: this.result, enumerable: false }); + } + /** Evaluates to true if the bulk operation correctly executes */ + get ok() { + return this.result.ok; + } + /** + * Returns document_ids that were actually inserted + * @internal + */ + getSuccessfullyInsertedIds(bulkResult, isOrdered) { + if (bulkResult.writeErrors.length === 0) + return bulkResult.insertedIds; + if (isOrdered) { + return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index); + } + return bulkResult.insertedIds.filter(({ index }) => !bulkResult.writeErrors.some(writeError => index === writeError.index)); + } + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + /** Returns raw internal result */ + getRawResponse() { + return this.result; + } + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + /** Returns a specific write error object */ + getWriteErrorAt(index) { + return index < this.result.writeErrors.length ? this.result.writeErrors[index] : undefined; + } + /** Retrieve all write errors */ + getWriteErrors() { + return this.result.writeErrors; + } + /** Retrieve the write concern error if one exists */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return; + } + else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } + else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + // TODO: Something better + if (i === 0) + errmsg = errmsg + ' and '; + } + return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernFailed }); + } + } + toString() { + return `BulkWriteResult(${this.result})`; + } + isOk() { + return this.result.ok === 1; + } +} +exports.BulkWriteResult = BulkWriteResult; +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +class WriteConcernError { + constructor(error) { + this[kServerError] = error; + } + /** Write concern error code. */ + get code() { + return this[kServerError].code; + } + /** Write concern error message. */ + get errmsg() { + return this[kServerError].errmsg; + } + /** Write concern error info. */ + get errInfo() { + return this[kServerError].errInfo; + } + toJSON() { + return this[kServerError]; + } + toString() { + return `WriteConcernError(${this.errmsg})`; + } +} +exports.WriteConcernError = WriteConcernError; +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +class WriteError { + constructor(err) { + this.err = err; + } + /** WriteError code. */ + get code() { + return this.err.code; + } + /** WriteError original bulk operation index. */ + get index() { + return this.err.index; + } + /** WriteError message. */ + get errmsg() { + return this.err.errmsg; + } + /** WriteError details. */ + get errInfo() { + return this.err.errInfo; + } + /** Returns the underlying operation that caused the error */ + getOperation() { + return this.err.op; + } + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} +exports.WriteError = WriteError; +/** Merges results into shared data structure */ +function mergeBatchResults(batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } + else if (result && result.result) { + result = result.result; + } + if (result == null) { + return; + } + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } + else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + // If we have an insert Batch type + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + let nUpserted = 0; + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } + else if (result.upserted) { + nUpserted = 1; + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + // If we have an update Batch type + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } + else { + bulkResult.nModified = 0; + } + } + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} +exports.mergeBatchResults = mergeBatchResults; +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return callback(undefined, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered)); + } + const batch = bulkOperation.s.batches.shift(); + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, return early + if (err && 'message' in err && !(err instanceof error_1.MongoWriteConcernError)) { + return callback(new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered))); + } + if (err instanceof error_1.MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, bulkOperation.isOrdered, err, callback); + } + // Merge the results together + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); + if (bulkOperation.handleWriteError(callback, writeResult)) + return; + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); + } + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); + } + } + try { + const operation = isInsertBatch(batch) + ? new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions) + : isUpdateBatch(batch) + ? new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions) + : isDeleteBatch(batch) + ? new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions) + : null; + if (operation != null) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, operation).then(result => resultHandler(undefined, result), error => resultHandler(error)); + } + } + catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} +function handleMongoWriteConcernError(batch, bulkResult, isOrdered, err, callback) { + mergeBatchResults(batch, bulkResult, undefined, err.result); + callback(new MongoBulkWriteError({ + message: err.result?.writeConcernError.errmsg, + code: err.result?.writeConcernError.result + }, new BulkWriteResult(bulkResult, isOrdered))); +} +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +class MongoBulkWriteError extends error_1.MongoServerError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(error, result) { + super(error); + this.writeErrors = []; + if (error instanceof WriteConcernError) + this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = error.writeErrors ?? []; + } + this.result = result; + Object.assign(this, error); + } + get name() { + return 'MongoBulkWriteError'; + } + /** Number of documents inserted. */ + get insertedCount() { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount() { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount() { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount() { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount() { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + return this.result.upsertedIds; + } +} +exports.MongoBulkWriteError = MongoBulkWriteError; +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +class FindOperators { + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation) { + this.bulkOperation = bulkOperation; + } + /** Add a multiple update operation to the bulk operation */ + update(updateDocument) { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + })); + } + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument) { + if (!(0, utils_1.hasAtomicOperators)(updateDocument)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false })); + } + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement) { + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false })); + } + /** Add a delete one operation to the bulk operation */ + deleteOne() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 })); + } + /** Add a delete many operation to the bulk operation */ + delete() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 })); + } + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert() { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + /** Specifies the collation for the query condition. */ + collation(collation) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } + /** Specifies hint for the bulk operation. */ + hint(hint) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.hint = hint; + return this; + } +} +exports.FindOperators = FindOperators; +const executeCommandsAsync = (0, util_1.promisify)(executeCommands); +/** + * TODO(NODE-4063) + * BulkWrites merge complexity is implemented in executeCommands + * This provides a vehicle to treat bulkOperations like any other operation (hence "shim") + * We would like this logic to simply live inside the BulkWriteOperation class + * @internal + */ +class BulkWriteShimOperation extends operation_1.AbstractOperation { + constructor(bulkOperation, options) { + super(options); + this.bulkOperation = bulkOperation; + } + get commandName() { + return 'bulkWrite'; + } + execute(_server, session) { + if (this.options.session == null) { + // An implicit session could have been created by 'executeOperation' + // So if we stick it on finalOptions here, each bulk operation + // will use this same session, it'll be passed in the same way + // an explicit session would be + this.options.session = session; + } + return executeCommandsAsync(this.bulkOperation, this.options); + } +} +exports.BulkWriteShimOperation = BulkWriteShimOperation; +/** @public */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(collection, options, isOrdered) { + this.collection = collection; + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + const topology = (0, utils_1.getTopology)(collection); + options = options == null ? {} : options; + // TODO Bring from driver information in hello + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + // Current item + const currentOp = undefined; + // Set max byte size + const hello = topology.lastHello(); + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000; + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + // Final options for retryable writes + let finalOptions = Object.assign({}, options); + finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.s.db); + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + // Internal state + this.s = { + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: (0, bson_1.resolveBSONOptions)(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false + }; + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + /** + * Add a single insert document to the bulk operation + * + * @example + * ```ts + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document) { + (0, common_functions_1.maybeAddIdToDocuments)(this.collection, document, { + forceServerObjectId: this.shouldForceServerObjectId() + }); + return this.addToOperationsList(exports.BatchType.INSERT, document); + } + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```ts + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector) { + if (!selector) { + throw new error_1.MongoInvalidArgumentError('Bulk find operation must specify a selector'); + } + // Save a current selector + this.s.currentOp = { + selector: selector + }; + return new FindOperators(this); + } + /** Specifies a raw operation to perform in the bulk write. */ + raw(op) { + if (op == null || typeof op !== 'object') { + throw new error_1.MongoInvalidArgumentError('Operation must be an object with an operation key'); + } + if ('insertOne' in op) { + const forceServerObjectId = this.shouldForceServerObjectId(); + const document = op.insertOne && op.insertOne.document == null + ? // TODO(NODE-6003): remove support for omitting the `documents` subdocument in bulk inserts + op.insertOne + : op.insertOne.document; + (0, common_functions_1.maybeAddIdToDocuments)(this.collection, document, { forceServerObjectId }); + return this.addToOperationsList(exports.BatchType.INSERT, document); + } + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); + if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + } + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); + } + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); + } + // otherwise an unknown operation was provided + throw new error_1.MongoInvalidArgumentError('bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany'); + } + get bsonOptions() { + return this.s.bsonOptions; + } + get writeConcern() { + return this.s.writeConcern; + } + get batches() { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) + batches.push(this.s.currentBatch); + } + else { + if (this.s.currentInsertBatch) + batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + batches.push(this.s.currentRemoveBatch); + } + return batches; + } + async execute(options = {}) { + if (this.s.executed) { + throw new error_1.MongoBatchReExecutionError(); + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) + this.s.batches.push(this.s.currentBatch); + } + else { + if (this.s.currentInsertBatch) + this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + throw new error_1.MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + } + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + const operation = new BulkWriteShimOperation(this, finalOptions); + return (0, execute_operation_1.executeOperation)(this.s.collection.client, operation); + } + /** + * Handles the write error before executing commands + * @internal + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + callback(new MongoBulkWriteError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, writeResult)); + return true; + } + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; + } + return false; + } + shouldForceServerObjectId() { + return (this.s.options.forceServerObjectId === true || + this.s.collection.s.db.options?.forceServerObjectId === true); + } +} +exports.BulkOperationBase = BulkOperationBase; +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); +function isInsertBatch(batch) { + return batch.batchType === exports.BatchType.INSERT; +} +function isUpdateBatch(batch) { + return batch.batchType === exports.BatchType.UPDATE; +} +function isDeleteBatch(batch) { + return batch.batchType === exports.BatchType.DELETE; +} +function buildCurrentOp(bulkOp) { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) + currentOp = {}; + return currentOp; +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bulk/common.js.map b/nodejs/node_modules/mongodb/lib/bulk/common.js.map new file mode 100644 index 00000000..b5802db4 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bulk/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/bulk/common.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AAEjC,kCAAuF;AAEvF,oCAOkB;AAGlB,qEAAuE;AACvE,iDAAkG;AAClG,uEAAmE;AACnE,iDAAuD;AACvD,uDAAuE;AACvE,iDAAkG;AAIlG,oCAOkB;AAClB,oDAAgD;AAEhD,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAE3C,cAAc;AACD,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC;IACrC,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;CACD,CAAC,CAAC;AA4GZ;;;;;GAKG;AACH,MAAa,KAAK;IAShB,YAAY,SAAoB,EAAE,iBAAyB;QACzD,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;QACd,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC;IACrB,CAAC;CACF;AAlBD,sBAkBC;AAED;;;GAGG;AACH,MAAa,eAAe;IAiBlB,MAAM,CAAC,aAAa,CAAC,GAAe;QAC1C,MAAM,KAAK,GAA6B,EAAE,CAAC;QAC3C,KAAK,MAAM,GAAG,IAAI,GAA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iBAAS,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAS,cAAc,CAAC,MAAyB;IAC/C,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC;IAC7B,MAAM,CAAC,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,IAAI,CAAC,SAAS;QAAE,SAAS,GAAG,EAAE,CAAC;IAC/B,OAAO,SAAS,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bulk/ordered.js b/nodejs/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 00000000..667f724f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OrderedBulkOperation = void 0; +const BSON = require("../bson"); +const error_1 = require("../error"); +const common_1 = require("./common"); +/** @public */ +class OrderedBulkOperation extends common_1.BulkOperationBase { + /** @internal */ + constructor(collection, options) { + super(collection, options, true); + } + addToOperationsList(batchType, document) { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + const maxKeySize = this.s.maxKeySize; + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + if (batchType === common_1.BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: document._id + }); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; + } +} +exports.OrderedBulkOperation = OrderedBulkOperation; +//# sourceMappingURL=ordered.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bulk/ordered.js.map b/nodejs/node_modules/mongodb/lib/bulk/ordered.js.map new file mode 100644 index 00000000..7f8fde0d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bulk/ordered.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ordered.js","sourceRoot":"","sources":["../../src/bulk/ordered.ts"],"names":[],"mappings":";;;AACA,gCAAgC;AAEhC,oCAAqD;AAGrD,qCAAsF;AAEtF,cAAc;AACd,MAAa,oBAAqB,SAAQ,0BAAiB;IACzD,gBAAgB;IAChB,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,mBAAmB,CACjB,SAAoB,EACpB,QAAsD;QAEtD,mBAAmB;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE;YAClD,SAAS,EAAE,KAAK;YAChB,oEAAoE;YACpE,wEAAwE;YACxE,eAAe,EAAE,KAAK;S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QAED,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YAClC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC;gBACjC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,YAAY;gBAC1B,GAAG,EAAG,QAAqB,CAAC,GAAG;aAChC,CAAC,CAAC;SACJ;QAED,gCAAgC;QAChC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC3B,MAAM,IAAI,iCAAyB,CAAC,wCAAwC,CAAC,CAAC;SAC/E;QAED,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QAC9D,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9C,IAAI,CAAC,CAAC,CAAC,gBAAgB,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,CAAC,CAAC,qBAAqB,IAAI,UAAU,GAAG,QAAQ,CAAC;QACtD,IAAI,CAAC,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAzED,oDAyEC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bulk/unordered.js b/nodejs/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 00000000..14b8f038 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnorderedBulkOperation = void 0; +const BSON = require("../bson"); +const error_1 = require("../error"); +const common_1 = require("./common"); +/** @public */ +class UnorderedBulkOperation extends common_1.BulkOperationBase { + /** @internal */ + constructor(collection, options) { + super(collection, options, false); + } + handleWriteError(callback, writeResult) { + if (this.s.batches.length) { + return false; + } + return super.handleWriteError(callback, writeResult); + } + addToOperationsList(batchType, document) { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + } + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === common_1.BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + const maxKeySize = this.s.maxKeySize; + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + // Save back the current Batch to the right type + if (batchType === common_1.BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: document._id + }); + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + return this; + } +} +exports.UnorderedBulkOperation = UnorderedBulkOperation; +//# sourceMappingURL=unordered.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/bulk/unordered.js.map b/nodejs/node_modules/mongodb/lib/bulk/unordered.js.map new file mode 100644 index 00000000..a510ddd8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/bulk/unordered.js.map @@ -0,0 +1 @@ +{"version":3,"file":"unordered.js","sourceRoot":"","sources":["../../src/bulk/unordered.ts"],"names":[],"mappings":";;;AACA,gCAAgC;AAEhC,oCAAqD;AAIrD,qCAMkB;AAElB,cAAc;AACd,MAAa,sBAAuB,SAAQ,0BAAiB;IAC3D,gBAAgB;IAChB,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACpC,CAAC;IAEQ,gBAAgB,CAAC,QAAkB,EAAE,WAA4B;QACxE,IAAI,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE;YACzB,OAAO,KAAK,CAAC;SACd;QAED,OAAO,KAAK,CAAC,gBAAgB,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IACvD,CAAC;IAED,mBAAmB,CACjB,SAAoB,EACpB,QAAsD;QAEtD,mBAAmB;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE;YAClD,SAAS,EAAE,KAAK;YAEhB,oEAAoE;YACpE,wEAAwE;YACxE,eAAe,EAAE,KAAK;SAChB,CAAC,CAAC;QAEV,0DAA0D;QAC1D,IAAI,QAAQ,IAAI,IAAI,C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D;aAAM,IAAI,SAAS,KAAK,kBAAS,CAAC,MAAM,EAAE;YACzC,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;SACjD;QAED,4BAA4B;QAC5B,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC,CAAC;QAC9B,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,IAAI,UAAU,GAAG,QAAQ,CAAC;QAEvD,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAnGD,wDAmGC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/change_stream.js b/nodejs/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 00000000..9c93183f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,399 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStream = void 0; +const collection_1 = require("./collection"); +const constants_1 = require("./constants"); +const change_stream_cursor_1 = require("./cursor/change_stream_cursor"); +const db_1 = require("./db"); +const error_1 = require("./error"); +const mongo_client_1 = require("./mongo_client"); +const mongo_types_1 = require("./mongo_types"); +const utils_1 = require("./utils"); +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); +const CHANGE_STREAM_OPTIONS = [ + 'resumeAfter', + 'startAfter', + 'startAtOperationTime', + 'fullDocument', + 'fullDocumentBeforeChange', + 'showExpandedEvents' +]; +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; +const CHANGE_STREAM_EVENTS = [constants_1.RESUME_TOKEN_CHANGED, constants_1.END, constants_1.CLOSE]; +const NO_RESUME_TOKEN_ERROR = 'A change stream document has been received that lacks a resume token (_id).'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +class ChangeStream extends mongo_types_1.TypedEventEmitter { + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor(parent, pipeline = [], options = {}) { + super(); + this.pipeline = pipeline; + this.options = { ...options }; + delete this.options.writeConcern; + if (parent instanceof collection_1.Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } + else if (parent instanceof db_1.Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } + else if (parent instanceof mongo_client_1.MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } + else { + throw new error_1.MongoChangeStreamError('Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient'); + } + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + // Create contained Change Stream cursor + this.cursor = this._createChangeStreamCursor(options); + this[kClosed] = false; + this[kMode] = false; + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this._streamEvents(this.cursor); + } + }); + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this[kCursorStream]?.removeAllListeners('data'); + } + }); + } + /** @internal */ + get cursorStream() { + return this[kCursorStream]; + } + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken() { + return this.cursor?.resumeToken; + } + /** Check if there is any document still available in the Change Stream */ + async hasNext() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + /** Get the next available document from the Change Stream. */ + async next() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + async tryNext() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + async *[Symbol.asyncIterator]() { + if (this.closed) { + return; + } + try { + // Change streams run indefinitely as long as errors are resumable + // So the only loop breaking condition is if `next()` throws + while (true) { + yield await this.next(); + } + } + finally { + try { + await this.close(); + } + catch { + // we're not concerned with errors from close() + } + } + } + /** Is the cursor closed */ + get closed() { + return this[kClosed] || this.cursor.closed; + } + /** Close the Change Stream */ + async close() { + this[kClosed] = true; + const cursor = this.cursor; + try { + await cursor.close(); + } + finally { + this._endStream(); + } + } + /** + * Return a modified Readable stream including a possible transform method. + * + * NOTE: When using a Stream to process change stream events, the stream will + * NOT automatically resume in the case a resumable error is encountered. + * + * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed + */ + stream(options) { + if (this.closed) { + throw new error_1.MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR); + } + this.streamOptions = options; + return this.cursor.stream(options); + } + /** @internal */ + _setIsEmitter() { + if (this[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an EventEmitter after being used as an iterator'); + } + this[kMode] = 'emitter'; + } + /** @internal */ + _setIsIterator() { + if (this[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an iterator after being used as an EventEmitter'); + } + this[kMode] = 'iterator'; + } + /** + * Create a new change stream cursor based on self's configuration + * @internal + */ + _createChangeStreamCursor(options) { + const changeStreamStageOptions = (0, utils_1.filterOptions)(options, CHANGE_STREAM_OPTIONS); + if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; + const client = this.type === CHANGE_DOMAIN_TYPES.CLUSTER + ? this.parent + : this.type === CHANGE_DOMAIN_TYPES.DATABASE + ? this.parent.client + : this.type === CHANGE_DOMAIN_TYPES.COLLECTION + ? this.parent.client + : null; + if (client == null) { + // This should never happen because of the assertion in the constructor + throw new error_1.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`); + } + const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client, this.namespace, pipeline, options); + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => this.emit(event, e)); + } + if (this.listenerCount(ChangeStream.CHANGE) > 0) { + this._streamEvents(changeStreamCursor); + } + return changeStreamCursor; + } + /** @internal */ + _closeEmitterModeWithError(error) { + this.emit(ChangeStream.ERROR, error); + this.close().catch(() => null); + } + /** @internal */ + _streamEvents(cursor) { + this._setIsEmitter(); + const stream = this[kCursorStream] ?? cursor.stream(); + this[kCursorStream] = stream; + stream.on('data', change => { + try { + const processedChange = this._processChange(change); + this.emit(ChangeStream.CHANGE, processedChange); + } + catch (error) { + this.emit(ChangeStream.ERROR, error); + } + }); + stream.on('error', error => this._processErrorStreamMode(error)); + } + /** @internal */ + _endStream() { + const cursorStream = this[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + this[kCursorStream] = undefined; + } + /** @internal */ + _processChange(change) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR); + } + if (change && !change._id) { + throw new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR); + } + // cache the resume token + this.cursor.cacheResumeToken(change._id); + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + this.options.startAtOperationTime = undefined; + return change; + } + /** @internal */ + _processErrorStreamMode(changeStreamError) { + // If the change stream has been closed explicitly, do not process error. + if (this[kClosed]) + return; + if ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) { + this._endStream(); + this.cursor.close().catch(() => null); + const topology = (0, utils_1.getTopology)(this.parent); + topology.selectServer(this.cursor.readPreference, { operationName: 'reconnect topology in change stream' }, serverSelectionError => { + if (serverSelectionError) + return this._closeEmitterModeWithError(changeStreamError); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + }); + } + else { + this._closeEmitterModeWithError(changeStreamError); + } + } + /** @internal */ + async _processErrorIteratorMode(changeStreamError) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + if (!(0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) { + try { + await this.close(); + } + catch { + // ignore errors from close + } + throw changeStreamError; + } + await this.cursor.close().catch(() => null); + const topology = (0, utils_1.getTopology)(this.parent); + try { + await topology.selectServerAsync(this.cursor.readPreference, { + operationName: 'reconnect topology in change stream' + }); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } + catch { + // if the topology can't reconnect, close the stream + await this.close(); + throw changeStreamError; + } + } +} +/** @event */ +ChangeStream.RESPONSE = constants_1.RESPONSE; +/** @event */ +ChangeStream.MORE = constants_1.MORE; +/** @event */ +ChangeStream.INIT = constants_1.INIT; +/** @event */ +ChangeStream.CLOSE = constants_1.CLOSE; +/** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ +ChangeStream.CHANGE = constants_1.CHANGE; +/** @event */ +ChangeStream.END = constants_1.END; +/** @event */ +ChangeStream.ERROR = constants_1.ERROR; +/** + * Emitted each time the change stream stores a new resume token. + * @event + */ +ChangeStream.RESUME_TOKEN_CHANGED = constants_1.RESUME_TOKEN_CHANGED; +exports.ChangeStream = ChangeStream; +//# sourceMappingURL=change_stream.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/change_stream.js.map b/nodejs/node_modules/mongodb/lib/change_stream.js.map new file mode 100644 index 00000000..88687bbc --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/change_stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"change_stream.js","sourceRoot":"","sources":["../src/change_stream.ts"],"names":[],"mappings":";;;AAGA,6CAA0C;AAC1C,2CAAoG;AAEpG,wEAAmG;AACnG,6BAA0B;AAC1B,mCAMiB;AACjB,iDAA6C;AAC7C,+CAAoE;AAKpE,mCAA4E;AAE5E,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAC7C,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;AAE7B,MAAM,qBAAqB,GAAG;IAC5B,aAAa;IACb,YAAY;IACZ,sBAAsB;IACtB,cAAc;IACd,0BAA0B;IAC1B,oBAAoB;CACZ,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AAC;QAC1C,IAAI;YACF,MAAM,QAAQ,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE;gBAC3D,aAAa,EAAE,qCAAqC;aACrD,CAAC,CAAC;YACH,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,yBAAyB,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;SACzE;QAAC,MAAM;YACN,oDAAoD;YACpD,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;YACnB,MAAM,iBAAiB,CAAC;SACzB;IACH,CAAC;;AAtZD,aAAa;AACG,qBAAQ,GAAG,oBAAQ,CAAC;AACpC,aAAa;AACG,iBAAI,GAAG,gBAAI,CAAC;AAC5B,aAAa;AACG,iBAAI,GAAG,gBAAI,CAAC;AAC5B,aAAa;AACG,kBAAK,GAAG,iBAAK,CAAC;AAC9B;;;;;GAKG;AACa,mBAAM,GAAG,kBAAM,CAAC;AAChC,aAAa;AACG,gBAAG,GAAG,eAAG,CAAC;AAC1B,aAAa;AACG,kBAAK,GAAG,iBAAK,CAAC;AAC9B;;;GAGG;AACa,iCAAoB,GAAG,gCAAoB,CAAC;AAjDjD,oCAAY"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js new file mode 100644 index 00000000..9f10223b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js @@ -0,0 +1,307 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AutoEncrypter = exports.AutoEncryptionLoggerLevel = void 0; +const bson_1 = require("../bson"); +const deps_1 = require("../deps"); +const error_1 = require("../error"); +const mongo_client_1 = require("../mongo_client"); +const utils_1 = require("../utils"); +const cryptoCallbacks = require("./crypto_callbacks"); +const errors_1 = require("./errors"); +const mongocryptd_manager_1 = require("./mongocryptd_manager"); +const providers_1 = require("./providers"); +const state_machine_1 = require("./state_machine"); +/** @public */ +exports.AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +}); +// Typescript errors if we index objects with `Symbol.for(...)`, so +// to avoid TS errors we pull them out into variables. Then we can type +// the objects (and class) that we expect to see them on and prevent TS +// errors. +/** @internal */ +const kDecorateResult = Symbol.for('@@mdb.decorateDecryptionResult'); +/** @internal */ +const kDecoratedKeys = Symbol.for('@@mdb.decryptedKeys'); +/** + * @internal An internal class to be used by the driver for auto encryption + * **NOTE**: Not meant to be instantiated directly, this is for internal use only. + */ +class AutoEncrypter { + /** @internal */ + static getMongoCrypt() { + const encryption = (0, deps_1.getMongoDBClientEncryption)(); + if ('kModuleError' in encryption) { + throw encryption.kModuleError; + } + return encryption.MongoCrypt; + } + /** + * Create an AutoEncrypter + * + * **Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient + * + * **Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + * + * @example Create an AutoEncrypter that makes use of mongocryptd + * ```ts + * // Enabling autoEncryption via a MongoClient using mongocryptd + * const { MongoClient } = require('mongodb'); + * const client = new MongoClient(URL, { + * autoEncryption: { + * kmsProviders: { + * aws: { + * accessKeyId: AWS_ACCESS_KEY, + * secretAccessKey: AWS_SECRET_KEY + * } + * } + * } + * }); + * ``` + * + * await client.connect(); + * // From here on, the client will be encrypting / decrypting automatically + * @example Create an AutoEncrypter that makes use of libmongocrypt's CSFLE shared library + * ```ts + * // Enabling autoEncryption via a MongoClient using CSFLE shared library + * const { MongoClient } = require('mongodb'); + * const client = new MongoClient(URL, { + * autoEncryption: { + * kmsProviders: { + * aws: {} + * }, + * extraOptions: { + * cryptSharedLibPath: '/path/to/local/crypt/shared/lib', + * cryptSharedLibRequired: true + * } + * } + * }); + * ``` + * + * await client.connect(); + * // From here on, the client will be encrypting / decrypting automatically + */ + constructor(client, options) { + /** + * Used by devtools to enable decorating decryption results. + * + * When set and enabled, `decrypt` will automatically recursively + * traverse a decrypted document and if a field has been decrypted, + * it will mark it as decrypted. Compass uses this to determine which + * fields were decrypted. + */ + this[_a] = false; + this._client = client; + this._bypassEncryption = options.bypassAutoEncryption === true; + this._keyVaultNamespace = options.keyVaultNamespace || 'admin.datakeys'; + this._keyVaultClient = options.keyVaultClient || client; + this._metaDataClient = options.metadataClient || client; + this._proxyOptions = options.proxyOptions || {}; + this._tlsOptions = options.tlsOptions || {}; + this._kmsProviders = options.kmsProviders || {}; + const mongoCryptOptions = { + cryptoCallbacks + }; + if (options.schemaMap) { + mongoCryptOptions.schemaMap = Buffer.isBuffer(options.schemaMap) + ? options.schemaMap + : (0, bson_1.serialize)(options.schemaMap); + } + if (options.encryptedFieldsMap) { + mongoCryptOptions.encryptedFieldsMap = Buffer.isBuffer(options.encryptedFieldsMap) + ? options.encryptedFieldsMap + : (0, bson_1.serialize)(options.encryptedFieldsMap); + } + mongoCryptOptions.kmsProviders = !Buffer.isBuffer(this._kmsProviders) + ? (0, bson_1.serialize)(this._kmsProviders) + : this._kmsProviders; + if (options.options?.logger) { + mongoCryptOptions.logger = options.options.logger; + } + if (options.extraOptions && options.extraOptions.cryptSharedLibPath) { + mongoCryptOptions.cryptSharedLibPath = options.extraOptions.cryptSharedLibPath; + } + if (options.bypassQueryAnalysis) { + mongoCryptOptions.bypassQueryAnalysis = options.bypassQueryAnalysis; + } + this._bypassMongocryptdAndCryptShared = this._bypassEncryption || !!options.bypassQueryAnalysis; + if (options.extraOptions && options.extraOptions.cryptSharedLibSearchPaths) { + // Only for driver testing + mongoCryptOptions.cryptSharedLibSearchPaths = options.extraOptions.cryptSharedLibSearchPaths; + } + else if (!this._bypassMongocryptdAndCryptShared) { + mongoCryptOptions.cryptSharedLibSearchPaths = ['$SYSTEM']; + } + const MongoCrypt = AutoEncrypter.getMongoCrypt(); + this._mongocrypt = new MongoCrypt(mongoCryptOptions); + this._contextCounter = 0; + if (options.extraOptions && + options.extraOptions.cryptSharedLibRequired && + !this.cryptSharedLibVersionInfo) { + throw new errors_1.MongoCryptInvalidArgumentError('`cryptSharedLibRequired` set but no crypt_shared library loaded'); + } + // Only instantiate mongocryptd manager/client once we know for sure + // that we are not using the CSFLE shared library. + if (!this._bypassMongocryptdAndCryptShared && !this.cryptSharedLibVersionInfo) { + this._mongocryptdManager = new mongocryptd_manager_1.MongocryptdManager(options.extraOptions); + const clientOptions = { + serverSelectionTimeoutMS: 10000 + }; + if (options.extraOptions == null || typeof options.extraOptions.mongocryptdURI !== 'string') { + clientOptions.family = 4; + } + this._mongocryptdClient = new mongo_client_1.MongoClient(this._mongocryptdManager.uri, clientOptions); + } + } + /** + * Initializes the auto encrypter by spawning a mongocryptd and connecting to it. + * + * This function is a no-op when bypassSpawn is set or the crypt shared library is used. + */ + async init() { + if (this._bypassMongocryptdAndCryptShared || this.cryptSharedLibVersionInfo) { + return; + } + if (!this._mongocryptdManager) { + throw new error_1.MongoRuntimeError('Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified.'); + } + if (!this._mongocryptdClient) { + throw new error_1.MongoRuntimeError('Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified.'); + } + if (!this._mongocryptdManager.bypassSpawn) { + await this._mongocryptdManager.spawn(); + } + try { + const client = await this._mongocryptdClient.connect(); + return client; + } + catch (error) { + const { message } = error; + if (message && (message.match(/timed out after/) || message.match(/ENOTFOUND/))) { + throw new error_1.MongoRuntimeError('Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn', { cause: error }); + } + throw error; + } + } + /** + * Cleans up the `_mongocryptdClient`, if present. + */ + async teardown(force) { + await this._mongocryptdClient?.close(force); + } + /** + * Encrypt a command for a given namespace. + */ + async encrypt(ns, cmd, options = {}) { + if (this._bypassEncryption) { + // If `bypassAutoEncryption` has been specified, don't encrypt + return cmd; + } + const commandBuffer = Buffer.isBuffer(cmd) ? cmd : (0, bson_1.serialize)(cmd, options); + const context = this._mongocrypt.makeEncryptionContext(utils_1.MongoDBCollectionNamespace.fromString(ns).db, commandBuffer); + context.id = this._contextCounter++; + context.ns = ns; + context.document = cmd; + const stateMachine = new state_machine_1.StateMachine({ + promoteValues: false, + promoteLongs: false, + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + return stateMachine.execute(this, context); + } + /** + * Decrypt a command response + */ + async decrypt(response, options = {}) { + const buffer = Buffer.isBuffer(response) ? response : (0, bson_1.serialize)(response, options); + const context = this._mongocrypt.makeDecryptionContext(buffer); + context.id = this._contextCounter++; + const stateMachine = new state_machine_1.StateMachine({ + ...options, + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + const decorateResult = this[kDecorateResult]; + const result = await stateMachine.execute(this, context); + if (decorateResult) { + decorateDecryptionResult(result, response); + } + return result; + } + /** + * Ask the user for KMS credentials. + * + * This returns anything that looks like the kmsProviders original input + * option. It can be empty, and any provider specified here will override + * the original ones. + */ + async askForKMSCredentials() { + return (0, providers_1.refreshKMSCredentials)(this._kmsProviders); + } + /** + * Return the current libmongocrypt's CSFLE shared library version + * as `{ version: bigint, versionStr: string }`, or `null` if no CSFLE + * shared library was loaded. + */ + get cryptSharedLibVersionInfo() { + return this._mongocrypt.cryptSharedLibVersionInfo; + } + static get libmongocryptVersion() { + return AutoEncrypter.getMongoCrypt().libmongocryptVersion; + } +} +exports.AutoEncrypter = AutoEncrypter; +_a = kDecorateResult; +/** + * Recurse through the (identically-shaped) `decrypted` and `original` + * objects and attach a `decryptedKeys` property on each sub-object that + * contained encrypted fields. Because we only call this on BSON responses, + * we do not need to worry about circular references. + * + * @internal + */ +function decorateDecryptionResult(decrypted, original, isTopLevelDecorateCall = true) { + if (isTopLevelDecorateCall) { + // The original value could have been either a JS object or a BSON buffer + if (Buffer.isBuffer(original)) { + original = (0, bson_1.deserialize)(original); + } + if (Buffer.isBuffer(decrypted)) { + throw new error_1.MongoRuntimeError('Expected result of decryption to be deserialized BSON object'); + } + } + if (!decrypted || typeof decrypted !== 'object') + return; + for (const k of Object.keys(decrypted)) { + const originalValue = original[k]; + // An object was decrypted by libmongocrypt if and only if it was + // a BSON Binary object with subtype 6. + if (originalValue && originalValue._bsontype === 'Binary' && originalValue.sub_type === 6) { + if (!decrypted[kDecoratedKeys]) { + Object.defineProperty(decrypted, kDecoratedKeys, { + value: [], + configurable: true, + enumerable: false, + writable: false + }); + } + // this is defined in the preceding if-statement + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + decrypted[kDecoratedKeys].push(k); + // Do not recurse into this decrypted value. It could be a sub-document/array, + // in which case there is no original value associated with its subfields. + continue; + } + decorateDecryptionResult(decrypted[k], originalValue, false); + } +} +//# sourceMappingURL=auto_encrypter.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js.map new file mode 100644 index 00000000..04aab3f2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auto_encrypter.js","sourceRoot":"","sources":["../../src/client-side-encryption/auto_encrypter.ts"],"names":[],"mappings":";;;;AAMA,kCAAgE;AAEhE,kCAAqD;AACrD,oCAA6C;AAC7C,kDAAuE;AACvE,oCAAsD;AACtD,sDAAsD;AACtD,qCAA0D;AAC1D,+DAA2D;AAC3D,2CAAuE;AACvE,mDAAwE;AA8KxE,cAAc;AACD,QAAA,yBAAyB,GAAG,MAAM,CAAC,MAAM,CAAC;IACrD,UAAU,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;CACA,CAAC,CAAC;AAiBZ,m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,CAAC,CAAC;aACJ;YACD,gDAAgD;YAChD,oEAAoE;YACpE,SAAS,CAAC,cAAc,CAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACnC,8EAA8E;YAC9E,0EAA0E;YAC1E,SAAS;SACV;QAED,wBAAwB,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,CAAC,CAAC;KAC9D;AACH,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/client_encryption.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/client_encryption.js new file mode 100644 index 00000000..b88b03c1 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/client_encryption.js @@ -0,0 +1,555 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClientEncryption = void 0; +const bson_1 = require("../bson"); +const deps_1 = require("../deps"); +const utils_1 = require("../utils"); +const cryptoCallbacks = require("./crypto_callbacks"); +const errors_1 = require("./errors"); +const index_1 = require("./providers/index"); +const state_machine_1 = require("./state_machine"); +/** + * @public + * The public interface for explicit in-use encryption + */ +class ClientEncryption { + /** @internal */ + static getMongoCrypt() { + const encryption = (0, deps_1.getMongoDBClientEncryption)(); + if ('kModuleError' in encryption) { + throw encryption.kModuleError; + } + return encryption.MongoCrypt; + } + /** + * Create a new encryption instance + * + * @example + * ```ts + * new ClientEncryption(mongoClient, { + * keyVaultNamespace: 'client.encryption', + * kmsProviders: { + * local: { + * key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer + * } + * } + * }); + * ``` + * + * @example + * ```ts + * new ClientEncryption(mongoClient, { + * keyVaultNamespace: 'client.encryption', + * kmsProviders: { + * aws: { + * accessKeyId: AWS_ACCESS_KEY, + * secretAccessKey: AWS_SECRET_KEY + * } + * } + * }); + * ``` + */ + constructor(client, options) { + this._client = client; + this._proxyOptions = options.proxyOptions ?? {}; + this._tlsOptions = options.tlsOptions ?? {}; + this._kmsProviders = options.kmsProviders || {}; + if (options.keyVaultNamespace == null) { + throw new errors_1.MongoCryptInvalidArgumentError('Missing required option `keyVaultNamespace`'); + } + const mongoCryptOptions = { + ...options, + cryptoCallbacks, + kmsProviders: !Buffer.isBuffer(this._kmsProviders) + ? (0, bson_1.serialize)(this._kmsProviders) + : this._kmsProviders + }; + this._keyVaultNamespace = options.keyVaultNamespace; + this._keyVaultClient = options.keyVaultClient || client; + const MongoCrypt = ClientEncryption.getMongoCrypt(); + this._mongoCrypt = new MongoCrypt(mongoCryptOptions); + } + /** + * Creates a data key used for explicit encryption and inserts it into the key vault namespace + * + * @example + * ```ts + * // Using async/await to create a local key + * const dataKeyId = await clientEncryption.createDataKey('local'); + * ``` + * + * @example + * ```ts + * // Using async/await to create an aws key + * const dataKeyId = await clientEncryption.createDataKey('aws', { + * masterKey: { + * region: 'us-east-1', + * key: 'xxxxxxxxxxxxxx' // CMK ARN here + * } + * }); + * ``` + * + * @example + * ```ts + * // Using async/await to create an aws key with a keyAltName + * const dataKeyId = await clientEncryption.createDataKey('aws', { + * masterKey: { + * region: 'us-east-1', + * key: 'xxxxxxxxxxxxxx' // CMK ARN here + * }, + * keyAltNames: [ 'mySpecialKey' ] + * }); + * ``` + */ + async createDataKey(provider, options = {}) { + if (options.keyAltNames && !Array.isArray(options.keyAltNames)) { + throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but was of type ${typeof options.keyAltNames}.`); + } + let keyAltNames = undefined; + if (options.keyAltNames && options.keyAltNames.length > 0) { + keyAltNames = options.keyAltNames.map((keyAltName, i) => { + if (typeof keyAltName !== 'string') { + throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${i} was of type ${typeof keyAltName}`); + } + return (0, bson_1.serialize)({ keyAltName }); + }); + } + let keyMaterial = undefined; + if (options.keyMaterial) { + keyMaterial = (0, bson_1.serialize)({ keyMaterial: options.keyMaterial }); + } + const dataKeyBson = (0, bson_1.serialize)({ + provider, + ...options.masterKey + }); + const context = this._mongoCrypt.makeDataKeyContext(dataKeyBson, { + keyAltNames, + keyMaterial + }); + const stateMachine = new state_machine_1.StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + const dataKey = await stateMachine.execute(this, context); + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + const { insertedId } = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .insertOne(dataKey, { writeConcern: { w: 'majority' } }); + return insertedId; + } + /** + * Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options. + * + * If no matches are found, then no bulk write is performed. + * + * @example + * ```ts + * // rewrapping all data data keys (using a filter that matches all documents) + * const filter = {}; + * + * const result = await clientEncryption.rewrapManyDataKey(filter); + * if (result.bulkWriteResult != null) { + * // keys were re-wrapped, results will be available in the bulkWrite object. + * } + * ``` + * + * @example + * ```ts + * // attempting to rewrap all data keys with no matches + * const filter = { _id: new Binary() } // assume _id matches no documents in the database + * const result = await clientEncryption.rewrapManyDataKey(filter); + * + * if (result.bulkWriteResult == null) { + * // no keys matched, `bulkWriteResult` does not exist on the result object + * } + * ``` + */ + async rewrapManyDataKey(filter, options) { + let keyEncryptionKeyBson = undefined; + if (options) { + const keyEncryptionKey = Object.assign({ provider: options.provider }, options.masterKey); + keyEncryptionKeyBson = (0, bson_1.serialize)(keyEncryptionKey); + } + const filterBson = (0, bson_1.serialize)(filter); + const context = this._mongoCrypt.makeRewrapManyDataKeyContext(filterBson, keyEncryptionKeyBson); + const stateMachine = new state_machine_1.StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + const { v: dataKeys } = await stateMachine.execute(this, context); + if (dataKeys.length === 0) { + return {}; + } + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + const replacements = dataKeys.map((key) => ({ + updateOne: { + filter: { _id: key._id }, + update: { + $set: { + masterKey: key.masterKey, + keyMaterial: key.keyMaterial + }, + $currentDate: { + updateDate: true + } + } + } + })); + const result = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .bulkWrite(replacements, { + writeConcern: { w: 'majority' } + }); + return { bulkWriteResult: result }; + } + /** + * Deletes the key with the provided id from the keyvault, if it exists. + * + * @example + * ```ts + * // delete a key by _id + * const id = new Binary(); // id is a bson binary subtype 4 object + * const { deletedCount } = await clientEncryption.deleteKey(id); + * + * if (deletedCount != null && deletedCount > 0) { + * // successful deletion + * } + * ``` + * + */ + async deleteKey(_id) { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .deleteOne({ _id }, { writeConcern: { w: 'majority' } }); + } + /** + * Finds all the keys currently stored in the keyvault. + * + * This method will not throw. + * + * @returns a FindCursor over all keys in the keyvault. + * @example + * ```ts + * // fetching all keys + * const keys = await clientEncryption.getKeys().toArray(); + * ``` + */ + getKeys() { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .find({}, { readConcern: { level: 'majority' } }); + } + /** + * Finds a key in the keyvault with the specified _id. + * + * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // getting a key by id + * const id = new Binary(); // id is a bson binary subtype 4 object + * const key = await clientEncryption.getKey(id); + * if (!key) { + * // key is null if there was no matching key + * } + * ``` + */ + async getKey(_id) { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOne({ _id }, { readConcern: { level: 'majority' } }); + } + /** + * Finds a key in the keyvault which has the specified keyAltName. + * + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the keyAltName. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // get a key by alt name + * const keyAltName = 'keyAltName'; + * const key = await clientEncryption.getKeyByAltName(keyAltName); + * if (!key) { + * // key is null if there is no matching key + * } + * ``` + */ + async getKeyByAltName(keyAltName) { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOne({ keyAltNames: keyAltName }, { readConcern: { level: 'majority' } }); + } + /** + * Adds a keyAltName to a key identified by the provided _id. + * + * This method resolves to/returns the *old* key value (prior to adding the new altKeyName). + * + * @param _id - The id of the document to update. + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // adding an keyAltName to a data key + * const id = new Binary(); // id is a bson binary subtype 4 object + * const keyAltName = 'keyAltName'; + * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName); + * if (!oldKey) { + * // null is returned if there is no matching document with an id matching the supplied id + * } + * ``` + */ + async addKeyAltName(_id, keyAltName) { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + const value = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOneAndUpdate({ _id }, { $addToSet: { keyAltNames: keyAltName } }, { writeConcern: { w: 'majority' }, returnDocument: 'before' }); + return value; + } + /** + * Adds a keyAltName to a key identified by the provided _id. + * + * This method resolves to/returns the *old* key value (prior to removing the new altKeyName). + * + * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document. + * + * @param _id - The id of the document to update. + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // removing a key alt name from a data key + * const id = new Binary(); // id is a bson binary subtype 4 object + * const keyAltName = 'keyAltName'; + * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName); + * + * if (!oldKey) { + * // null is returned if there is no matching document with an id matching the supplied id + * } + * ``` + */ + async removeKeyAltName(_id, keyAltName) { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); + const pipeline = [ + { + $set: { + keyAltNames: { + $cond: [ + { + $eq: ['$keyAltNames', [keyAltName]] + }, + '$$REMOVE', + { + $filter: { + input: '$keyAltNames', + cond: { + $ne: ['$$this', keyAltName] + } + } + } + ] + } + } + } + ]; + const value = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOneAndUpdate({ _id }, pipeline, { + writeConcern: { w: 'majority' }, + returnDocument: 'before' + }); + return value; + } + /** + * A convenience method for creating an encrypted collection. + * This method will create data keys for any encryptedFields that do not have a `keyId` defined + * and then create a new collection with the full set of encryptedFields. + * + * @param db - A Node.js driver Db object with which to create the collection + * @param name - The name of the collection to be created + * @param options - Options for createDataKey and for createCollection + * @returns created collection and generated encryptedFields + * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created. + * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created. + */ + async createEncryptedCollection(db, name, options) { + const { provider, masterKey, createCollectionOptions: { encryptedFields: { ...encryptedFields }, ...createCollectionOptions } } = options; + if (Array.isArray(encryptedFields.fields)) { + const createDataKeyPromises = encryptedFields.fields.map(async (field) => field == null || typeof field !== 'object' || field.keyId != null + ? field + : { + ...field, + keyId: await this.createDataKey(provider, { masterKey }) + }); + const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises); + encryptedFields.fields = createDataKeyResolutions.map((resolution, index) => resolution.status === 'fulfilled' ? resolution.value : encryptedFields.fields[index]); + const rejection = createDataKeyResolutions.find((result) => result.status === 'rejected'); + if (rejection != null) { + throw new errors_1.MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason }); + } + } + try { + const collection = await db.createCollection(name, { + ...createCollectionOptions, + encryptedFields + }); + return { collection, encryptedFields }; + } + catch (cause) { + throw new errors_1.MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause }); + } + } + /** + * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must + * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. + * + * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON + * @param options - + * @returns a Promise that either resolves with the encrypted value, or rejects with an error. + * + * @example + * ```ts + * // Encryption with async/await api + * async function encryptMyData(value) { + * const keyId = await clientEncryption.createDataKey('local'); + * return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); + * } + * ``` + * + * @example + * ```ts + * // Encryption using a keyAltName + * async function encryptMyData(value) { + * await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' }); + * return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); + * } + * ``` + */ + async encrypt(value, options) { + return this._encrypt(value, false, options); + } + /** + * Encrypts a Match Expression or Aggregate Expression to query a range index. + * + * Only supported when queryType is "rangePreview" and algorithm is "RangePreview". + * + * @experimental The Range algorithm is experimental only. It is not intended for production use. It is subject to breaking changes. + * + * @param expression - a BSON document of one of the following forms: + * 1. A Match Expression of this form: + * `{$and: [{: {$gt: }}, {: {$lt: }}]}` + * 2. An Aggregate Expression of this form: + * `{$and: [{$gt: [, ]}, {$lt: [, ]}]}` + * + * `$gt` may also be `$gte`. `$lt` may also be `$lte`. + * + * @param options - + * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error. + */ + async encryptExpression(expression, options) { + return this._encrypt(expression, true, options); + } + /** + * Explicitly decrypt a provided encrypted value + * + * @param value - An encrypted value + * @returns a Promise that either resolves with the decrypted value, or rejects with an error + * + * @example + * ```ts + * // Decrypting value with async/await API + * async function decryptMyValue(value) { + * return clientEncryption.decrypt(value); + * } + * ``` + */ + async decrypt(value) { + const valueBuffer = (0, bson_1.serialize)({ v: value }); + const context = this._mongoCrypt.makeExplicitDecryptionContext(valueBuffer); + const stateMachine = new state_machine_1.StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + const { v } = await stateMachine.execute(this, context); + return v; + } + /** + * @internal + * Ask the user for KMS credentials. + * + * This returns anything that looks like the kmsProviders original input + * option. It can be empty, and any provider specified here will override + * the original ones. + */ + async askForKMSCredentials() { + return (0, index_1.refreshKMSCredentials)(this._kmsProviders); + } + static get libmongocryptVersion() { + return ClientEncryption.getMongoCrypt().libmongocryptVersion; + } + /** + * @internal + * A helper that perform explicit encryption of values and expressions. + * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must + * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. + * + * @param value - The value that you wish to encrypt. Must be of a type that can be serialized into BSON + * @param expressionMode - a boolean that indicates whether or not to encrypt the value as an expression + * @param options - options to pass to encrypt + * @returns the raw result of the call to stateMachine.execute(). When expressionMode is set to true, the return + * value will be a bson document. When false, the value will be a BSON Binary. + * + */ + async _encrypt(value, expressionMode, options) { + const { algorithm, keyId, keyAltName, contentionFactor, queryType, rangeOptions } = options; + const contextOptions = { + expressionMode, + algorithm + }; + if (keyId) { + contextOptions.keyId = keyId.buffer; + } + if (keyAltName) { + if (keyId) { + throw new errors_1.MongoCryptInvalidArgumentError(`"options" cannot contain both "keyId" and "keyAltName"`); + } + if (typeof keyAltName !== 'string') { + throw new errors_1.MongoCryptInvalidArgumentError(`"options.keyAltName" must be of type string, but was of type ${typeof keyAltName}`); + } + contextOptions.keyAltName = (0, bson_1.serialize)({ keyAltName }); + } + if (typeof contentionFactor === 'number' || typeof contentionFactor === 'bigint') { + contextOptions.contentionFactor = contentionFactor; + } + if (typeof queryType === 'string') { + contextOptions.queryType = queryType; + } + if (typeof rangeOptions === 'object') { + contextOptions.rangeOptions = (0, bson_1.serialize)(rangeOptions); + } + const valueBuffer = (0, bson_1.serialize)({ v: value }); + const stateMachine = new state_machine_1.StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions); + const result = await stateMachine.execute(this, context); + return result.v; + } +} +exports.ClientEncryption = ClientEncryption; +//# sourceMappingURL=client_encryption.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/client_encryption.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/client_encryption.js.map new file mode 100644 index 00000000..dd836227 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/client_encryption.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client_encryption.js","sourceRoot":"","sources":["../../src/client-side-encryption/client_encryption.ts"],"names":[],"mappings":";;;AAOA,kCAAsF;AAMtF,kCAAqD;AAKrD,oCAAsD;AACtD,sDAAsD;AACtD,qCAIkB;AAClB,6CAI2B;AAC3B,mDAAwE;AAiBxE;;;GAGG;AACH,MAAa,gBAAgB;IAiB3B,gBAAgB;IAChB,MAAM,CAAC,aAAa;QAClB,MAAM,UAAU,GAAG,IAAA,iCAA0B,GAAE,CAAC;QAChD,IAAI,cAAc,IAAI,UAAU,EAAE;YAChC,MAAM,UAAU,CAAC,YAAY,CAAC;SAC/B;QACD,OAAO,UAAU,CAAC,UAAU,CAAC;IAC/B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,YAAY,MAAmB,EAAE,OAAgC;QAC/D,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC;QAChD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC;QAC5C,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY,IAAI,EAAE,CAAC;QAEhD,IAAI,OAAO,CAAC,iBAAiB,I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d,IAAI,KAAK,EAAE;gBACT,MAAM,IAAI,uCAA8B,CACtC,wDAAwD,CACzD,CAAC;aACH;YACD,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;gBAClC,MAAM,IAAI,uCAA8B,CACtC,gEAAgE,OAAO,UAAU,EAAE,CACpF,CAAC;aACH;YAED,cAAc,CAAC,UAAU,GAAG,IAAA,gBAAS,EAAC,EAAE,UAAU,EAAE,CAAC,CAAC;SACvD;QACD,IAAI,OAAO,gBAAgB,KAAK,QAAQ,IAAI,OAAO,gBAAgB,KAAK,QAAQ,EAAE;YAChF,cAAc,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;SACpD;QACD,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE;YACjC,cAAc,CAAC,SAAS,GAAG,SAAS,CAAC;SACtC;QAED,IAAI,OAAO,YAAY,KAAK,QAAQ,EAAE;YACpC,cAAc,CAAC,YAAY,GAAG,IAAA,gBAAS,EAAC,YAAY,CAAC,CAAC;SACvD;QAED,MAAM,WAAW,GAAG,IAAA,gBAAS,EAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5C,MAAM,YAAY,GAAG,IAAI,4BAAY,CAAC;YACpC,YAAY,EAAE,IAAI,CAAC,aAAa;YAChC,UAAU,EAAE,IAAI,CAAC,WAAW;SAC7B,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,6BAA6B,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC;QAE5F,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,OAAO,CAAgB,IAAI,EAAE,OAAO,CAAC,CAAC;QACxE,OAAO,MAAM,CAAC,CAAC,CAAC;IAClB,CAAC;CACF;AAjqBD,4CAiqBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js new file mode 100644 index 00000000..acdb2c73 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hmacSha256Hook = exports.hmacSha512Hook = exports.aes256CtrDecryptHook = exports.aes256CtrEncryptHook = exports.aes256CbcDecryptHook = exports.aes256CbcEncryptHook = exports.signRsaSha256Hook = exports.makeHmacHook = exports.sha256Hook = exports.randomHook = exports.makeAES256Hook = void 0; +const crypto = require("crypto"); +function makeAES256Hook(method, mode) { + return function (key, iv, input, output) { + let result; + try { + const cipher = crypto[method](mode, key, iv); + cipher.setAutoPadding(false); + result = cipher.update(input); + const final = cipher.final(); + if (final.length > 0) { + result = Buffer.concat([result, final]); + } + } + catch (e) { + return e; + } + result.copy(output); + return result.length; + }; +} +exports.makeAES256Hook = makeAES256Hook; +function randomHook(buffer, count) { + try { + crypto.randomFillSync(buffer, 0, count); + } + catch (e) { + return e; + } + return count; +} +exports.randomHook = randomHook; +function sha256Hook(input, output) { + let result; + try { + result = crypto.createHash('sha256').update(input).digest(); + } + catch (e) { + return e; + } + result.copy(output); + return result.length; +} +exports.sha256Hook = sha256Hook; +function makeHmacHook(algorithm) { + return (key, input, output) => { + let result; + try { + result = crypto.createHmac(algorithm, key).update(input).digest(); + } + catch (e) { + return e; + } + result.copy(output); + return result.length; + }; +} +exports.makeHmacHook = makeHmacHook; +function signRsaSha256Hook(key, input, output) { + let result; + try { + const signer = crypto.createSign('sha256WithRSAEncryption'); + const privateKey = Buffer.from(`-----BEGIN PRIVATE KEY-----\n${key.toString('base64')}\n-----END PRIVATE KEY-----\n`); + result = signer.update(input).end().sign(privateKey); + } + catch (e) { + return e; + } + result.copy(output); + return result.length; +} +exports.signRsaSha256Hook = signRsaSha256Hook; +exports.aes256CbcEncryptHook = makeAES256Hook('createCipheriv', 'aes-256-cbc'); +exports.aes256CbcDecryptHook = makeAES256Hook('createDecipheriv', 'aes-256-cbc'); +exports.aes256CtrEncryptHook = makeAES256Hook('createCipheriv', 'aes-256-ctr'); +exports.aes256CtrDecryptHook = makeAES256Hook('createDecipheriv', 'aes-256-ctr'); +exports.hmacSha512Hook = makeHmacHook('sha512'); +exports.hmacSha256Hook = makeHmacHook('sha256'); +//# sourceMappingURL=crypto_callbacks.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js.map new file mode 100644 index 00000000..50a31385 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/crypto_callbacks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"crypto_callbacks.js","sourceRoot":"","sources":["../../src/client-side-encryption/crypto_callbacks.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAIjC,SAAgB,cAAc,CAC5B,MAA6C,EAC7C,IAAmC;IAEnC,OAAO,UAAU,GAAW,EAAE,EAAU,EAAE,KAAa,EAAE,MAAc;QACrE,IAAI,MAAM,CAAC;QAEX,IAAI;YACF,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YAC7C,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;YAC7B,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC9B,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,EAAE,CAAC;YAC7B,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;gBACpB,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;aACzC;SACF;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,CAAC,CAAC;SACV;QAED,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACpB,OAAO,MAAM,CAAC,MAAM,CAAC;IACvB,CAAC,CAAC;AACJ,CAAC;AAtBD,wCAsBC;AAED,SAAgB,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,QAAQ,CAAC,QAAQ,CAAC,+BAA+B,CACtF,CAAC;QAEF,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;KACtD;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,CAAC;KACV;IAED,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpB,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC;AAfD,8CAeC;AAEY,QAAA,oBAAoB,GAAG,cAAc,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;AACvE,QAAA,oBAAoB,GAAG,cAAc,CAAC,kBAAkB,EAAE,aAAa,CAAC,CAAC;AACzE,QAAA,oBAAoB,GAAG,cAAc,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;AACvE,QAAA,oBAAoB,GAAG,cAAc,CAAC,kBAAkB,EAAE,aAAa,CAAC,CAAC;AACzE,QAAA,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;AACxC,QAAA,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/errors.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/errors.js new file mode 100644 index 00000000..5d91e11e --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/errors.js @@ -0,0 +1,136 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCryptKMSRequestNetworkTimeoutError = exports.MongoCryptAzureKMSRequestError = exports.MongoCryptCreateEncryptedCollectionError = exports.MongoCryptCreateDataKeyError = exports.MongoCryptInvalidArgumentError = exports.MongoCryptError = void 0; +const error_1 = require("../error"); +/** + * @public + * An error indicating that something went wrong specifically with MongoDB Client Encryption + */ +class MongoCryptError extends error_1.MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options = {}) { + super(message, options); + } + get name() { + return 'MongoCryptError'; + } +} +exports.MongoCryptError = MongoCryptError; +/** + * @public + * + * An error indicating an invalid argument was provided to an encryption API. + */ +class MongoCryptInvalidArgumentError extends MongoCryptError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoCryptInvalidArgumentError'; + } +} +exports.MongoCryptInvalidArgumentError = MongoCryptInvalidArgumentError; +/** + * @public + * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create data keys + */ +class MongoCryptCreateDataKeyError extends MongoCryptError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(encryptedFields, { cause }) { + super(`Unable to complete creating data keys: ${cause.message}`, { cause }); + this.encryptedFields = encryptedFields; + } + get name() { + return 'MongoCryptCreateDataKeyError'; + } +} +exports.MongoCryptCreateDataKeyError = MongoCryptCreateDataKeyError; +/** + * @public + * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create a collection + */ +class MongoCryptCreateEncryptedCollectionError extends MongoCryptError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(encryptedFields, { cause }) { + super(`Unable to create collection: ${cause.message}`, { cause }); + this.encryptedFields = encryptedFields; + } + get name() { + return 'MongoCryptCreateEncryptedCollectionError'; + } +} +exports.MongoCryptCreateEncryptedCollectionError = MongoCryptCreateEncryptedCollectionError; +/** + * @public + * An error indicating that mongodb-client-encryption failed to auto-refresh Azure KMS credentials. + */ +class MongoCryptAzureKMSRequestError extends MongoCryptError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, body) { + super(message); + this.body = body; + } + get name() { + return 'MongoCryptAzureKMSRequestError'; + } +} +exports.MongoCryptAzureKMSRequestError = MongoCryptAzureKMSRequestError; +/** @public */ +class MongoCryptKMSRequestNetworkTimeoutError extends MongoCryptError { + get name() { + return 'MongoCryptKMSRequestNetworkTimeoutError'; + } +} +exports.MongoCryptKMSRequestNetworkTimeoutError = MongoCryptKMSRequestNetworkTimeoutError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/errors.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/errors.js.map new file mode 100644 index 00000000..4576ba25 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/client-side-encryption/errors.ts"],"names":[],"mappings":";;;AACA,oCAAsC;AAEtC;;;GAGG;AACH,MAAa,eAAgB,SAAQ,kBAAU;IAC7C;;;;;;;;;;QAUI;IACJ,YAAY,OAAe,EAAE,UAA6B,EAAE;QAC1D,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;IAED,IAAa,IAAI;QACf,OAAO,iBAAiB,CAAC;IAC3B,CAAC;CACF;AAnBD,0CAmBC;AAED;;;;GAIG;AACH,MAAa,8BAA+B,SAAQ,eAAe;IACjE;;;;;;;;;;QAUI;IACJ,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;IAED,IAAa,IAAI;QACf,OAAO,gCAAgC,CAAC;IAC1C,CAAC;CACF;AAnBD,wEAmBC;AACD;;;GAGG;AACH,MAAa,4BAA6B,SAAQ,eAAe;IAE/D;;;;;;;;;;QAUI;IACJ,YAAY,eAAyB,EAAE,EAAE,KAAK,EAAoB;QAChE,KAAK,CAAC,0CAA0C,KAAK,CAAC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5E,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IACzC,CAAC;IAED,IAAa,IAAI;QACf,OAAO,8BAA8B,CAAC;IACxC,CAAC;CACF;AArBD,oEAqBC;AAED;;;GAGG;AACH,MAAa,wCAAyC,SAAQ,eAAe;IAE3E;;;;;;;;;;QAUI;IACJ,YAAY,eAAyB,EAAE,EAAE,KAAK,EAAoB;QAChE,KAAK,CAAC,gCAAgC,KAAK,CAAC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAClE,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IACzC,CAAC;IAED,IAAa,IAAI;QACf,OAAO,0CAA0C,CAAC;IACpD,CAAC;CACF;AArBD,4FAqBC;AAED;;;GAGG;AACH,MAAa,8BAA+B,SAAQ,eAAe;IAGjE;;;;;;;;;;QAUI;IACJ,YAAY,OAAe,EAAE,IAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,IAAa,IAAI;QACf,OAAO,gCAAgC,CAAC;IAC1C,CAAC;CACF;AAtBD,wEAsBC;AAED,cAAc;AACd,MAAa,uCAAwC,SAAQ,eAAe;IAC1E,IAAa,IAAI;QACf,OAAO,yCAAyC,CAAC;IACnD,CAAC;CACF;AAJD,0FAIC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js new file mode 100644 index 00000000..a4d361ef --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongocryptdManager = void 0; +const error_1 = require("../error"); +/** + * @internal + * An internal class that handles spawning a mongocryptd. + */ +class MongocryptdManager { + constructor(extraOptions = {}) { + this.uri = + typeof extraOptions.mongocryptdURI === 'string' && extraOptions.mongocryptdURI.length > 0 + ? extraOptions.mongocryptdURI + : MongocryptdManager.DEFAULT_MONGOCRYPTD_URI; + this.bypassSpawn = !!extraOptions.mongocryptdBypassSpawn; + this.spawnPath = extraOptions.mongocryptdSpawnPath || ''; + this.spawnArgs = []; + if (Array.isArray(extraOptions.mongocryptdSpawnArgs)) { + this.spawnArgs = this.spawnArgs.concat(extraOptions.mongocryptdSpawnArgs); + } + if (this.spawnArgs + .filter(arg => typeof arg === 'string') + .every(arg => arg.indexOf('--idleShutdownTimeoutSecs') < 0)) { + this.spawnArgs.push('--idleShutdownTimeoutSecs', '60'); + } + } + /** + * Will check to see if a mongocryptd is up. If it is not up, it will attempt + * to spawn a mongocryptd in a detached process, and then wait for it to be up. + */ + async spawn() { + const cmdName = this.spawnPath || 'mongocryptd'; + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { spawn } = require('child_process'); + // Spawned with stdio: ignore and detached: true + // to ensure child can outlive parent. + this._child = spawn(cmdName, this.spawnArgs, { + stdio: 'ignore', + detached: true + }); + this._child.on('error', () => { + // From the FLE spec: + // "The stdout and stderr of the spawned process MUST not be exposed in the driver + // (e.g. redirect to /dev/null). Users can pass the argument --logpath to + // extraOptions.mongocryptdSpawnArgs if they need to inspect mongocryptd logs. + // If spawning is necessary, the driver MUST spawn mongocryptd whenever server + // selection on the MongoClient to mongocryptd fails. If the MongoClient fails to + // connect after spawning, the server selection error is propagated to the user." + // The AutoEncrypter and MongoCryptdManager should work together to spawn + // mongocryptd whenever necessary. Additionally, the `mongocryptd` intentionally + // shuts down after 60s and gets respawned when necessary. We rely on server + // selection timeouts when connecting to the `mongocryptd` to inform users that something + // has been configured incorrectly. For those reasons, we suppress stderr from + // the `mongocryptd` process and immediately unref the process. + }); + // unref child to remove handle from event loop + this._child.unref(); + } + /** + * @returns the result of `fn` or rejects with an error. + */ + async withRespawn(fn) { + try { + const result = await fn(); + return result; + } + catch (err) { + // If we are not bypassing spawning, then we should retry once on a MongoTimeoutError (server selection error) + const shouldSpawn = err instanceof error_1.MongoNetworkTimeoutError && !this.bypassSpawn; + if (!shouldSpawn) { + throw err; + } + } + await this.spawn(); + const result = await fn(); + return result; + } +} +MongocryptdManager.DEFAULT_MONGOCRYPTD_URI = 'mongodb://localhost:27020'; +exports.MongocryptdManager = MongocryptdManager; +//# sourceMappingURL=mongocryptd_manager.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js.map new file mode 100644 index 00000000..cebcb909 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/mongocryptd_manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongocryptd_manager.js","sourceRoot":"","sources":["../../src/client-side-encryption/mongocryptd_manager.ts"],"names":[],"mappings":";;;AAEA,oCAAoD;AAGpD;;;GAGG;AACH,MAAa,kBAAkB;IAS7B,YAAY,eAA2C,EAAE;QACvD,IAAI,CAAC,GAAG;YACN,OAAO,YAAY,CAAC,cAAc,KAAK,QAAQ,IAAI,YAAY,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC;gBACvF,CAAC,CAAC,YAAY,CAAC,cAAc;gBAC7B,CAAC,CAAC,kBAAkB,CAAC,uBAAuB,CAAC;QAEjD,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,YAAY,CAAC,sBAAsB,CAAC;QAEzD,IAAI,CAAC,SAAS,GAAG,YAAY,CAAC,oBAAoB,IAAI,EAAE,CAAC;QACzD,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;QACpB,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,oBAAoB,CAAC,EAAE;YACpD,IAAI,CAAC,SAAS,GAAG,IA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,GAAG,EAAE;YACZ,8GAA8G;YAC9G,MAAM,WAAW,GAAG,GAAG,YAAY,gCAAwB,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC;YACjF,IAAI,CAAC,WAAW,EAAE;gBAChB,MAAM,GAAG,CAAC;aACX;SACF;QACD,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACnB,MAAM,MAAM,GAAG,MAAM,EAAE,EAAE,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;;AApFM,0CAAuB,GAAG,2BAA2B,CAAC;AADlD,gDAAkB"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/aws.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/aws.js new file mode 100644 index 00000000..5103c56b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/aws.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadAWSCredentials = void 0; +const deps_1 = require("../../deps"); +/** + * @internal + */ +async function loadAWSCredentials(kmsProviders) { + const credentialProvider = (0, deps_1.getAwsCredentialProvider)(); + if ('kModuleError' in credentialProvider) { + return kmsProviders; + } + const { fromNodeProviderChain } = credentialProvider; + const provider = fromNodeProviderChain(); + // The state machine is the only place calling this so it will + // catch if there is a rejection here. + const aws = await provider(); + return { ...kmsProviders, aws }; +} +exports.loadAWSCredentials = loadAWSCredentials; +//# sourceMappingURL=aws.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/aws.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/aws.js.map new file mode 100644 index 00000000..a4f37d84 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/aws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aws.js","sourceRoot":"","sources":["../../../src/client-side-encryption/providers/aws.ts"],"names":[],"mappings":";;;AAAA,qCAAsD;AAGtD;;GAEG;AACI,KAAK,UAAU,kBAAkB,CAAC,YAA0B;IACjE,MAAM,kBAAkB,GAAG,IAAA,+BAAwB,GAAE,CAAC;IAEtD,IAAI,cAAc,IAAI,kBAAkB,EAAE;QACxC,OAAO,YAAY,CAAC;KACrB;IAED,MAAM,EAAE,qBAAqB,EAAE,GAAG,kBAAkB,CAAC;IACrD,MAAM,QAAQ,GAAG,qBAAqB,EAAE,CAAC;IACzC,8DAA8D;IAC9D,sCAAsC;IACtC,MAAM,GAAG,GAAG,MAAM,QAAQ,EAAE,CAAC;IAC7B,OAAO,EAAE,GAAG,YAAY,EAAE,GAAG,EAAE,CAAC;AAClC,CAAC;AAbD,gDAaC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/azure.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/azure.js new file mode 100644 index 00000000..3d95c94f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/azure.js @@ -0,0 +1,114 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadAzureCredentials = exports.fetchAzureKMSToken = exports.prepareRequest = exports.tokenCache = exports.AzureCredentialCache = void 0; +const errors_1 = require("../errors"); +const utils_1 = require("./utils"); +const MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS = 6000; +/** + * @internal + */ +class AzureCredentialCache { + constructor() { + this.cachedToken = null; + } + async getToken() { + if (this.cachedToken == null || this.needsRefresh(this.cachedToken)) { + this.cachedToken = await this._getToken(); + } + return { accessToken: this.cachedToken.accessToken }; + } + needsRefresh(token) { + const timeUntilExpirationMS = token.expiresOnTimestamp - Date.now(); + return timeUntilExpirationMS <= MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS; + } + /** + * exposed for testing + */ + resetCache() { + this.cachedToken = null; + } + /** + * exposed for testing + */ + _getToken() { + return fetchAzureKMSToken(); + } +} +exports.AzureCredentialCache = AzureCredentialCache; +/** @internal */ +exports.tokenCache = new AzureCredentialCache(); +/** @internal */ +async function parseResponse(response) { + const { status, body: rawBody } = response; + const body = (() => { + try { + return JSON.parse(rawBody); + } + catch { + throw new errors_1.MongoCryptAzureKMSRequestError('Malformed JSON body in GET request.'); + } + })(); + if (status !== 200) { + throw new errors_1.MongoCryptAzureKMSRequestError('Unable to complete request.', body); + } + if (!body.access_token) { + throw new errors_1.MongoCryptAzureKMSRequestError('Malformed response body - missing field `access_token`.'); + } + if (!body.expires_in) { + throw new errors_1.MongoCryptAzureKMSRequestError('Malformed response body - missing field `expires_in`.'); + } + const expiresInMS = Number(body.expires_in) * 1000; + if (Number.isNaN(expiresInMS)) { + throw new errors_1.MongoCryptAzureKMSRequestError('Malformed response body - unable to parse int from `expires_in` field.'); + } + return { + accessToken: body.access_token, + expiresOnTimestamp: Date.now() + expiresInMS + }; +} +/** + * @internal + * + * parses any options provided by prose tests to `fetchAzureKMSToken` and merges them with + * the default values for headers and the request url. + */ +function prepareRequest(options) { + const url = new URL(options.url?.toString() ?? 'http://169.254.169.254/metadata/identity/oauth2/token'); + url.searchParams.append('api-version', '2018-02-01'); + url.searchParams.append('resource', 'https://vault.azure.net'); + const headers = { ...options.headers, 'Content-Type': 'application/json', Metadata: true }; + return { headers, url }; +} +exports.prepareRequest = prepareRequest; +/** + * @internal + * + * `AzureKMSRequestOptions` allows prose tests to modify the http request sent to the idms + * servers. This is required to simulate different server conditions. No options are expected to + * be set outside of tests. + * + * exposed for CSFLE + * [prose test 18](https://github.com/mongodb/specifications/tree/master/source/client-side-encryption/tests#azure-imds-credentials) + */ +async function fetchAzureKMSToken(options = {}) { + const { headers, url } = prepareRequest(options); + const response = await (0, utils_1.get)(url, { headers }).catch(error => { + if (error instanceof errors_1.MongoCryptKMSRequestNetworkTimeoutError) { + throw new errors_1.MongoCryptAzureKMSRequestError(`[Azure KMS] ${error.message}`); + } + throw error; + }); + return parseResponse(response); +} +exports.fetchAzureKMSToken = fetchAzureKMSToken; +/** + * @internal + * + * @throws Will reject with a `MongoCryptError` if the http request fails or the http response is malformed. + */ +async function loadAzureCredentials(kmsProviders) { + const azure = await exports.tokenCache.getToken(); + return { ...kmsProviders, azure }; +} +exports.loadAzureCredentials = loadAzureCredentials; +//# sourceMappingURL=azure.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/azure.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/azure.js.map new file mode 100644 index 00000000..060957cc --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/azure.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azure.js","sourceRoot":"","sources":["../../../src/client-side-encryption/providers/azure.ts"],"names":[],"mappings":";;;AACA,sCAAoG;AAEpG,mCAA8B;AAE9B,MAAM,qCAAqC,GAAG,IAAI,CAAC;AAkBnD;;GAEG;AACH,MAAa,oBAAoB;IAAjC;QACE,gBAAW,GAAgC,IAAI,CAAC;IA4BlD,CAAC;IA1BC,KAAK,CAAC,QAAQ;QACZ,IAAI,IAAI,CAAC,WAAW,IAAI,IAAI,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE;YACnE,IAAI,CAAC,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;SAC3C;QAED,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC,WAAW,EAAE,CAAC;IACvD,CAAC;IAED,YAAY,CAAC,KAA2B;QACtC,MAAM,qBAAqB,GAAG,KAAK,CAAC,kBAAkB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACpE,OAAO,qBAAqB,IAAI,qCAAqC,CAAC;IACxE,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAED;;OAEG;IACH,SAAS;QACP,OAAO,kBAAkB,EAAE,CAAC;IAC9B,CAAC;CACF;AA7BD,oDA6BC;AAED,gBAAgB;AACH,QAAA,UAAU,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAErD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AU,EAAE,yBAAyB,CAAC,CAAC;IAE/D,MAAM,OAAO,GAAG,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAC3F,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;AAC1B,CAAC;AAbD,wCAaC;AAED;;;;;;;;;GASG;AACI,KAAK,UAAU,kBAAkB,CACtC,UAAkC,EAAE;IAEpC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAG,MAAM,IAAA,WAAG,EAAC,GAAG,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QACzD,IAAI,KAAK,YAAY,gDAAuC,EAAE;YAC5D,MAAM,IAAI,uCAA8B,CAAC,eAAe,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;SAC1E;QACD,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACH,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC;AACjC,CAAC;AAXD,gDAWC;AAED;;;;GAIG;AACI,KAAK,UAAU,oBAAoB,CAAC,YAA0B;IACnE,MAAM,KAAK,GAAG,MAAM,kBAAU,CAAC,QAAQ,EAAE,CAAC;IAC1C,OAAO,EAAE,GAAG,YAAY,EAAE,KAAK,EAAE,CAAC;AACpC,CAAC;AAHD,oDAGC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js new file mode 100644 index 00000000..12c819d2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadGCPCredentials = void 0; +const deps_1 = require("../../deps"); +/** @internal */ +async function loadGCPCredentials(kmsProviders) { + const gcpMetadata = (0, deps_1.getGcpMetadata)(); + if ('kModuleError' in gcpMetadata) { + return kmsProviders; + } + const { access_token: accessToken } = await gcpMetadata.instance({ + property: 'service-accounts/default/token' + }); + return { ...kmsProviders, gcp: { accessToken } }; +} +exports.loadGCPCredentials = loadGCPCredentials; +//# sourceMappingURL=gcp.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js.map new file mode 100644 index 00000000..23b4106b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/gcp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gcp.js","sourceRoot":"","sources":["../../../src/client-side-encryption/providers/gcp.ts"],"names":[],"mappings":";;;AAAA,qCAA4C;AAG5C,gBAAgB;AACT,KAAK,UAAU,kBAAkB,CAAC,YAA0B;IACjE,MAAM,WAAW,GAAG,IAAA,qBAAc,GAAE,CAAC;IAErC,IAAI,cAAc,IAAI,WAAW,EAAE;QACjC,OAAO,YAAY,CAAC;KACrB;IAED,MAAM,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,MAAM,WAAW,CAAC,QAAQ,CAA2B;QACzF,QAAQ,EAAE,gCAAgC;KAC3C,CAAC,CAAC;IACH,OAAO,EAAE,GAAG,YAAY,EAAE,GAAG,EAAE,EAAE,WAAW,EAAE,EAAE,CAAC;AACnD,CAAC;AAXD,gDAWC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/index.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/index.js new file mode 100644 index 00000000..f6bebbae --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/index.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.refreshKMSCredentials = exports.isEmptyCredentials = void 0; +const aws_1 = require("./aws"); +const azure_1 = require("./azure"); +const gcp_1 = require("./gcp"); +/** + * Auto credential fetching should only occur when the provider is defined on the kmsProviders map + * and the settings are an empty object. + * + * This is distinct from a nullish provider key. + * + * @internal - exposed for testing purposes only + */ +function isEmptyCredentials(providerName, kmsProviders) { + const provider = kmsProviders[providerName]; + if (provider == null) { + return false; + } + return typeof provider === 'object' && Object.keys(provider).length === 0; +} +exports.isEmptyCredentials = isEmptyCredentials; +/** + * Load cloud provider credentials for the user provided KMS providers. + * Credentials will only attempt to get loaded if they do not exist + * and no existing credentials will get overwritten. + * + * @internal + */ +async function refreshKMSCredentials(kmsProviders) { + let finalKMSProviders = kmsProviders; + if (isEmptyCredentials('aws', kmsProviders)) { + finalKMSProviders = await (0, aws_1.loadAWSCredentials)(finalKMSProviders); + } + if (isEmptyCredentials('gcp', kmsProviders)) { + finalKMSProviders = await (0, gcp_1.loadGCPCredentials)(finalKMSProviders); + } + if (isEmptyCredentials('azure', kmsProviders)) { + finalKMSProviders = await (0, azure_1.loadAzureCredentials)(finalKMSProviders); + } + return finalKMSProviders; +} +exports.refreshKMSCredentials = refreshKMSCredentials; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/index.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/index.js.map new file mode 100644 index 00000000..f5aad1f5 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client-side-encryption/providers/index.ts"],"names":[],"mappings":";;;AAAA,+BAA2C;AAC3C,mCAA+C;AAC/C,+BAA2C;AA4H3C;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAChC,YAA6C,EAC7C,YAA0B;IAE1B,MAAM,QAAQ,GAAG,YAAY,CAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,QAAQ,IAAI,IAAI,EAAE;QACpB,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AAC5E,CAAC;AATD,gDASC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,qBAAqB,CAAC,YAA0B;IACpE,IAAI,iBAAiB,GAAG,YAAY,CAAC;IAErC,IAAI,kBAAkB,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE;QAC3C,iBAAiB,GAAG,MAAM,IAAA,wBAAkB,EAAC,iBAAiB,CAAC,CAAC;KACjE;IAED,IAAI,kBAAkB,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE;QAC3C,iBAAiB,GAAG,MAAM,IAAA,wBAAkB,EAAC,iBAAiB,CAAC,CAAC;KACjE;IAED,IAAI,kBAAkB,CAAC,OAAO,EAAE,YAAY,CAAC,EAAE;QAC7C,iBAAiB,GAAG,MAAM,IAAA,4BAAoB,EAAC,iBAAiB,CAAC,CAAC;KACnE;IACD,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AAfD,sDAeC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/utils.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/utils.js new file mode 100644 index 00000000..c75b9692 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/utils.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.get = void 0; +const http = require("http"); +const timers_1 = require("timers"); +const errors_1 = require("../errors"); +/** + * @internal + */ +function get(url, options = {}) { + return new Promise((resolve, reject) => { + /* eslint-disable prefer-const */ + let timeoutId; + const request = http + .get(url, options, response => { + response.setEncoding('utf8'); + let body = ''; + response.on('data', chunk => (body += chunk)); + response.on('end', () => { + (0, timers_1.clearTimeout)(timeoutId); + resolve({ status: response.statusCode, body }); + }); + }) + .on('error', error => { + (0, timers_1.clearTimeout)(timeoutId); + reject(error); + }) + .end(); + timeoutId = (0, timers_1.setTimeout)(() => { + request.destroy(new errors_1.MongoCryptKMSRequestNetworkTimeoutError(`request timed out after 10 seconds`)); + }, 10000); + }); +} +exports.get = get; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/utils.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/utils.js.map new file mode 100644 index 00000000..e3aea6fd --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/providers/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/client-side-encryption/providers/utils.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAC7B,mCAAkD;AAElD,sCAAoE;AAEpE;;GAEG;AACH,SAAgB,GAAG,CACjB,GAAiB,EACjB,UAA+B,EAAE;IAEjC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,iCAAiC;QACjC,IAAI,SAAyB,CAAC;QAC9B,MAAM,OAAO,GAAG,IAAI;aACjB,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE;YAC5B,QAAQ,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAC7B,IAAI,IAAI,GAAG,EAAE,CAAC;YACd,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC;YAC9C,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;gBACtB,IAAA,qBAAY,EAAC,SAAS,CAAC,CAAC;gBACxB,OAAO,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;YACjD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;aACD,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE;YACnB,IAAA,qBAAY,EAAC,SAAS,CAAC,CAAC;YACxB,MAAM,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC;aACD,GAAG,EAAE,CAAC;QACT,SAAS,GAAG,IAAA,mBAAU,EAAC,GAAG,EAAE;YAC1B,OAAO,CAAC,OAAO,CACb,IAAI,gDAAuC,CAAC,oCAAoC,CAAC,CAClF,CAAC;QACJ,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC;AA5BD,kBA4BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/state_machine.js b/nodejs/node_modules/mongodb/lib/client-side-encryption/state_machine.js new file mode 100644 index 00000000..74a3a876 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/state_machine.js @@ -0,0 +1,369 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StateMachine = void 0; +const fs = require("fs/promises"); +const net = require("net"); +const tls = require("tls"); +const bson_1 = require("../bson"); +const deps_1 = require("../deps"); +const utils_1 = require("../utils"); +const errors_1 = require("./errors"); +let socks = null; +function loadSocks() { + if (socks == null) { + const socksImport = (0, deps_1.getSocks)(); + if ('kModuleError' in socksImport) { + throw socksImport.kModuleError; + } + socks = socksImport; + } + return socks; +} +// libmongocrypt states +const MONGOCRYPT_CTX_ERROR = 0; +const MONGOCRYPT_CTX_NEED_MONGO_COLLINFO = 1; +const MONGOCRYPT_CTX_NEED_MONGO_MARKINGS = 2; +const MONGOCRYPT_CTX_NEED_MONGO_KEYS = 3; +const MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS = 7; +const MONGOCRYPT_CTX_NEED_KMS = 4; +const MONGOCRYPT_CTX_READY = 5; +const MONGOCRYPT_CTX_DONE = 6; +const HTTPS_PORT = 443; +const stateToString = new Map([ + [MONGOCRYPT_CTX_ERROR, 'MONGOCRYPT_CTX_ERROR'], + [MONGOCRYPT_CTX_NEED_MONGO_COLLINFO, 'MONGOCRYPT_CTX_NEED_MONGO_COLLINFO'], + [MONGOCRYPT_CTX_NEED_MONGO_MARKINGS, 'MONGOCRYPT_CTX_NEED_MONGO_MARKINGS'], + [MONGOCRYPT_CTX_NEED_MONGO_KEYS, 'MONGOCRYPT_CTX_NEED_MONGO_KEYS'], + [MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS, 'MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS'], + [MONGOCRYPT_CTX_NEED_KMS, 'MONGOCRYPT_CTX_NEED_KMS'], + [MONGOCRYPT_CTX_READY, 'MONGOCRYPT_CTX_READY'], + [MONGOCRYPT_CTX_DONE, 'MONGOCRYPT_CTX_DONE'] +]); +const INSECURE_TLS_OPTIONS = [ + 'tlsInsecure', + 'tlsAllowInvalidCertificates', + 'tlsAllowInvalidHostnames', + // These options are disallowed by the spec, so we explicitly filter them out if provided, even + // though the StateMachine does not declare support for these options. + 'tlsDisableOCSPEndpointCheck', + 'tlsDisableCertificateRevocationCheck' +]; +/** + * Helper function for logging. Enabled by setting the environment flag MONGODB_CRYPT_DEBUG. + * @param msg - Anything you want to be logged. + */ +function debug(msg) { + if (process.env.MONGODB_CRYPT_DEBUG) { + // eslint-disable-next-line no-console + console.error(msg); + } +} +/** + * @internal + * An internal class that executes across a MongoCryptContext until either + * a finishing state or an error is reached. Do not instantiate directly. + */ +class StateMachine { + constructor(options, bsonOptions = (0, bson_1.pluckBSONSerializeOptions)(options)) { + this.options = options; + this.bsonOptions = bsonOptions; + } + /** + * Executes the state machine according to the specification + */ + async execute(executor, context) { + const keyVaultNamespace = executor._keyVaultNamespace; + const keyVaultClient = executor._keyVaultClient; + const metaDataClient = executor._metaDataClient; + const mongocryptdClient = executor._mongocryptdClient; + const mongocryptdManager = executor._mongocryptdManager; + let result = null; + while (context.state !== MONGOCRYPT_CTX_DONE && context.state !== MONGOCRYPT_CTX_ERROR) { + debug(`[context#${context.id}] ${stateToString.get(context.state) || context.state}`); + switch (context.state) { + case MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: { + const filter = (0, bson_1.deserialize)(context.nextMongoOperation()); + if (!metaDataClient) { + throw new errors_1.MongoCryptError('unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_COLLINFO but metadata client is undefined'); + } + const collInfo = await this.fetchCollectionInfo(metaDataClient, context.ns, filter); + if (collInfo) { + context.addMongoOperationResponse(collInfo); + } + context.finishMongoOperation(); + break; + } + case MONGOCRYPT_CTX_NEED_MONGO_MARKINGS: { + const command = context.nextMongoOperation(); + if (!mongocryptdClient) { + throw new errors_1.MongoCryptError('unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined'); + } + // When we are using the shared library, we don't have a mongocryptd manager. + const markedCommand = mongocryptdManager + ? await mongocryptdManager.withRespawn(this.markCommand.bind(this, mongocryptdClient, context.ns, command)) + : await this.markCommand(mongocryptdClient, context.ns, command); + context.addMongoOperationResponse(markedCommand); + context.finishMongoOperation(); + break; + } + case MONGOCRYPT_CTX_NEED_MONGO_KEYS: { + const filter = context.nextMongoOperation(); + const keys = await this.fetchKeys(keyVaultClient, keyVaultNamespace, filter); + if (keys.length === 0) { + // This is kind of a hack. For `rewrapManyDataKey`, we have tests that + // guarantee that when there are no matching keys, `rewrapManyDataKey` returns + // nothing. We also have tests for auto encryption that guarantee for `encrypt` + // we return an error when there are no matching keys. This error is generated in + // subsequent iterations of the state machine. + // Some apis (`encrypt`) throw if there are no filter matches and others (`rewrapManyDataKey`) + // do not. We set the result manually here, and let the state machine continue. `libmongocrypt` + // will inform us if we need to error by setting the state to `MONGOCRYPT_CTX_ERROR` but + // otherwise we'll return `{ v: [] }`. + result = { v: [] }; + } + for await (const key of keys) { + context.addMongoOperationResponse((0, bson_1.serialize)(key)); + } + context.finishMongoOperation(); + break; + } + case MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS: { + const kmsProviders = await executor.askForKMSCredentials(); + context.provideKMSProviders((0, bson_1.serialize)(kmsProviders)); + break; + } + case MONGOCRYPT_CTX_NEED_KMS: { + const requests = Array.from(this.requests(context)); + await Promise.all(requests); + context.finishKMSRequests(); + break; + } + case MONGOCRYPT_CTX_READY: { + const finalizedContext = context.finalize(); + // @ts-expect-error finalize can change the state, check for error + if (context.state === MONGOCRYPT_CTX_ERROR) { + const message = context.status.message || 'Finalization error'; + throw new errors_1.MongoCryptError(message); + } + result = (0, bson_1.deserialize)(finalizedContext, this.options); + break; + } + default: + throw new errors_1.MongoCryptError(`Unknown state: ${context.state}`); + } + } + if (context.state === MONGOCRYPT_CTX_ERROR || result == null) { + const message = context.status.message; + if (!message) { + debug(`unidentifiable error in MongoCrypt - received an error status from \`libmongocrypt\` but received no error message.`); + } + throw new errors_1.MongoCryptError(message ?? + 'unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message.'); + } + return result; + } + /** + * Handles the request to the KMS service. Exposed for testing purposes. Do not directly invoke. + * @param kmsContext - A C++ KMS context returned from the bindings + * @returns A promise that resolves when the KMS reply has be fully parsed + */ + async kmsRequest(request) { + const parsedUrl = request.endpoint.split(':'); + const port = parsedUrl[1] != null ? Number.parseInt(parsedUrl[1], 10) : HTTPS_PORT; + const options = { + host: parsedUrl[0], + servername: parsedUrl[0], + port + }; + const message = request.message; + const buffer = new utils_1.BufferPool(); + const netSocket = new net.Socket(); + let socket; + function destroySockets() { + for (const sock of [socket, netSocket]) { + if (sock) { + sock.removeAllListeners(); + sock.destroy(); + } + } + } + function ontimeout() { + return new errors_1.MongoCryptError('KMS request timed out'); + } + function onerror(cause) { + return new errors_1.MongoCryptError('KMS request failed', { cause }); + } + function onclose() { + return new errors_1.MongoCryptError('KMS request closed'); + } + const tlsOptions = this.options.tlsOptions; + if (tlsOptions) { + const kmsProvider = request.kmsProvider; + const providerTlsOptions = tlsOptions[kmsProvider]; + if (providerTlsOptions) { + const error = this.validateTlsOptions(kmsProvider, providerTlsOptions); + if (error) { + throw error; + } + try { + await this.setTlsOptions(providerTlsOptions, options); + } + catch (err) { + throw onerror(err); + } + } + } + const { promise: willConnect, reject: rejectOnNetSocketError, resolve: resolveOnNetSocketConnect } = (0, utils_1.promiseWithResolvers)(); + netSocket + .once('timeout', () => rejectOnNetSocketError(ontimeout())) + .once('error', err => rejectOnNetSocketError(onerror(err))) + .once('close', () => rejectOnNetSocketError(onclose())) + .once('connect', () => resolveOnNetSocketConnect()); + try { + if (this.options.proxyOptions && this.options.proxyOptions.proxyHost) { + netSocket.connect({ + host: this.options.proxyOptions.proxyHost, + port: this.options.proxyOptions.proxyPort || 1080 + }); + await willConnect; + try { + socks ??= loadSocks(); + options.socket = (await socks.SocksClient.createConnection({ + existing_socket: netSocket, + command: 'connect', + destination: { host: options.host, port: options.port }, + proxy: { + // host and port are ignored because we pass existing_socket + host: 'iLoveJavaScript', + port: 0, + type: 5, + userId: this.options.proxyOptions.proxyUsername, + password: this.options.proxyOptions.proxyPassword + } + })).socket; + } + catch (err) { + throw onerror(err); + } + } + socket = tls.connect(options, () => { + socket.write(message); + }); + const { promise: willResolveKmsRequest, reject: rejectOnTlsSocketError, resolve } = (0, utils_1.promiseWithResolvers)(); + socket + .once('timeout', () => rejectOnTlsSocketError(ontimeout())) + .once('error', err => rejectOnTlsSocketError(onerror(err))) + .once('close', () => rejectOnTlsSocketError(onclose())) + .on('data', data => { + buffer.append(data); + while (request.bytesNeeded > 0 && buffer.length) { + const bytesNeeded = Math.min(request.bytesNeeded, buffer.length); + request.addResponse(buffer.read(bytesNeeded)); + } + if (request.bytesNeeded <= 0) { + resolve(); + } + }); + await willResolveKmsRequest; + } + finally { + // There's no need for any more activity on this socket at this point. + destroySockets(); + } + } + *requests(context) { + for (let request = context.nextKMSRequest(); request != null; request = context.nextKMSRequest()) { + yield this.kmsRequest(request); + } + } + /** + * Validates the provided TLS options are secure. + * + * @param kmsProvider - The KMS provider name. + * @param tlsOptions - The client TLS options for the provider. + * + * @returns An error if any option is invalid. + */ + validateTlsOptions(kmsProvider, tlsOptions) { + const tlsOptionNames = Object.keys(tlsOptions); + for (const option of INSECURE_TLS_OPTIONS) { + if (tlsOptionNames.includes(option)) { + return new errors_1.MongoCryptError(`Insecure TLS options prohibited for ${kmsProvider}: ${option}`); + } + } + } + /** + * Sets only the valid secure TLS options. + * + * @param tlsOptions - The client TLS options for the provider. + * @param options - The existing connection options. + */ + async setTlsOptions(tlsOptions, options) { + if (tlsOptions.tlsCertificateKeyFile) { + const cert = await fs.readFile(tlsOptions.tlsCertificateKeyFile); + options.cert = options.key = cert; + } + if (tlsOptions.tlsCAFile) { + options.ca = await fs.readFile(tlsOptions.tlsCAFile); + } + if (tlsOptions.tlsCertificateKeyFilePassword) { + options.passphrase = tlsOptions.tlsCertificateKeyFilePassword; + } + } + /** + * Fetches collection info for a provided namespace, when libmongocrypt + * enters the `MONGOCRYPT_CTX_NEED_MONGO_COLLINFO` state. The result is + * used to inform libmongocrypt of the schema associated with this + * namespace. Exposed for testing purposes. Do not directly invoke. + * + * @param client - A MongoClient connected to the topology + * @param ns - The namespace to list collections from + * @param filter - A filter for the listCollections command + * @param callback - Invoked with the info of the requested collection, or with an error + */ + async fetchCollectionInfo(client, ns, filter) { + const { db } = utils_1.MongoDBCollectionNamespace.fromString(ns); + const collections = await client + .db(db) + .listCollections(filter, { + promoteLongs: false, + promoteValues: false + }) + .toArray(); + const info = collections.length > 0 ? (0, bson_1.serialize)(collections[0]) : null; + return info; + } + /** + * Calls to the mongocryptd to provide markings for a command. + * Exposed for testing purposes. Do not directly invoke. + * @param client - A MongoClient connected to a mongocryptd + * @param ns - The namespace (database.collection) the command is being executed on + * @param command - The command to execute. + * @param callback - Invoked with the serialized and marked bson command, or with an error + */ + async markCommand(client, ns, command) { + const options = { promoteLongs: false, promoteValues: false }; + const { db } = utils_1.MongoDBCollectionNamespace.fromString(ns); + const rawCommand = (0, bson_1.deserialize)(command, options); + const response = await client.db(db).command(rawCommand, options); + return (0, bson_1.serialize)(response, this.bsonOptions); + } + /** + * Requests keys from the keyVault collection on the topology. + * Exposed for testing purposes. Do not directly invoke. + * @param client - A MongoClient connected to the topology + * @param keyVaultNamespace - The namespace (database.collection) of the keyVault Collection + * @param filter - The filter for the find query against the keyVault Collection + * @param callback - Invoked with the found keys, or with an error + */ + fetchKeys(client, keyVaultNamespace, filter) { + const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(keyVaultNamespace); + return client + .db(dbName) + .collection(collectionName, { readConcern: { level: 'majority' } }) + .find((0, bson_1.deserialize)(filter)) + .toArray(); + } +} +exports.StateMachine = StateMachine; +//# sourceMappingURL=state_machine.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/client-side-encryption/state_machine.js.map b/nodejs/node_modules/mongodb/lib/client-side-encryption/state_machine.js.map new file mode 100644 index 00000000..1aef49f9 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/client-side-encryption/state_machine.js.map @@ -0,0 +1 @@ +{"version":3,"file":"state_machine.js","sourceRoot":"","sources":["../../src/client-side-encryption/state_machine.ts"],"names":[],"mappings":";;;AAAA,kCAAkC;AAElC,2BAA2B;AAC3B,2BAA2B;AAE3B,kCAMiB;AAEjB,kCAAkD;AAElD,oCAAwF;AAExF,qCAA2C;AAI3C,IAAI,KAAK,GAAoB,IAAI,CAAC;AAClC,SAAS,SAAS;IAChB,IAAI,KAAK,IAAI,IAAI,EAAE;QACjB,MAAM,WAAW,GAAG,IAAA,eAAQ,GAAE,CAAC;QAC/B,IAAI,cAAc,IAAI,WAAW,EAAE;YACjC,MAAM,WAAW,CAAC,YAAY,CAAC;SAChC;QACD,KAAK,GAAG,WAAW,CAAC;KACrB;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,uBAAuB;AACvB,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,kCAAkC,GAAG,CAAC,CAAC;AAC7C,MAAM,kCAAkC,GAAG,CAAC,CAAC;AAC7C,MAAM,8BAA8B,GAAG,CAAC,CAAC;AACzC,MAAM,mCAAmC,GAAG,CAAC,CAAC;AAC9C,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAClC,MAAM,oBAAo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CAAC,CAAC;QAE3D,OAAO,MAAM;aACV,EAAE,CAAC,MAAM,CAAC;aACV,UAAU,CAAU,cAAc,EAAE,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC;aAC3E,IAAI,CAAC,IAAA,kBAAW,EAAC,MAAM,CAAC,CAAC;aACzB,OAAO,EAAE,CAAC;IACf,CAAC;CACF;AA/XD,oCA+XC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/auth_provider.js b/nodejs/node_modules/mongodb/lib/cmap/auth/auth_provider.js new file mode 100644 index 00000000..99cbf72a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/auth_provider.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthProvider = exports.AuthContext = void 0; +const error_1 = require("../../error"); +/** + * Context used during authentication + * @internal + */ +class AuthContext { + constructor(connection, credentials, options) { + /** If the context is for reauthentication. */ + this.reauthenticating = false; + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} +exports.AuthContext = AuthContext; +/** + * Provider used during authentication. + * @internal + */ +class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + async prepare(handshakeDoc, _authContext) { + return handshakeDoc; + } + /** + * Reauthenticate. + * @param context - The shared auth context. + */ + async reauth(context) { + if (context.reauthenticating) { + throw new error_1.MongoRuntimeError('Reauthentication already in progress.'); + } + try { + context.reauthenticating = true; + await this.auth(context); + } + finally { + context.reauthenticating = false; + } + } +} +exports.AuthProvider = AuthProvider; +//# sourceMappingURL=auth_provider.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map new file mode 100644 index 00000000..caa3981a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth_provider.js","sourceRoot":"","sources":["../../../src/cmap/auth/auth_provider.ts"],"names":[],"mappings":";;;AACA,uCAAgD;AAKhD;;;GAGG;AACH,MAAa,WAAW;IAetB,YACE,UAAsB,EACtB,WAAyC,EACzC,OAA0B;QAb5B,8CAA8C;QAC9C,qBAAgB,GAAG,KAAK,CAAC;QAcvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAxBD,kCAwBC;AAED;;;GAGG;AACH,MAAsB,YAAY;IAChC;;;;;OAKG;IACH,KAAK,CAAC,OAAO,CACX,YAA+B,EAC/B,YAAyB;QAEzB,OAAO,YAAY,CAAC;IACtB,CAAC;IASD;;;OAGG;IACH,KAAK,CAAC,MAAM,CAAC,OAAoB;QAC/B,IAAI,OAAO,CAAC,gBAAgB,EAAE;YAC5B,MAAM,IAAI,yBAAiB,CAAC,uCAAuC,CAAC,CAAC;SACtE;QACD,IAAI;YACF,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAChC,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;SAC1B;gBAAS;YACR,OAAO,CAAC,gBAAgB,GAAG,KAAK,CAAC;SAClC;IACH,CAAC;CACF;AApCD,oCAoCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/gssapi.js b/nodejs/node_modules/mongodb/lib/cmap/auth/gssapi.js new file mode 100644 index 00000000..192d2fda --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/gssapi.js @@ -0,0 +1,153 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveCname = exports.performGSSAPICanonicalizeHostName = exports.GSSAPI = exports.GSSAPICanonicalizationValue = void 0; +const dns = require("dns"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +/** @public */ +exports.GSSAPICanonicalizationValue = Object.freeze({ + on: true, + off: false, + none: 'none', + forward: 'forward', + forwardAndReverse: 'forwardAndReverse' +}); +async function externalCommand(connection, command) { + return connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined); +} +let krb; +class GSSAPI extends auth_provider_1.AuthProvider { + async auth(authContext) { + const { connection, credentials } = authContext; + if (credentials == null) { + throw new error_1.MongoMissingCredentialsError('Credentials required for GSSAPI authentication'); + } + const { username } = credentials; + const client = await makeKerberosClient(authContext); + const payload = await client.step(''); + const saslStartResponse = await externalCommand(connection, saslStart(payload)); + const negotiatedPayload = await negotiate(client, 10, saslStartResponse.payload); + const saslContinueResponse = await externalCommand(connection, saslContinue(negotiatedPayload, saslStartResponse.conversationId)); + const finalizePayload = await finalize(client, username, saslContinueResponse.payload); + await externalCommand(connection, { + saslContinue: 1, + conversationId: saslContinueResponse.conversationId, + payload: finalizePayload + }); + } +} +exports.GSSAPI = GSSAPI; +async function makeKerberosClient(authContext) { + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + throw new error_1.MongoInvalidArgumentError('Connection must have host and port and credentials defined.'); + } + loadKrb(); + if ('kModuleError' in krb) { + throw krb['kModuleError']; + } + const { initializeClient } = krb; + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties; + const serviceName = mechanismProperties.SERVICE_NAME ?? 'mongodb'; + const host = await performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties); + const initOptions = {}; + if (password != null) { + // TODO(NODE-5139): These do not match the typescript options in initializeClient + Object.assign(initOptions, { user: username, password: password }); + } + const spnHost = mechanismProperties.SERVICE_HOST ?? host; + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${spnHost}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + return initializeClient(spn, initOptions); +} +function saslStart(payload) { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; +} +function saslContinue(payload, conversationId) { + return { + saslContinue: 1, + conversationId, + payload + }; +} +async function negotiate(client, retries, payload) { + try { + const response = await client.step(payload); + return response || ''; + } + catch (error) { + if (retries === 0) { + // Retries exhausted, raise error + throw error; + } + // Adjust number of retries and call step again + return negotiate(client, retries - 1, payload); + } +} +async function finalize(client, user, payload) { + // GSS Client Unwrap + const response = await client.unwrap(payload); + return client.wrap(response || '', { user }); +} +async function performGSSAPICanonicalizeHostName(host, mechanismProperties) { + const mode = mechanismProperties.CANONICALIZE_HOST_NAME; + if (!mode || mode === exports.GSSAPICanonicalizationValue.none) { + return host; + } + // If forward and reverse or true + if (mode === exports.GSSAPICanonicalizationValue.on || + mode === exports.GSSAPICanonicalizationValue.forwardAndReverse) { + // Perform the lookup of the ip address. + const { address } = await dns.promises.lookup(host); + try { + // Perform a reverse ptr lookup on the ip address. + const results = await dns.promises.resolvePtr(address); + // If the ptr did not error but had no results, return the host. + return results.length > 0 ? results[0] : host; + } + catch (error) { + // This can error as ptr records may not exist for all ips. In this case + // fallback to a cname lookup as dns.lookup() does not return the + // cname. + return resolveCname(host); + } + } + else { + // The case for forward is just to resolve the cname as dns.lookup() + // will not return it. + return resolveCname(host); + } +} +exports.performGSSAPICanonicalizeHostName = performGSSAPICanonicalizeHostName; +async function resolveCname(host) { + // Attempt to resolve the host name + try { + const results = await dns.promises.resolveCname(host); + // Get the first resolved host id + return results.length > 0 ? results[0] : host; + } + catch { + return host; + } +} +exports.resolveCname = resolveCname; +/** + * Load the Kerberos library. + */ +function loadKrb() { + if (!krb) { + krb = (0, deps_1.getKerberos)(); + } +} +//# sourceMappingURL=gssapi.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/gssapi.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/gssapi.js.map new file mode 100644 index 00000000..b7c34886 --- /dev/null +++ b/nod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,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;KAC/C;IAAC,MAAM;QACN,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AATD,oCASC;AAED;;GAEG;AACH,SAAS,OAAO;IACd,IAAI,CAAC,GAAG,EAAE;QACR,GAAG,GAAG,IAAA,kBAAW,GAAE,CAAC;KACrB;AACH,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js new file mode 100644 index 00000000..e7c3304b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js @@ -0,0 +1,177 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCredentials = exports.DEFAULT_ALLOWED_HOSTS = void 0; +const error_1 = require("../../error"); +const gssapi_1 = require("./gssapi"); +const providers_1 = require("./providers"); +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(hello) { + if (hello) { + // If hello contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(hello.saslSupportedMechs)) { + return hello.saslSupportedMechs.includes(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) + ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA256 + : providers_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (hello.maxWireVersion >= 3) { + return providers_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + } + // Default for wireprotocol < 3 + return providers_1.AuthMechanism.MONGODB_CR; +} +const ALLOWED_PROVIDER_NAMES = ['aws', 'azure']; +const ALLOWED_HOSTS_ERROR = 'Auth mechanism property ALLOWED_HOSTS must be an array of strings.'; +/** @internal */ +exports.DEFAULT_ALLOWED_HOSTS = [ + '*.mongodb.net', + '*.mongodb-dev.net', + '*.mongodbgov.net', + 'localhost', + '127.0.0.1', + '::1' +]; +/** Error for when the token audience is missing in the environment. */ +const TOKEN_AUDIENCE_MISSING_ERROR = 'TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.'; +/** + * A representation of the credentials used by MongoDB + * @public + */ +class MongoCredentials { + constructor(options) { + this.username = options.username ?? ''; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || providers_1.AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + if (this.mechanism.match(/MONGODB-AWS/i)) { + 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 = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } + } + if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC && !this.mechanismProperties.ALLOWED_HOSTS) { + this.mechanismProperties = { + ...this.mechanismProperties, + ALLOWED_HOSTS: exports.DEFAULT_ALLOWED_HOSTS + }; + } + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + /** Determines if two MongoCredentials objects are equivalent */ + equals(other) { + return (this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source); + } + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param hello - A hello response from the server + */ + resolveAuthMechanism(hello) { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(hello), + mechanismProperties: this.mechanismProperties + }); + } + return this; + } + validate() { + if ((this.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI || + this.mechanism === providers_1.AuthMechanism.MONGODB_CR || + this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || + this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === providers_1.AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username) { + throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) { + if (this.username && this.mechanismProperties.PROVIDER_NAME) { + throw new error_1.MongoInvalidArgumentError(`username and PROVIDER_NAME may not be used together for mechanism '${this.mechanism}'.`); + } + if (this.mechanismProperties.PROVIDER_NAME === 'azure' && + !this.mechanismProperties.TOKEN_AUDIENCE) { + throw new error_1.MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR); + } + if (this.mechanismProperties.PROVIDER_NAME && + !ALLOWED_PROVIDER_NAMES.includes(this.mechanismProperties.PROVIDER_NAME)) { + throw new error_1.MongoInvalidArgumentError(`Currently only a PROVIDER_NAME in ${ALLOWED_PROVIDER_NAMES.join(',')} is supported for mechanism '${this.mechanism}'.`); + } + if (this.mechanismProperties.REFRESH_TOKEN_CALLBACK && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) { + throw new error_1.MongoInvalidArgumentError(`A REQUEST_TOKEN_CALLBACK must be provided when using a REFRESH_TOKEN_CALLBACK for mechanism '${this.mechanism}'`); + } + if (!this.mechanismProperties.PROVIDER_NAME && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) { + throw new error_1.MongoInvalidArgumentError(`Either a PROVIDER_NAME or a REQUEST_TOKEN_CALLBACK must be specified for mechanism '${this.mechanism}'.`); + } + if (this.mechanismProperties.ALLOWED_HOSTS) { + const hosts = this.mechanismProperties.ALLOWED_HOSTS; + if (!Array.isArray(hosts)) { + throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR); + } + for (const host of hosts) { + if (typeof host !== 'string') { + throw new error_1.MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR); + } + } + } + } + if (providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`); + } + } + if (this.mechanism === providers_1.AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + if (this.mechanism === providers_1.AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); + } + const canonicalization = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false; + if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) { + throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); + } + } + static merge(creds, options) { + return new MongoCredentials({ + username: options.username ?? creds?.username ?? '', + password: options.password ?? creds?.password ?? '', + mechanism: options.mechanism ?? creds?.mechanism ?? providers_1.AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, + source: options.source ?? options.db ?? creds?.source ?? 'admin' + }); + } +} +exports.MongoCredentials = MongoCredentials; +//# sourceMappingURL=mongo_credentials.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map new file mode 100644 index 00000000..a6556d67 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_credentials.js","sourceRoot":"","sources":["../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;YACnD,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,KAAK,EAAE,SAAS,IAAI,yBAAa,CAAC,eAAe;YACjF,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,IAAI,KAAK,EAAE,mBAAmB,IAAI,EAAE;YACpF,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE,IAAI,KAAK,EAAE,MAAM,IAAI,OAAO;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAjMD,4CAiMC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongocr.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongocr.js new file mode 100644 index 00000000..b6d34637 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongocr.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCR = void 0; +const crypto = require("crypto"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +class MongoCR extends auth_provider_1.AuthProvider { + async auth(authContext) { + const { connection, credentials } = authContext; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + const { username, password, source } = credentials; + const { nonce } = await connection.command((0, utils_1.ns)(`${source}.$cmd`), { getnonce: 1 }, undefined); + const hashPassword = crypto + .createHash('md5') + .update(`${username}:mongo:${password}`, 'utf8') + .digest('hex'); + // Final key + const key = crypto + .createHash('md5') + .update(`${nonce}${username}${hashPassword}`, 'utf8') + .digest('hex'); + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + await connection.command((0, utils_1.ns)(`${source}.$cmd`), authenticateCommand, undefined); + } +} +exports.MongoCR = MongoCR; +//# sourceMappingURL=mongocr.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongocr.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongocr.js.map new file mode 100644 index 00000000..596cdf85 --- /dev/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E,SAAS,CAAC,CAAC;IACjF,CAAC;CACF;AA/BD,0BA+BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js new file mode 100644 index 00000000..a8dd2232 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js @@ -0,0 +1,230 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoDBAWS = void 0; +const process = require("process"); +const BSON = require("../../bson"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +const mongo_credentials_1 = require("./mongo_credentials"); +const providers_1 = require("./providers"); +/** + * The following regions use the global AWS STS endpoint, sts.amazonaws.com, by default + * https://docs.aws.amazon.com/sdkref/latest/guide/feature-sts-regionalized-endpoints.html + */ +const LEGACY_REGIONS = new Set([ + 'ap-northeast-1', + 'ap-south-1', + 'ap-southeast-1', + 'ap-southeast-2', + 'aws-global', + 'ca-central-1', + 'eu-central-1', + 'eu-north-1', + 'eu-west-1', + 'eu-west-2', + 'eu-west-3', + 'sa-east-1', + 'us-east-1', + 'us-east-2', + 'us-west-1', + 'us-west-2' +]); +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; +const bsonOptions = { + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; +class MongoDBAWS extends auth_provider_1.AuthProvider { + constructor() { + super(); + MongoDBAWS.credentialProvider ??= (0, deps_1.getAwsCredentialProvider)(); + let { AWS_STS_REGIONAL_ENDPOINTS = '', AWS_REGION = '' } = process.env; + AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase(); + AWS_REGION = AWS_REGION.toLowerCase(); + /** The option setting should work only for users who have explicit settings in their environment, the driver should not encode "defaults" */ + const awsRegionSettingsExist = AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0; + /** + * If AWS_STS_REGIONAL_ENDPOINTS is set to regional, users are opting into the new behavior of respecting the region settings + * + * If AWS_STS_REGIONAL_ENDPOINTS is set to legacy, then "old" regions need to keep using the global setting. + * Technically the SDK gets this wrong, it reaches out to 'sts.us-east-1.amazonaws.com' when it should be 'sts.amazonaws.com'. + * That is not our bug to fix here. We leave that up to the SDK. + */ + const useRegionalSts = AWS_STS_REGIONAL_ENDPOINTS === 'regional' || + (AWS_STS_REGIONAL_ENDPOINTS === 'legacy' && !LEGACY_REGIONS.has(AWS_REGION)); + if ('fromNodeProviderChain' in MongoDBAWS.credentialProvider) { + this.provider = + awsRegionSettingsExist && useRegionalSts + ? MongoDBAWS.credentialProvider.fromNodeProviderChain({ + clientConfig: { region: AWS_REGION } + }) + : MongoDBAWS.credentialProvider.fromNodeProviderChain(); + } + } + async auth(authContext) { + const { connection } = authContext; + if (!authContext.credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + if ('kModuleError' in deps_1.aws4) { + throw deps_1.aws4['kModuleError']; + } + const { sign } = deps_1.aws4; + if ((0, utils_1.maxWireVersion)(connection) < 9) { + throw new error_1.MongoCompatibilityError('MONGODB-AWS authentication requires MongoDB version 4.4 or later'); + } + if (!authContext.credentials.username) { + authContext.credentials = await makeTempCredentials(authContext.credentials, this.provider); + } + const { credentials } = authContext; + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + // Allow the user to specify an AWS session token for authentication with temporary credentials. + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + const db = credentials.source; + const nonce = await (0, utils_1.randomBytes)(32); + // All messages between MongoDB clients and servers are sent as BSON objects + // in the payload field of saslStart and saslContinue. + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) + }; + const saslStartResponse = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStart, undefined); + const serverResponse = BSON.deserialize(saslStartResponse.payload.buffer, bsonOptions); + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`); + } + if (!utils_1.ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { + // throw because the serverNonce's leading 32 bytes must equal the client nonce's 32 bytes + // https://github.com/mongodb/specifications/blob/875446db44aade414011731840831f38a6c668df/source/auth/auth.rst#id11 + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('Server nonce does not begin with client nonce'); + } + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`); + } + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = sign({ + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': utils_1.ByteUtils.toBase64(serverNonce), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, awsCredentials); + const payload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + if (sessionToken) { + payload.t = sessionToken; + } + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinue, undefined); + } +} +exports.MongoDBAWS = MongoDBAWS; +async function makeTempCredentials(credentials, provider) { + function makeMongoCredentialsFromAWSTemp(creds) { + // The AWS session token (creds.Token) may or may not be set. + if (!creds.AccessKeyId || !creds.SecretAccessKey) { + throw new error_1.MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials'); + } + return new mongo_credentials_1.MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: providers_1.AuthMechanism.MONGODB_AWS, + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + }); + } + // Check if the AWS credential provider from the SDK is present. If not, + // use the old method. + if (provider && !('kModuleError' in MongoDBAWS.credentialProvider)) { + /* + * Creates a credential provider that will attempt to find credentials from the + * following sources (listed in order of precedence): + * + * - Environment variables exposed via process.env + * - SSO credentials from token cache + * - Web identity token credentials + * - Shared credentials and config ini files + * - The EC2/ECS Instance Metadata Service + */ + try { + const creds = await provider(); + return makeMongoCredentialsFromAWSTemp({ + AccessKeyId: creds.accessKeyId, + SecretAccessKey: creds.secretAccessKey, + Token: creds.sessionToken, + Expiration: creds.expiration + }); + } + catch (error) { + throw new error_1.MongoAWSError(error.message); + } + } + else { + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + return makeMongoCredentialsFromAWSTemp(await (0, utils_1.request)(`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`)); + } + // Otherwise assume we are on an EC2 instance + // get a token + const token = await (0, utils_1.request)(`${AWS_EC2_URI}/latest/api/token`, { + method: 'PUT', + json: false, + headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } + }); + // get role name + const roleName = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, { + json: false, + headers: { 'X-aws-ec2-metadata-token': token } + }); + // get temp credentials + const creds = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, { + headers: { 'X-aws-ec2-metadata-token': token } + }); + return makeMongoCredentialsFromAWSTemp(creds); + } +} +function deriveRegion(host) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + return parts[1]; +} +//# sourceMappingURL=mongodb_aws.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map new file mode 100644 index 00000000..e7e1f91d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongodb_aws.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongodb_aws.ts"],"names":[],"mappings":";;;AAAA,mCAAmC;AAGnC,mCAAmC;AACnC,qCAAiF;AACjF,uCAKqB;AACrB,uCAAkF;AAClF,mDAAiE;AACjE,2DAAuD;AACvD,2CAA4C;AAE5C;;;GAGG;AACH,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC7B,gBAAgB;IAChB,YAAY;IACZ,gBAAgB;IAChB,gBAAgB;IAChB,YAAY;IACZ,cAAc;IACd,cAAc;IACd,YAAY;IACZ,WAAW;IACX,WAAW;IACX,WAAW;IACX,WAAW;IACX,WAAW;IACX,WAAW;IACX,WAAW;IACX,WAAW;CACZ,CAAC,CAAC;AACH,MAAM,OAAO,GAAG,GAAG,CAAC;AACpB,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AAChD,MAAM,WAAW,GAAG,wBAAwB,CAAC;AAC7C,MAAM,YAAY,GAAG,4CAA4C,CAAC;AAClE,MAAM,WAAW,GAAyB;IACxC,WAAW,EAAE,KAAK;IAClB,YAAY,EAAE,IAAI;IAClB,aAAa,EAAE,IAAI;IACnB,cAAc,EAAE,KAAK;IACrB,UAAU,EAAE,KAAK;CAClB,CAAC;AAQF,MAAa,UAAW,SAAQ,4BAAY;IAI1C;QACE,KAAK,EAAE,CAAC;QACR,UAAU,CAAC,kBAAkB,KA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AC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,EAAE;QAClD,OAAO,WAAW,CAAC;KACpB;IAED,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js new file mode 100644 index 00000000..050cf8aa --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoDBOIDC = exports.OIDC_WORKFLOWS = void 0; +const error_1 = require("../../error"); +const auth_provider_1 = require("./auth_provider"); +const aws_service_workflow_1 = require("./mongodb_oidc/aws_service_workflow"); +const azure_service_workflow_1 = require("./mongodb_oidc/azure_service_workflow"); +const callback_workflow_1 = require("./mongodb_oidc/callback_workflow"); +/** Error when credentials are missing. */ +const MISSING_CREDENTIALS_ERROR = 'AuthContext must provide credentials.'; +/** @internal */ +exports.OIDC_WORKFLOWS = new Map(); +exports.OIDC_WORKFLOWS.set('callback', new callback_workflow_1.CallbackWorkflow()); +exports.OIDC_WORKFLOWS.set('aws', new aws_service_workflow_1.AwsServiceWorkflow()); +exports.OIDC_WORKFLOWS.set('azure', new azure_service_workflow_1.AzureServiceWorkflow()); +/** + * OIDC auth provider. + * @experimental + */ +class MongoDBOIDC extends auth_provider_1.AuthProvider { + /** + * Instantiate the auth provider. + */ + constructor() { + super(); + } + /** + * Authenticate using OIDC + */ + async auth(authContext) { + const { connection, reauthenticating, response } = authContext; + const credentials = getCredentials(authContext); + const workflow = getWorkflow(credentials); + await workflow.execute(connection, credentials, reauthenticating, response); + } + /** + * Add the speculative auth for the initial handshake. + */ + async prepare(handshakeDoc, authContext) { + const credentials = getCredentials(authContext); + const workflow = getWorkflow(credentials); + const result = await workflow.speculativeAuth(credentials); + return { ...handshakeDoc, ...result }; + } +} +exports.MongoDBOIDC = MongoDBOIDC; +/** + * Get credentials from the auth context, throwing if they do not exist. + */ +function getCredentials(authContext) { + const { credentials } = authContext; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR); + } + return credentials; +} +/** + * Gets either a device workflow or callback workflow. + */ +function getWorkflow(credentials) { + const providerName = credentials.mechanismProperties.PROVIDER_NAME; + const workflow = exports.OIDC_WORKFLOWS.get(providerName || 'callback'); + if (!workflow) { + throw new error_1.MongoInvalidArgumentError(`Could not load workflow for provider ${credentials.mechanismProperties.PROVIDER_NAME}`); + } + return workflow; +} +//# sourceMappingURL=mongodb_oidc.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map new file mode 100644 index 00000000..60dcbabd --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongodb_oidc.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongodb_oidc.ts"],"names":[],"mappings":";;;AAEA,uCAAsF;AAGtF,mDAAiE;AAEjE,8EAAyE;AACzE,kFAA6E;AAC7E,wEAAoE;AAEpE,0CAA0C;AAC1C,MAAM,yBAAyB,GAAG,uCAAuC,CAAC;AAuE1E,gBAAgB;AACH,QAAA,cAAc,GAAgC,IAAI,GAAG,EAAE,CAAC;AACrE,sBAAc,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,oCAAgB,EAAE,CAAC,CAAC;AACvD,sBAAc,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,yCAAkB,EAAE,CAAC,CAAC;AACpD,sBAAc,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,6CAAoB,EAAE,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAa,WAAY,SAAQ,4BAAY;IAC3C;;OAEG;IACH;QACE,KAAK,EAAE,CAAC;IACV,CAAC;IAED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;AAClB,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js new file mode 100644 index 00000000..44286f38 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsServiceWorkflow = void 0; +const fs = require("fs"); +const error_1 = require("../../../error"); +const service_workflow_1 = require("./service_workflow"); +/** Error for when the token is missing in the environment. */ +const TOKEN_MISSING_ERROR = 'AWS_WEB_IDENTITY_TOKEN_FILE must be set in the environment.'; +/** + * Device workflow implementation for AWS. + * + * @internal + */ +class AwsServiceWorkflow extends service_workflow_1.ServiceWorkflow { + constructor() { + super(); + } + /** + * Get the token from the environment. + */ + async getToken() { + const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE; + if (!tokenFile) { + throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR); + } + return fs.promises.readFile(tokenFile, 'utf8'); + } +} +exports.AwsServiceWorkflow = AwsServiceWorkflow; +//# sourceMappingURL=aws_service_workflow.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js.map new file mode 100644 index 00000000..9a2fd769 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aws_service_workflow.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/aws_service_workflow.ts"],"names":[],"mappings":";;;AAAA,yBAAyB;AAEzB,0CAA+C;AAC/C,yDAAqD;AAErD,8DAA8D;AAC9D,MAAM,mBAAmB,GAAG,6DAA6D,CAAC;AAE1F;;;;GAIG;AACH,MAAa,kBAAmB,SAAQ,kCAAe;IACrD;QACE,KAAK,EAAE,CAAC;IACV,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,QAAQ;QACZ,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC;QAC1D,IAAI,CAAC,SAAS,EAAE;YACd,MAAM,IAAI,qBAAa,CAAC,mBAAmB,CAAC,CAAC;SAC9C;QACD,OAAO,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;IACjD,CAAC;CACF;AAfD,gDAeC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js new file mode 100644 index 00000000..e5984e42 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AzureServiceWorkflow = void 0; +const error_1 = require("../../../error"); +const utils_1 = require("../../../utils"); +const azure_token_cache_1 = require("./azure_token_cache"); +const service_workflow_1 = require("./service_workflow"); +/** Base URL for getting Azure tokens. */ +const AZURE_BASE_URL = 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01'; +/** Azure request headers. */ +const AZURE_HEADERS = Object.freeze({ Metadata: 'true', Accept: 'application/json' }); +/** Invalid endpoint result error. */ +const ENDPOINT_RESULT_ERROR = 'Azure endpoint did not return a value with only access_token and expires_in properties'; +/** Error for when the token audience is missing in the environment. */ +const TOKEN_AUDIENCE_MISSING_ERROR = 'TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.'; +/** + * Device workflow implementation for Azure. + * + * @internal + */ +class AzureServiceWorkflow extends service_workflow_1.ServiceWorkflow { + constructor() { + super(...arguments); + this.cache = new azure_token_cache_1.AzureTokenCache(); + } + /** + * Get the token from the environment. + */ + async getToken(credentials) { + const tokenAudience = credentials?.mechanismProperties.TOKEN_AUDIENCE; + if (!tokenAudience) { + throw new error_1.MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR); + } + let token; + const entry = this.cache.getEntry(tokenAudience); + if (entry?.isValid()) { + token = entry.token; + } + else { + this.cache.deleteEntry(tokenAudience); + const response = await getAzureTokenData(tokenAudience); + if (!isEndpointResultValid(response)) { + throw new error_1.MongoAzureError(ENDPOINT_RESULT_ERROR); + } + this.cache.addEntry(tokenAudience, response); + token = response.access_token; + } + return token; + } +} +exports.AzureServiceWorkflow = AzureServiceWorkflow; +/** + * Hit the Azure endpoint to get the token data. + */ +async function getAzureTokenData(tokenAudience) { + const url = `${AZURE_BASE_URL}&resource=${tokenAudience}`; + const data = await (0, utils_1.request)(url, { + json: true, + headers: AZURE_HEADERS + }); + return data; +} +/** + * Determines if a result returned from the endpoint is valid. + * This means the result is not nullish, contains the access_token required field + * and the expires_in required field. + */ +function isEndpointResultValid(token) { + if (token == null || typeof token !== 'object') + return false; + return 'access_token' in token && 'expires_in' in token; +} +//# sourceMappingURL=azure_service_workflow.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js.map new file mode 100644 index 00000000..cbc885d9 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azure_service_workflow.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/azure_service_workflow.ts"],"names":[],"mappings":";;;AAAA,0CAAiD;AACjD,0CAAyC;AAEzC,2DAAsD;AACtD,yDAAqD;AAErD,yCAAyC;AACzC,MAAM,cAAc,GAClB,8EAA8E,CAAC;AAEjF,6BAA6B;AAC7B,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC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AAM,IAAI,GAAG,MAAM,IAAA,eAAO,EAAC,GAAG,EAAE;QAC9B,IAAI,EAAE,IAAI;QACV,OAAO,EAAE,aAAa;KACvB,CAAC,CAAC;IACH,OAAO,IAAwB,CAAC;AAClC,CAAC;AAED;;;;GAIG;AACH,SAAS,qBAAqB,CAC5B,KAAc;IAEd,IAAI,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC7D,OAAO,cAAc,IAAI,KAAK,IAAI,YAAY,IAAI,KAAK,CAAC;AAC1D,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js new file mode 100644 index 00000000..845750bd --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AzureTokenCache = exports.AzureTokenEntry = void 0; +const cache_1 = require("./cache"); +/** @internal */ +class AzureTokenEntry extends cache_1.ExpiringCacheEntry { + /** + * Instantiate the entry. + */ + constructor(token, expiration) { + super(expiration); + this.token = token; + } +} +exports.AzureTokenEntry = AzureTokenEntry; +/** + * A cache of access tokens from Azure. + * @internal + */ +class AzureTokenCache extends cache_1.Cache { + /** + * Add an entry to the cache. + */ + addEntry(tokenAudience, token) { + const entry = new AzureTokenEntry(token.access_token, token.expires_in); + this.entries.set(tokenAudience, entry); + return entry; + } + /** + * Create a cache key. + */ + cacheKey(tokenAudience) { + return tokenAudience; + } + /** + * Delete an entry from the cache. + */ + deleteEntry(tokenAudience) { + this.entries.delete(tokenAudience); + } + /** + * Get an Azure token entry from the cache. + */ + getEntry(tokenAudience) { + return this.entries.get(tokenAudience); + } +} +exports.AzureTokenCache = AzureTokenCache; +//# sourceMappingURL=azure_token_cache.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js.map new file mode 100644 index 00000000..86b81637 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azure_token_cache.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/azure_token_cache.ts"],"names":[],"mappings":";;;AACA,mCAAoD;AAEpD,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAAkB;IAGrD;;OAEG;IACH,YAAY,KAAa,EAAE,UAAkB;QAC3C,KAAK,CAAC,UAAU,CAAC,CAAC;QAClB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAVD,0CAUC;AAED;;;GAGG;AACH,MAAa,eAAgB,SAAQ,aAAsB;IACzD;;OAEG;IACH,QAAQ,CAAC,aAAqB,EAAE,KAAuB;QACrD,MAAM,KAAK,GAAG,IAAI,eAAe,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QACvC,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,aAAqB;QAC5B,OAAO,aAAa,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,aAAqB;QAC/B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IACrC,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,aAAqB;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IACzC,CAAC;CACF;AA9BD,0CA8BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js new file mode 100644 index 00000000..2f08551e --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Cache = exports.ExpiringCacheEntry = void 0; +/* 5 minutes in milliseconds */ +const EXPIRATION_BUFFER_MS = 300000; +/** + * An entry in a cache that can expire in a certain amount of time. + */ +class ExpiringCacheEntry { + /** + * Create a new expiring token entry. + */ + constructor(expiration) { + this.expiration = this.expirationTime(expiration); + } + /** + * The entry is still valid if the expiration is more than + * 5 minutes from the expiration time. + */ + isValid() { + return this.expiration - Date.now() > EXPIRATION_BUFFER_MS; + } + /** + * Get an expiration time in milliseconds past epoch. + */ + expirationTime(expiresInSeconds) { + return Date.now() + expiresInSeconds * 1000; + } +} +exports.ExpiringCacheEntry = ExpiringCacheEntry; +/** + * Base class for OIDC caches. + */ +class Cache { + /** + * Create a new cache. + */ + constructor() { + this.entries = new Map(); + } + /** + * Clear the cache. + */ + clear() { + this.entries.clear(); + } + /** + * Create a cache key from the address and username. + */ + hashedCacheKey(address, username, callbackHash) { + return JSON.stringify([address, username, callbackHash]); + } +} +exports.Cache = Cache; +//# sourceMappingURL=cache.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js.map new file mode 100644 index 00000000..34ad50c1 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/cache.ts"],"names":[],"mappings":";;;AAAA,+BAA+B;AAC/B,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAEpC;;GAEG;AACH,MAAsB,kBAAkB;IAGtC;;OAEG;IACH,YAAY,UAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;IACpD,CAAC;IACD;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,oBAAoB,CAAC;IAC7D,CAAC;IAED;;OAEG;IACK,cAAc,CAAC,gBAAwB;QAC7C,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,gBAAgB,GAAG,IAAI,CAAC;IAC9C,CAAC;CACF;AAvBD,gDAuBC;AAED;;GAEG;AACH,MAAsB,KAAK;IAGzB;;OAEG;IACH;QACE,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,EAAa,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;IAOD;;OAEG;IACH,cAAc,CAAC,OAAe,EAAE,QAAgB,EAAE,YAAoB;QACpE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AA5BD,sBA4BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js new file mode 100644 index 00000000..94e99847 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CallbackLockCache = void 0; +const error_1 = require("../../../error"); +const cache_1 = require("./cache"); +/** Error message for when request callback is missing. */ +const REQUEST_CALLBACK_REQUIRED_ERROR = 'Auth mechanism property REQUEST_TOKEN_CALLBACK is required.'; +/* Counter for function "hashes".*/ +let FN_HASH_COUNTER = 0; +/* No function present function */ +const NO_FUNCTION = async () => ({ accessToken: 'test' }); +/* The map of function hashes */ +const FN_HASHES = new WeakMap(); +/* Put the no function hash in the map. */ +FN_HASHES.set(NO_FUNCTION, FN_HASH_COUNTER); +/** + * A cache of request and refresh callbacks per server/user. + */ +class CallbackLockCache extends cache_1.Cache { + /** + * Get the callbacks for the connection and credentials. If an entry does not + * exist a new one will get set. + */ + getEntry(connection, credentials) { + const requestCallback = credentials.mechanismProperties.REQUEST_TOKEN_CALLBACK; + const refreshCallback = credentials.mechanismProperties.REFRESH_TOKEN_CALLBACK; + if (!requestCallback) { + throw new error_1.MongoInvalidArgumentError(REQUEST_CALLBACK_REQUIRED_ERROR); + } + const callbackHash = hashFunctions(requestCallback, refreshCallback); + const key = this.cacheKey(connection.address, credentials.username, callbackHash); + const entry = this.entries.get(key); + if (entry) { + return entry; + } + return this.addEntry(key, callbackHash, requestCallback, refreshCallback); + } + /** + * Set locked callbacks on for connection and credentials. + */ + addEntry(key, callbackHash, requestCallback, refreshCallback) { + const entry = { + requestCallback: withLock(requestCallback), + refreshCallback: refreshCallback ? withLock(refreshCallback) : undefined, + callbackHash: callbackHash + }; + this.entries.set(key, entry); + return entry; + } + /** + * Create a cache key from the address and username. + */ + cacheKey(address, username, callbackHash) { + return this.hashedCacheKey(address, username, callbackHash); + } +} +exports.CallbackLockCache = CallbackLockCache; +/** + * Ensure the callback is only executed one at a time. + */ +function withLock(callback) { + let lock = Promise.resolve(); + return async (info, context) => { + await lock; + lock = lock.then(() => callback(info, context)); + return lock; + }; +} +/** + * Get the hash string for the request and refresh functions. + */ +function hashFunctions(requestFn, refreshFn) { + let requestHash = FN_HASHES.get(requestFn); + let refreshHash = FN_HASHES.get(refreshFn ?? NO_FUNCTION); + if (requestHash == null) { + // Create a new one for the function and put it in the map. + FN_HASH_COUNTER++; + requestHash = FN_HASH_COUNTER; + FN_HASHES.set(requestFn, FN_HASH_COUNTER); + } + if (refreshHash == null && refreshFn) { + // Create a new one for the function and put it in the map. + FN_HASH_COUNTER++; + refreshHash = FN_HASH_COUNTER; + FN_HASHES.set(refreshFn, FN_HASH_COUNTER); + } + return `${requestHash}-${refreshHash}`; +} +//# sourceMappingURL=callback_lock_cache.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js.map new file mode 100644 index 00000000..39e05dd7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"callback_lock_cache.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/callback_lock_cache.ts"],"names":[],"mappings":";;;AAAA,0CAA2D;AAU3D,mCAAgC;AAEhC,0DAA0D;AAC1D,MAAM,+BAA+B,GACnC,6DAA6D,CAAC;AAChE,mCAAmC;AACnC,IAAI,eAAe,GAAG,CAAC,CAAC;AACxB,kCAAkC;AAClC,MAAM,WAAW,GAAwB,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;AAC/E,gCAAgC;AAChC,MAAM,SAAS,GAAG,IAAI,OAAO,EAAqD,CAAC;AACnF,0CAA0C;AAC1C,SAAS,CAAC,GAAG,CAAC,WAAW,EAAE,eAAe,CAAC,CAAC;AAW5C;;GAEG;AACH,MAAa,iBAAkB,SAAQ,aAAqB;IAC1D;;;OAGG;IACH,QAAQ,CAAC,UAAsB,EAAE,WAA6B;QAC5D,MAAM,eAAe,GAAG,WAAW,CAAC,mBAAmB,CAAC,sBAAsB,CAAC;QAC/E,MAAM,eAAe,GAAG,WAAW,CAAC,mBAAmB,CAAC,sBAAsB,CAAC;QAC/E,IAAI,CAAC,eAAe,EAAE;YACpB,MAAM,IAAI,iCAAyB,CAAC,+BAA+B,CAAC,CAAC;SACtE;QACD,MAAM,YAAY,GAAG,aAAa,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;QACrE,MA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,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,SAA8B,EAAE,SAA+B;IACpF,IAAI,WAAW,GAAG,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC3C,IAAI,WAAW,GAAG,SAAS,CAAC,GAAG,CAAC,SAAS,IAAI,WAAW,CAAC,CAAC;IAC1D,IAAI,WAAW,IAAI,IAAI,EAAE;QACvB,2DAA2D;QAC3D,eAAe,EAAE,CAAC;QAClB,WAAW,GAAG,eAAe,CAAC;QAC9B,SAAS,CAAC,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;KAC3C;IACD,IAAI,WAAW,IAAI,IAAI,IAAI,SAAS,EAAE;QACpC,2DAA2D;QAC3D,eAAe,EAAE,CAAC;QAClB,WAAW,GAAG,eAAe,CAAC;QAC9B,SAAS,CAAC,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;KAC3C;IACD,OAAO,GAAG,WAAW,IAAI,WAAW,EAAE,CAAC;AACzC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js new file mode 100644 index 00000000..34ad9a94 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js @@ -0,0 +1,204 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CallbackWorkflow = void 0; +const bson_1 = require("bson"); +const error_1 = require("../../../error"); +const utils_1 = require("../../../utils"); +const providers_1 = require("../providers"); +const callback_lock_cache_1 = require("./callback_lock_cache"); +const token_entry_cache_1 = require("./token_entry_cache"); +/** The current version of OIDC implementation. */ +const OIDC_VERSION = 0; +/** 5 minutes in seconds */ +const TIMEOUT_S = 300; +/** Properties allowed on results of callbacks. */ +const RESULT_PROPERTIES = ['accessToken', 'expiresInSeconds', 'refreshToken']; +/** Error message when the callback result is invalid. */ +const CALLBACK_RESULT_ERROR = 'User provided OIDC callbacks must return a valid object with an accessToken.'; +/** + * OIDC implementation of a callback based workflow. + * @internal + */ +class CallbackWorkflow { + /** + * Instantiate the workflow + */ + constructor() { + this.cache = new token_entry_cache_1.TokenEntryCache(); + this.callbackCache = new callback_lock_cache_1.CallbackLockCache(); + } + /** + * Get the document to add for speculative authentication. This also needs + * to add a db field from the credentials source. + */ + async speculativeAuth(credentials) { + const document = startCommandDocument(credentials); + document.db = credentials.source; + return { speculativeAuthenticate: document }; + } + /** + * Execute the OIDC callback workflow. + */ + async execute(connection, credentials, reauthenticating, response) { + // Get the callbacks with locks from the callback lock cache. + const { requestCallback, refreshCallback, callbackHash } = this.callbackCache.getEntry(connection, credentials); + // Look for an existing entry in the cache. + const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash); + let result; + if (entry) { + // Reauthentication cannot use a token from the cache since the server has + // stated it is invalid by the request for reauthentication. + if (entry.isValid() && !reauthenticating) { + // Presence of a valid cache entry means we can skip to the finishing step. + result = await this.finishAuthentication(connection, credentials, entry.tokenResult, response?.speculativeAuthenticate?.conversationId); + } + else { + // Presence of an expired cache entry means we must fetch a new one and + // then execute the final step. + const tokenResult = await this.fetchAccessToken(connection, credentials, entry.serverInfo, reauthenticating, callbackHash, requestCallback, refreshCallback); + try { + result = await this.finishAuthentication(connection, credentials, tokenResult, reauthenticating ? undefined : response?.speculativeAuthenticate?.conversationId); + } + catch (error) { + // If we are reauthenticating and this errors with reauthentication + // required, we need to do the entire process over again and clear + // the cache entry. + if (reauthenticating && + error instanceof error_1.MongoError && + error.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) { + this.cache.deleteEntry(connection.address, credentials.username, callbackHash); + result = await this.execute(connection, credentials, reauthenticating); + } + else { + throw error; + } + } + } + } + else { + // No entry in the cache requires us to do all authentication steps + // from start to finish, including getting a fresh token for the cache. + const startDocument = await this.startAuthentication(connection, credentials, reauthenticating, response); + const conversationId = startDocument.conversationId; + const serverResult = bson_1.BSON.deserialize(startDocument.payload.buffer); + const tokenResult = await this.fetchAccessToken(connection, credentials, serverResult, reauthenticating, callbackHash, requestCallback, refreshCallback); + result = await this.finishAuthentication(connection, credentials, tokenResult, conversationId); + } + return result; + } + /** + * Starts the callback authentication process. If there is a speculative + * authentication document from the initial handshake, then we will use that + * value to get the issuer, otherwise we will send the saslStart command. + */ + async startAuthentication(connection, credentials, reauthenticating, response) { + let result; + if (!reauthenticating && response?.speculativeAuthenticate) { + result = response.speculativeAuthenticate; + } + else { + result = await connection.command((0, utils_1.ns)(credentials.source), startCommandDocument(credentials), undefined); + } + return result; + } + /** + * Finishes the callback authentication process. + */ + async finishAuthentication(connection, credentials, tokenResult, conversationId) { + const result = await connection.command((0, utils_1.ns)(credentials.source), finishCommandDocument(tokenResult.accessToken, conversationId), undefined); + return result; + } + /** + * Fetches an access token using either the request or refresh callbacks and + * puts it in the cache. + */ + async fetchAccessToken(connection, credentials, serverInfo, reauthenticating, callbackHash, requestCallback, refreshCallback) { + // Get the token from the cache. + const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash); + let result; + const context = { timeoutSeconds: TIMEOUT_S, version: OIDC_VERSION }; + // Check if there's a token in the cache. + if (entry) { + // If the cache entry is valid, return the token result. + if (entry.isValid() && !reauthenticating) { + return entry.tokenResult; + } + // If the cache entry is not valid, remove it from the cache and first attempt + // to use the refresh callback to get a new token. If no refresh callback + // exists, then fallback to the request callback. + if (refreshCallback) { + context.refreshToken = entry.tokenResult.refreshToken; + result = await refreshCallback(serverInfo, context); + } + else { + result = await requestCallback(serverInfo, context); + } + } + else { + // With no token in the cache we use the request callback. + result = await requestCallback(serverInfo, context); + } + // Validate that the result returned by the callback is acceptable. If it is not + // we must clear the token result from the cache. + if (isCallbackResultInvalid(result)) { + this.cache.deleteEntry(connection.address, credentials.username, callbackHash); + throw new error_1.MongoMissingCredentialsError(CALLBACK_RESULT_ERROR); + } + // Cleanup the cache. + this.cache.deleteExpiredEntries(); + // Put the new entry into the cache. + this.cache.addEntry(connection.address, credentials.username || '', callbackHash, result, serverInfo); + return result; + } +} +exports.CallbackWorkflow = CallbackWorkflow; +/** + * Generate the finishing command document for authentication. Will be a + * saslStart or saslContinue depending on the presence of a conversation id. + */ +function finishCommandDocument(token, conversationId) { + if (conversationId != null && typeof conversationId === 'number') { + return { + saslContinue: 1, + conversationId: conversationId, + payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token })) + }; + } + // saslContinue requires a conversationId in the command to be valid so in this + // case the server allows "step two" to actually be a saslStart with the token + // as the jwt since the use of the cached value has no correlating conversating + // on the particular connection. + return { + saslStart: 1, + mechanism: providers_1.AuthMechanism.MONGODB_OIDC, + payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token })) + }; +} +/** + * Determines if a result returned from a request or refresh callback + * function is invalid. This means the result is nullish, doesn't contain + * the accessToken required field, and does not contain extra fields. + */ +function isCallbackResultInvalid(tokenResult) { + if (tokenResult == null || typeof tokenResult !== 'object') + return true; + if (!('accessToken' in tokenResult)) + return true; + return !Object.getOwnPropertyNames(tokenResult).every(prop => RESULT_PROPERTIES.includes(prop)); +} +/** + * Generate the saslStart command document. + */ +function startCommandDocument(credentials) { + const payload = {}; + if (credentials.username) { + payload.n = credentials.username; + } + return { + saslStart: 1, + autoAuthorize: 1, + mechanism: providers_1.AuthMechanism.MONGODB_OIDC, + payload: new bson_1.Binary(bson_1.BSON.serialize(payload)) + }; +} +//# sourceMappingURL=callback_workflow.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map new file mode 100644 index 00000000..ac85e9b5 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map @@ -0,0 +1 @@ +{"version":3,"file":"callback_workflow.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/callback_workflow.ts"],"names":[],"mappings":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AE,CAAC;QACZ,aAAa,EAAE,CAAC;QAChB,SAAS,EAAE,yBAAa,CAAC,YAAY;QACrC,OAAO,EAAE,IAAI,aAAM,CAAC,WAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;KAC7C,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js new file mode 100644 index 00000000..34251dd7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.commandDocument = exports.ServiceWorkflow = void 0; +const bson_1 = require("bson"); +const utils_1 = require("../../../utils"); +const providers_1 = require("../providers"); +/** + * Common behaviour for OIDC device workflows. + * @internal + */ +class ServiceWorkflow { + /** + * Execute the workflow. Looks for AWS_WEB_IDENTITY_TOKEN_FILE in the environment + * and then attempts to read the token from that path. + */ + async execute(connection, credentials) { + const token = await this.getToken(credentials); + const command = commandDocument(token); + return connection.command((0, utils_1.ns)(credentials.source), command, undefined); + } + /** + * Get the document to add for speculative authentication. + */ + async speculativeAuth(credentials) { + const token = await this.getToken(credentials); + const document = commandDocument(token); + document.db = credentials.source; + return { speculativeAuthenticate: document }; + } +} +exports.ServiceWorkflow = ServiceWorkflow; +/** + * Create the saslStart command document. + */ +function commandDocument(token) { + return { + saslStart: 1, + mechanism: providers_1.AuthMechanism.MONGODB_OIDC, + payload: bson_1.BSON.serialize({ jwt: token }) + }; +} +exports.commandDocument = commandDocument; +//# sourceMappingURL=service_workflow.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js.map new file mode 100644 index 00000000..e22321b9 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js.map @@ -0,0 +1 @@ +{"version":3,"file":"service_workflow.js","sourceRoot":"","sources":["../../../../src/cmap/auth/mongodb_oidc/service_workflow.ts"],"names":[],"mappings":";;;AAAA,+BAA2C;AAE3C,0CAAoC;AAIpC,4CAA6C;AAE7C;;;GAGG;AACH,MAAsB,eAAe;IACnC;;;OAGG;IACH,KAAK,CAAC,OAAO,CAAC,UAAsB,EAAE,WAA6B;QACjE,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAC/C,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,OAAO,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,WAAW,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IACxE,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,eAAe,CAAC,WAA6B;QACjD,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAC/C,MAAM,QAAQ,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACxC,QAAQ,CAAC,EAAE,GAAG,WAAW,CAAC,MAAM,CAAC;QACjC,OAAO,EAAE,uBAAuB,EAAE,QAAQ,EAAE,CAAC;IAC/C,CAAC;CAMF;AAzBD,0CAyBC;AAED;;GAEG;AACH,SAAgB,eAAe,CAAC,KAAa;IAC3C,OAAO;QACL,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,yBAAa,CAAC,YAAY;QACrC,OAAO,EAAE,WAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;KACxC,CAAC;AACJ,CAAC;AAND,0CAMC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js new file mode 100644 index 00000000..35cdbbe4 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TokenEntryCache = exports.TokenEntry = void 0; +const cache_1 = require("./cache"); +/* Default expiration is now for when no expiration provided */ +const DEFAULT_EXPIRATION_SECS = 0; +/** @internal */ +class TokenEntry extends cache_1.ExpiringCacheEntry { + /** + * Instantiate the entry. + */ + constructor(tokenResult, serverInfo, expiration) { + super(expiration); + this.tokenResult = tokenResult; + this.serverInfo = serverInfo; + } +} +exports.TokenEntry = TokenEntry; +/** + * Cache of OIDC token entries. + * @internal + */ +class TokenEntryCache extends cache_1.Cache { + /** + * Set an entry in the token cache. + */ + addEntry(address, username, callbackHash, tokenResult, serverInfo) { + const entry = new TokenEntry(tokenResult, serverInfo, tokenResult.expiresInSeconds ?? DEFAULT_EXPIRATION_SECS); + this.entries.set(this.cacheKey(address, username, callbackHash), entry); + return entry; + } + /** + * Delete an entry from the cache. + */ + deleteEntry(address, username, callbackHash) { + this.entries.delete(this.cacheKey(address, username, callbackHash)); + } + /** + * Get an entry from the cache. + */ + getEntry(address, username, callbackHash) { + return this.entries.get(this.cacheKey(address, username, callbackHash)); + } + /** + * Delete all expired entries from the cache. + */ + deleteExpiredEntries() { + for (const [key, entry] of this.entries) { + if (!entry.isValid()) { + this.entries.delete(key); + } + } + } + /** + * Create a cache key from the address and username. + */ + cacheKey(address, username, callbackHash) { + return this.hashedCacheKey(address, username, callbackHash); + } +} +exports.TokenEntryCache = TokenEntryCache; +//# sourceMappingURL=token_entry_cache.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js.map new file mode 100644 index 00000000..03995372 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.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;IAC1E,CAAC;IAED;;OAEG;IACH,oBAAoB;QAClB,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACvC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE;gBACpB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;aAC1B;SACF;IACH,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,OAAe,EAAE,QAAgB,EAAE,YAAoB;QAC9D,OAAO,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;IAC9D,CAAC;CACF;AAnDD,0CAmDC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/plain.js b/nodejs/node_modules/mongodb/lib/cmap/auth/plain.js new file mode 100644 index 00000000..7d197ab2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/plain.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Plain = void 0; +const bson_1 = require("../../bson"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +class Plain extends auth_provider_1.AuthProvider { + async auth(authContext) { + const { connection, credentials } = authContext; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + const { username, password } = credentials; + const payload = new bson_1.Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + await connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined); + } +} +exports.Plain = Plain; +//# sourceMappingURL=plain.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/plain.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/plain.js.map new file mode 100644 index 00000000..70accdde --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/plain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"plain.js","sourceRoot":"","sources":["../../../src/cmap/auth/plain.ts"],"names":[],"mappings":";;;AAAA,qCAAoC;AACpC,uCAA2D;AAC3D,uCAAiC;AACjC,mDAAiE;AAEjE,MAAa,KAAM,SAAQ,4BAAY;IAC5B,KAAK,CAAC,IAAI,CAAC,WAAwB;QAC1C,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC;SACjF;QAED,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,WAAW,CAAC;QAE3C,MAAM,OAAO,GAAG,IAAI,aAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,QAAQ,OAAO,QAAQ,EAAE,CAAC,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG;YACd,SAAS,EAAE,CAAC;YACZ,SAAS,EAAE,OAAO;YAClB,OAAO,EAAE,OAAO;YAChB,aAAa,EAAE,CAAC;SACjB,CAAC;QAEF,MAAM,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IACrE,CAAC;CACF;AAnBD,sBAmBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/providers.js b/nodejs/node_modules/mongodb/lib/cmap/auth/providers.js new file mode 100644 index 00000000..a546512e --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/providers.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AUTH_MECHS_AUTH_SRC_EXTERNAL = exports.AuthMechanism = void 0; +/** @public */ +exports.AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509', + /** @experimental */ + MONGODB_OIDC: 'MONGODB-OIDC' +}); +/** @internal */ +exports.AUTH_MECHS_AUTH_SRC_EXTERNAL = new Set([ + exports.AuthMechanism.MONGODB_GSSAPI, + exports.AuthMechanism.MONGODB_AWS, + exports.AuthMechanism.MONGODB_OIDC, + exports.AuthMechanism.MONGODB_X509 +]); +//# sourceMappingURL=providers.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/providers.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/providers.js.map new file mode 100644 index 00000000..8f177657 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/providers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"providers.js","sourceRoot":"","sources":["../../../src/cmap/auth/providers.ts"],"names":[],"mappings":";;;AAAA,cAAc;AACD,QAAA,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,WAAW,EAAE,aAAa;IAC1B,UAAU,EAAE,YAAY;IACxB,eAAe,EAAE,SAAS;IAC1B,cAAc,EAAE,QAAQ;IACxB,aAAa,EAAE,OAAO;IACtB,kBAAkB,EAAE,aAAa;IACjC,oBAAoB,EAAE,eAAe;IACrC,YAAY,EAAE,cAAc;IAC5B,oBAAoB;IACpB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKZ,gBAAgB;AACH,QAAA,4BAA4B,GAAG,IAAI,GAAG,CAAgB;IACjE,qBAAa,CAAC,cAAc;IAC5B,qBAAa,CAAC,WAAW;IACzB,qBAAa,CAAC,YAAY;IAC1B,qBAAa,CAAC,YAAY;CAC3B,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/scram.js b/nodejs/node_modules/mongodb/lib/cmap/auth/scram.js new file mode 100644 index 00000000..1b6a18ef --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/scram.js @@ -0,0 +1,254 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ScramSHA256 = exports.ScramSHA1 = void 0; +const saslprep_1 = require("@mongodb-js/saslprep"); +const crypto = require("crypto"); +const bson_1 = require("../../bson"); +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +const providers_1 = require("./providers"); +class ScramSHA extends auth_provider_1.AuthProvider { + constructor(cryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + async prepare(handshakeDoc, authContext) { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + const nonce = await (0, utils_1.randomBytes)(24); + // store the nonce for later use + authContext.nonce = nonce; + const request = { + ...handshakeDoc, + speculativeAuthenticate: { + ...makeFirstMessage(cryptoMethod, credentials, nonce), + db: credentials.source + } + }; + return request; + } + async auth(authContext) { + const { reauthenticating, response } = authContext; + if (response?.speculativeAuthenticate && !reauthenticating) { + return continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext); + } + return executeScram(this.cryptoMethod, authContext); + } +} +function cleanUsername(username) { + return username.replace('=', '=3D').replace(',', '=2C'); +} +function clientFirstMessageBare(username, nonce) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} +function makeFirstMessage(cryptoMethod, credentials, nonce) { + const username = cleanUsername(credentials.username); + const mechanism = cryptoMethod === 'sha1' ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA256; + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new bson_1.Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} +async function executeScram(cryptoMethod, authContext) { + const { connection, credentials } = authContext; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + if (!authContext.nonce) { + throw new error_1.MongoInvalidArgumentError('AuthContext must contain a valid nonce property'); + } + const nonce = authContext.nonce; + const db = credentials.source; + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + const response = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, undefined); + await continueScramConversation(cryptoMethod, response, authContext); +} +async function continueScramConversation(cryptoMethod, response, authContext) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + if (!authContext.nonce) { + throw new error_1.MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce'); + } + const nonce = authContext.nonce; + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + const processedPassword = cryptoMethod === 'sha256' ? (0, saslprep_1.saslprep)(password) : passwordDigest(username, password); + const payload = Buffer.isBuffer(response.payload) + ? new bson_1.Binary(response.payload) + : response.payload; + const dict = parsePayload(payload); + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`); + } + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`); + } + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI(processedPassword, Buffer.from(salt, 'base64'), iterations, cryptoMethod); + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [ + clientFirstMessageBare(username, nonce), + payload.toString('utf8'), + withoutProof + ].join(','); + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new bson_1.Binary(Buffer.from(clientFinal)) + }; + const r = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined); + const parsedResponse = parsePayload(r.payload); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + throw new error_1.MongoRuntimeError('Server returned an invalid signature'); + } + if (r.done !== false) { + // If the server sends r.done === true we can save one RTT + return; + } + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + await connection.command((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, undefined); +} +function parsePayload(payload) { + const payloadStr = payload.toString('utf8'); + const dict = {}; + const parts = payloadStr.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = (parts[i].match(/^([^=]*)=(.*)$/) ?? []).slice(1); + dict[valueParts[0]] = valueParts[1]; + } + return dict; +} +function passwordDigest(username, password) { + if (typeof username !== 'string') { + throw new error_1.MongoInvalidArgumentError('Username must be a string'); + } + if (typeof password !== 'string') { + throw new error_1.MongoInvalidArgumentError('Password must be a string'); + } + if (password.length === 0) { + throw new error_1.MongoInvalidArgumentError('Password cannot be empty'); + } + let md5; + try { + md5 = crypto.createHash('md5'); + } + catch (err) { + if (crypto.getFips()) { + // This error is (slightly) more helpful than what comes from OpenSSL directly, e.g. + // 'Error: error:060800C8:digital envelope routines:EVP_DigestInit_ex:disabled for FIPS' + throw new Error('Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode'); + } + throw err; + } + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + const length = Math.max(a.length, b.length); + const res = []; + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + return Buffer.from(res).toString('base64'); +} +function H(method, text) { + return crypto.createHash(method).update(text).digest(); +} +function HMAC(method, key, text) { + return crypto.createHmac(method, key).update(text).digest(); +} +let _hiCache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] != null) { + return _hiCache[key]; + } + // generate the salt + const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod); + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} +function compareDigest(lhs, rhs) { + if (lhs.length !== rhs.length) { + return false; + } + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + return result === 0; +} +class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} +exports.ScramSHA1 = ScramSHA1; +class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} +exports.ScramSHA256 = ScramSHA256; +//# sourceMappingURL=scram.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/scram.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/scram.js.map new file mode 100644 index 00000000..d537945b --- /dev/null +++ b/nodejs/node_modules/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,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,UAAU,EAAE;QAChD,OAAO,MAAM,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;KACzC;IAED,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;KAC3B;IAED,OAAO,MAAM,KAAK,CAAC,CAAC;AACtB,CAAC;AAED,MAAa,SAAU,SAAQ,QAAQ;IACrC;QACE,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;CACF;AAJD,8BAIC;AAED,MAAa,WAAY,SAAQ,QAAQ;IACvC;QACE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAClB,CAAC;CACF;AAJD,kCAIC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/x509.js b/nodejs/node_modules/mongodb/lib/cmap/auth/x509.js new file mode 100644 index 00000000..6f431c49 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/x509.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.X509 = void 0; +const error_1 = require("../../error"); +const utils_1 = require("../../utils"); +const auth_provider_1 = require("./auth_provider"); +class X509 extends auth_provider_1.AuthProvider { + async prepare(handshakeDoc, authContext) { + const { credentials } = authContext; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + return { ...handshakeDoc, speculativeAuthenticate: x509AuthenticateCommand(credentials) }; + } + async auth(authContext) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + const response = authContext.response; + if (response?.speculativeAuthenticate) { + return; + } + await connection.command((0, utils_1.ns)('$external.$cmd'), x509AuthenticateCommand(credentials), undefined); + } +} +exports.X509 = X509; +function x509AuthenticateCommand(credentials) { + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + return command; +} +//# sourceMappingURL=x509.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/auth/x509.js.map b/nodejs/node_modules/mongodb/lib/cmap/auth/x509.js.map new file mode 100644 index 00000000..2429b587 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/auth/x509.js.map @@ -0,0 +1 @@ +{"version":3,"file":"x509.js","sourceRoot":"","sources":["../../../src/cmap/auth/x509.ts"],"names":[],"mappings":";;;AACA,uCAA2D;AAC3D,uCAAiC;AAEjC,mDAAiE;AAGjE,MAAa,IAAK,SAAQ,4BAAY;IAC3B,KAAK,CAAC,OAAO,CACpB,YAA+B,EAC/B,WAAwB;QAExB,MAAM,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QACpC,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC;SACjF;QACD,OAAO,EAAE,GAAG,YAAY,EAAE,uBAAuB,EAAE,uBAAuB,CAAC,WAAW,CAAC,EAAE,CAAC;IAC5F,CAAC;IAEQ,KAAK,CAAC,IAAI,CAAC,WAAwB;QAC1C,MAAM,UAAU,GAAG,WAAW,CAAC,UAAU,CAAC;QAC1C,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC;QAC5C,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,oCAA4B,CAAC,uCAAuC,CAAC,CAAC;SACjF;QACD,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;QAEtC,IAAI,QAAQ,EAAE,uBAAuB,EAAE;YACrC,OAAO;SACR;QAED,MAAM,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,gBAAgB,CAAC,EAAE,uBAAuB,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,CAAC;IAClG,CAAC;CACF;AA1BD,oBA0BC;AAED,SAAS,uBAAuB,CAAC,WAA6B;IAC5D,MAAM,OAAO,GAAa,EAAE,YAAY,EAAE,CAAC,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC;IACzE,IAAI,WAAW,CAAC,QAAQ,EAAE;QACxB,OAAO,CAAC,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC;KACrC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/command_monitoring_events.js b/nodejs/node_modules/mongodb/lib/cmap/command_monitoring_events.js new file mode 100644 index 00000000..0969033e --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/command_monitoring_events.js @@ -0,0 +1,253 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SENSITIVE_COMMANDS = exports.CommandFailedEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = void 0; +const constants_1 = require("../constants"); +const utils_1 = require("../utils"); +const commands_1 = require("./commands"); +/** + * An event indicating the start of a given command + * @public + * @category Event + */ +class CommandStartedEvent { + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor(connection, command, serverConnectionId) { + /** @internal */ + this.name = constants_1.COMMAND_STARTED; + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + // TODO: remove in major revision, this is not spec behavior + if (exports.SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = command.databaseName; + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + this.serverConnectionId = serverConnectionId; + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandStartedEvent = CommandStartedEvent; +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, reply, started, serverConnectionId) { + /** @internal */ + this.name = constants_1.COMMAND_SUCCEEDED; + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = (0, utils_1.calculateDurationInMs)(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + this.serverConnectionId = serverConnectionId; + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandSucceededEvent = CommandSucceededEvent; +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, error, started, serverConnectionId) { + /** @internal */ + this.name = constants_1.COMMAND_FAILED; + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = (0, utils_1.calculateDurationInMs)(started); + this.failure = maybeRedact(commandName, cmd, error); + this.serverConnectionId = serverConnectionId; + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandFailedEvent = CommandFailedEvent; +/** + * Commands that we want to redact because of the sensitive nature of their contents + * @internal + */ +exports.SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); +const HELLO_COMMANDS = new Set(['hello', constants_1.LEGACY_HELLO_COMMAND, constants_1.LEGACY_HELLO_COMMAND_CAMEL_CASE]); +// helper methods +const extractCommandName = (commandDoc) => Object.keys(commandDoc)[0]; +const namespace = (command) => command.ns; +const collectionName = (command) => command.ns.split('.')[1]; +const maybeRedact = (commandName, commandDoc, result) => exports.SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldSelector: 'projection' +}; +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command) { + if (command instanceof commands_1.OpMsgRequest) { + return (0, utils_1.deepCopy)(command.command); + } + if (command.query?.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command + result = Object.assign({}, command.query.$query); + } + else { + // up-convert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = (0, utils_1.deepCopy)(command.query[key]); + } + }); + } + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = (0, utils_1.deepCopy)(command[legacyKey]); + } + }); + OP_QUERY_KEYS.forEach(key => { + if (command[key]) { + result[key] = command[key]; + } + }); + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; + } + if (command.query.$explain) { + return { explain: result }; + } + return result; + } + const clonedQuery = {}; + const clonedCommand = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = (0, utils_1.deepCopy)(command.query[k]); + } + clonedCommand.query = clonedQuery; + } + for (const k in command) { + if (k === 'query') + continue; + clonedCommand[k] = (0, utils_1.deepCopy)(command[k]); + } + return command.query ? clonedQuery : clonedCommand; +} +function extractReply(command, reply) { + if (!reply) { + return reply; + } + if (command instanceof commands_1.OpMsgRequest) { + return (0, utils_1.deepCopy)(reply.result ? reply.result : reply); + } + // is this a legacy find command? + if (command.query && command.query.$query != null) { + return { + ok: 1, + cursor: { + id: (0, utils_1.deepCopy)(reply.cursorId), + ns: namespace(command), + firstBatch: (0, utils_1.deepCopy)(reply.documents) + } + }; + } + return (0, utils_1.deepCopy)(reply.result ? reply.result : reply); +} +function extractConnectionDetails(connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} +//# sourceMappingURL=command_monitoring_events.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map b/nodejs/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map new file mode 100644 index 00000000..0b26ecb8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command_monitoring_events.js","sourceRoot":"","sources":["../../src/cmap/command_monitoring_events.ts"],"names":[],"mappings":";;;AACA,4CAMsB;AACtB,oCAA2D;AAC3D,yCAA8F;AAG9F;;;;GAIG;AACH,MAAa,mBAAmB;IAmB9B;;;;;;OAMG;IACH,YACE,UAAsB,EACtB,OAAiC,EACjC,kBAAiC;QAbnC,gBAAgB;QAChB,SAAI,GAAG,2BAAe,CAAC;QAcrB,MAAM,GAAG,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;QACpC,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,EAAE,OAA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AK,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,aAAa,CAAC;AACrD,CAAC;AAED,SAAS,YAAY,CAAC,OAAiC,EAAE,KAAgB;IACvE,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,KAAK,CAAC;KACd;IAED,IAAI,OAAO,YAAY,uBAAY,EAAE;QACnC,OAAO,IAAA,gBAAQ,EAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;KACtD;IAED,iCAAiC;IACjC,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,EAAE;QACjD,OAAO;YACL,EAAE,EAAE,CAAC;YACL,MAAM,EAAE;gBACN,EAAE,EAAE,IAAA,gBAAQ,EAAC,KAAK,CAAC,QAAQ,CAAC;gBAC5B,EAAE,EAAE,SAAS,CAAC,OAAO,CAAC;gBACtB,UAAU,EAAE,IAAA,gBAAQ,EAAC,KAAK,CAAC,SAAS,CAAC;aACtC;SACF,CAAC;KACH;IAED,OAAO,IAAA,gBAAQ,EAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,wBAAwB,CAAC,UAAsB;IACtD,IAAI,YAAY,CAAC;IACjB,IAAI,IAAI,IAAI,UAAU,EAAE;QACtB,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;KAC9B;IACD,OAAO;QACL,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,SAAS,EAAE,UAAU,CAAC,SAAS;QAC/B,YAAY;KACb,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/commands.js b/nodejs/node_modules/mongodb/lib/cmap/commands.js new file mode 100644 index 00000000..a11f55cc --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/commands.js @@ -0,0 +1,531 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OpCompressedRequest = exports.OpMsgResponse = exports.OpMsgRequest = exports.OpQueryResponse = exports.OpQueryRequest = void 0; +const BSON = require("../bson"); +const error_1 = require("../error"); +const compression_1 = require("./wire_protocol/compression"); +const constants_1 = require("./wire_protocol/constants"); +// Incrementing request id +let _requestId = 0; +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SECONDARY = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +class OpQueryRequest { + constructor(databaseName, query, options) { + this.databaseName = databaseName; + this.query = query; + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + const ns = `${databaseName}.$cmd`; + if (typeof databaseName !== 'string') { + throw new error_1.MongoRuntimeError('Database name must be a string for a query'); + } + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) + throw new error_1.MongoRuntimeError('A query document must be specified for query'); + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoRuntimeError('Namespace cannot contain a null character'); + } + // Basic options + this.ns = ns; + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + this.requestId = options.requestId ?? OpQueryRequest.getRequestId(); + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.batchSize = this.numberToReturn; + // Flags + this.tailable = false; + this.secondaryOk = typeof options.secondaryOk === 'boolean' ? options.secondaryOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; + } + /** Assign next request Id. */ + incRequestId() { + this.requestId = _requestId++; + } + /** Peek next request Id. */ + nextRequestId() { + return _requestId + 1; + } + /** Increment then return next request Id. */ + static getRequestId() { + return ++_requestId; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const buffers = []; + let projection = null; + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + if (this.secondaryOk) { + flags |= OPTS_SECONDARY; + } + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + if (this.partial) { + flags |= OPTS_PARTIAL; + } + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) + this.numberToReturn = this.batchSize; + // Allocate write protocol header buffer + const header = Buffer.alloc(4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + // Add header to buffers + buffers.push(header); + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add query document + buffers.push(query); + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + // Total message size + const totalLength = header.length + query.length + (projection ? projection.length : 0); + // Set up the index + let index = 4; + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + // Write header information OP_QUERY + header[index + 3] = (constants_1.OP_QUERY >> 24) & 0xff; + header[index + 2] = (constants_1.OP_QUERY >> 16) & 0xff; + header[index + 1] = (constants_1.OP_QUERY >> 8) & 0xff; + header[index] = constants_1.OP_QUERY & 0xff; + index = index + 4; + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + // Return the buffers + return buffers; + } +} +exports.OpQueryRequest = OpQueryRequest; +/** @internal */ +class OpQueryResponse { + constructor(message, msgHeader, msgBody, opts) { + this.documents = new Array(0); + /** moreToCome is an OP_MSG only concept */ + this.moreToCome = false; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + // Flag values + this.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + isParsed() { + return this.parsed; + } + parse(options) { + // Don't parse again if not needed + if (this.parsed) + return; + options = options ?? {}; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + let bsonSize; + // Set up the options + const _options = { + useBigInt64, + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + // Position within OP_REPLY at which documents start + // (See https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + // Read the message body + this.responseFlags = this.data.readInt32LE(0); + this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8)); + this.startingFrom = this.data.readInt32LE(12); + this.numberReturned = this.data.readInt32LE(16); + // Preallocate document array + this.documents = new Array(this.numberReturned); + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + // Parse Body + for (let i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } + else { + this.documents[i] = BSON.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + // Adjust the index + this.index = this.index + bsonSize; + } + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + // Set parsed + this.parsed = true; + } +} +exports.OpQueryResponse = OpQueryResponse; +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; +/** @internal */ +class OpMsgRequest { + constructor(databaseName, command, options) { + this.databaseName = databaseName; + this.command = command; + this.options = options; + // Basic options needed to be passed in + if (command == null) + throw new error_1.MongoInvalidArgumentError('Query document must be specified for query'); + // Basic options + this.command.$db = databaseName; + // Ensure empty options + this.options = options ?? {}; + // Additional options + this.requestId = options.requestId ? options.requestId : OpMsgRequest.getRequestId(); + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + toBin() { + const buffers = []; + let flags = 0; + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + const header = Buffer.alloc(4 * 4 + // Header + 4 // Flags + ); + buffers.push(header); + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(constants_1.OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + makeDocumentSegment(buffers, document) { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + return payloadTypeBuffer.length + documentBuffer.length; + } + serializeBson(document) { + return BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } + static getRequestId() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} +exports.OpMsgRequest = OpMsgRequest; +/** @internal */ +class OpMsgResponse { + constructor(message, msgHeader, msgBody, opts) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + this.documents = []; + } + isParsed() { + return this.parsed; + } + parse(options) { + // Don't parse again if not needed + if (this.parsed) + return; + options = options ?? {}; + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + const validation = this.parseBsonSerializationOptions(options); + // Set up the options + const bsonOptions = { + useBigInt64, + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp, + validation + // Due to the strictness of the BSON libraries validation option we need this cast + }; + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : BSON.deserialize(bin, bsonOptions)); + this.index += bsonSize; + } + else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new error_1.MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } + } + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + bsonOptions.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], bsonOptions); + this.documents = [doc]; + } + this.parsed = true; + } + parseBsonSerializationOptions({ enableUtf8Validation }) { + if (enableUtf8Validation === false) { + return { utf8: false }; + } + return { utf8: { writeErrors: false } }; + } +} +exports.OpMsgResponse = OpMsgResponse; +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID +/** + * @internal + * + * An OP_COMPRESSED request wraps either an OP_QUERY or OP_MSG message. + */ +class OpCompressedRequest { + constructor(command, options) { + this.command = command; + this.options = options; + } + // Return whether a command contains an uncompressible command term + // Will return true if command contains no uncompressible command terms + static canCompress(command) { + const commandDoc = command instanceof OpMsgRequest ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !compression_1.uncompressibleCommands.has(commandName); + } + async toBin() { + const concatenatedOriginalCommandBuffer = Buffer.concat(this.command.toBin()); + // otherwise, compress the message + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + // Compress the message body + const compressedMessage = await (0, compression_1.compress)(this.options, messageToBeCompressed); + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, 0); // messageLength + msgHeader.writeInt32LE(this.command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(constants_1.OP_COMPRESSED, 12); // opCode + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compression_1.Compressor[this.options.agreedCompressor], 8); // compressorID + return [msgHeader, compressionDetails, compressedMessage]; + } +} +exports.OpCompressedRequest = OpCompressedRequest; +//# sourceMappingURL=commands.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/commands.js.map b/nodejs/node_modules/mongodb/lib/cmap/commands.js.map new file mode 100644 index 00000000..ead067e1 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/commands.js.map @@ -0,0 +1 @@ +{"version":3,"file":"commands.js","sourceRoot":"","sources":["../../src/cmap/commands.ts"],"names":[],"mappings":";;;AACA,gCAAgC;AAChC,oCAAwE;AAIxE,6DAKqC;AACrC,yDAA4E;AAE5E,0BAA0B;AAC1B,IAAI,UAAU,GAAG,CAAC,CAAC;AAEnB,cAAc;AACd,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,iBAAiB;AACjB,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,aAAa,GAAG,CAAC,CAAC;A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EAAE,iBAAiB,CAAC,CAAC;IAC5D,CAAC;CACF;AAzCD,kDAyCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connect.js b/nodejs/node_modules/mongodb/lib/cmap/connect.js new file mode 100644 index 00000000..99112bd8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connect.js @@ -0,0 +1,364 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeSocket = exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.prepareHandshakeDocument = exports.performInitialHandshake = exports.makeConnection = exports.connect = void 0; +const net = require("net"); +const tls = require("tls"); +const constants_1 = require("../constants"); +const deps_1 = require("../deps"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const auth_provider_1 = require("./auth/auth_provider"); +const providers_1 = require("./auth/providers"); +const connection_1 = require("./connection"); +const constants_2 = require("./wire_protocol/constants"); +async function connect(options) { + let connection = null; + try { + const socket = await makeSocket(options); + connection = makeConnection(options, socket); + await performInitialHandshake(connection, options); + return connection; + } + catch (error) { + connection?.destroy(); + throw error; + } +} +exports.connect = connect; +function makeConnection(options, socket) { + let ConnectionType = options.connectionType ?? connection_1.Connection; + if (options.autoEncrypter) { + ConnectionType = connection_1.CryptoConnection; + } + return new ConnectionType(socket, options); +} +exports.makeConnection = makeConnection; +function checkSupportedServer(hello, options) { + const maxWireVersion = Number(hello.maxWireVersion); + const minWireVersion = Number(hello.minWireVersion); + const serverVersionHighEnough = !Number.isNaN(maxWireVersion) && maxWireVersion >= constants_2.MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = !Number.isNaN(minWireVersion) && minWireVersion <= constants_2.MAX_SUPPORTED_WIRE_VERSION; + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(hello.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_2.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MAX_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); + } + const message = `Server at ${options.hostAddress} reports maximum wire version ${JSON.stringify(hello.maxWireVersion) ?? 0}, but this version of the Node.js Driver requires at least ${constants_2.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MIN_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); +} +async function performInitialHandshake(conn, options) { + const credentials = options.credentials; + if (credentials) { + if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && + !options.authProviders.getOrCreateProvider(credentials.mechanism)) { + throw new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`); + } + } + const authContext = new auth_provider_1.AuthContext(conn, credentials, options); + conn.authContext = authContext; + const handshakeDoc = await prepareHandshakeDocument(authContext); + // @ts-expect-error: TODO(NODE-5141): The options need to be filtered properly, Connection options differ from Command options + const handshakeOptions = { ...options }; + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; + } + const start = new Date().getTime(); + const response = await conn.command((0, utils_1.ns)('admin.$cmd'), handshakeDoc, handshakeOptions); + if (!('isWritablePrimary' in response)) { + // Provide hello-style response document. + response.isWritablePrimary = response[constants_1.LEGACY_HELLO_COMMAND]; + } + if (response.helloOk) { + conn.helloOk = true; + } + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + throw supportedServerErr; + } + if (options.loadBalanced) { + if (!response.serviceId) { + throw new error_1.MongoCompatibilityError('Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.'); + } + } + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.hello = response; + conn.lastHelloMS = new Date().getTime() - start; + if (!response.arbiterOnly && credentials) { + // store the response on auth context + authContext.response = response; + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = options.authProviders.getOrCreateProvider(resolvedCredentials.mechanism); + if (!provider) { + throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`); + } + try { + await provider.auth(authContext); + } + catch (error) { + if (error instanceof error_1.MongoError) { + error.addErrorLabel(error_1.MongoErrorLabel.HandshakeError); + if ((0, error_1.needsRetryableWriteLabel)(error, response.maxWireVersion)) { + error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + } + throw error; + } + } + // Connection establishment is socket creation (tcp handshake, tls handshake, MongoDB handshake (saslStart, saslContinue)) + // Once connection is established, command logging can log events (if enabled) + conn.established = true; +} +exports.performInitialHandshake = performInitialHandshake; +/** + * @internal + * + * This function is only exposed for testing purposes. + */ +async function prepareHandshakeDocument(authContext) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const clientMetadata = await options.extendedMetadata; + const handshakeDoc = { + [serverApi?.version || options.loadBalanced === true ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: 1, + helloOk: true, + client: clientMetadata, + compression: compressors + }; + if (options.loadBalanced === true) { + handshakeDoc.loadBalanced = true; + } + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + const provider = authContext.options.authProviders.getOrCreateProvider(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256); + if (!provider) { + // This auth mechanism is always present. + throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`); + } + return provider.prepare(handshakeDoc, authContext); + } + const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism); + if (!provider) { + throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`); + } + return provider.prepare(handshakeDoc, authContext); + } + return handshakeDoc; +} +exports.prepareHandshakeDocument = prepareHandshakeDocument; +/** @public */ +exports.LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +]; +/** @public */ +exports.LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +]; +function parseConnectOptions(options) { + const hostAddress = options.hostAddress; + if (!hostAddress) + throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required'); + const result = {}; + for (const name of exports.LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; + } + } + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result; + } + else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result; + } + else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} +function parseSslOptions(options) { + const result = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of exports.LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; + } + } + if (options.existingSocket) { + result.socket = options.existingSocket; + } + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + return result; +} +async function makeSocket(options) { + const useTLS = options.tls ?? false; + const noDelay = options.noDelay ?? true; + const connectTimeoutMS = options.connectTimeoutMS ?? 30000; + const existingSocket = options.existingSocket; + let socket; + if (options.proxyHost != null) { + // Currently, only Socks5 is supported. + return makeSocks5Connection({ + ...options, + connectTimeoutMS // Should always be present for Socks5 + }); + } + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); + } + socket = tlsSocket; + } + else if (existingSocket) { + // In the TLS case, parseSslOptions() sets options.socket to existingSocket, + // so we only need to handle the non-TLS case here (where existingSocket + // gives us all we need out of the box). + socket = existingSocket; + } + else { + socket = net.createConnection(parseConnectOptions(options)); + } + socket.setKeepAlive(true, 300000); + socket.setTimeout(connectTimeoutMS); + socket.setNoDelay(noDelay); + let cancellationHandler = null; + const { promise: connectedSocket, resolve, reject } = (0, utils_1.promiseWithResolvers)(); + if (existingSocket) { + resolve(socket); + } + else { + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + socket + .once(connectEvent, () => resolve(socket)) + .once('error', error => reject(connectionFailureError('error', error))) + .once('timeout', () => reject(connectionFailureError('timeout'))) + .once('close', () => reject(connectionFailureError('close'))); + if (options.cancellationToken != null) { + cancellationHandler = () => reject(connectionFailureError('cancel')); + options.cancellationToken.once('cancel', cancellationHandler); + } + } + try { + socket = await connectedSocket; + return socket; + } + catch (error) { + socket.destroy(); + throw error; + } + finally { + socket.setTimeout(0); + socket.removeAllListeners(); + if (cancellationHandler != null) { + options.cancellationToken?.removeListener('cancel', cancellationHandler); + } + } +} +exports.makeSocket = makeSocket; +let socks = null; +function loadSocks() { + if (socks == null) { + const socksImport = (0, deps_1.getSocks)(); + if ('kModuleError' in socksImport) { + throw socksImport.kModuleError; + } + socks = socksImport; + } + return socks; +} +async function makeSocks5Connection(options) { + const hostAddress = utils_1.HostAddress.fromHostPort(options.proxyHost ?? '', // proxyHost is guaranteed to set here + options.proxyPort ?? 1080); + // First, connect to the proxy server itself: + const rawSocket = await makeSocket({ + ...options, + hostAddress, + tls: false, + proxyHost: undefined + }); + const destination = parseConnectOptions(options); + if (typeof destination.host !== 'string' || typeof destination.port !== 'number') { + throw new error_1.MongoInvalidArgumentError('Can only make Socks5 connections to TCP hosts'); + } + socks ??= loadSocks(); + try { + // Then, establish the Socks5 proxy connection: + const { socket } = await socks.SocksClient.createConnection({ + existing_socket: rawSocket, + timeout: options.connectTimeoutMS, + command: 'connect', + destination: { + host: destination.host, + port: destination.port + }, + proxy: { + // host and port are ignored because we pass existing_socket + host: 'iLoveJavaScript', + port: 0, + type: 5, + userId: options.proxyUsername || undefined, + password: options.proxyPassword || undefined + } + }); + // Finally, now treat the resulting duplex stream as the + // socket over which we send and receive wire protocol messages: + return await makeSocket({ + ...options, + existingSocket: socket, + proxyHost: undefined + }); + } + catch (error) { + throw connectionFailureError('error', error); + } +} +function connectionFailureError(type, cause) { + switch (type) { + case 'error': + return new error_1.MongoNetworkError(error_1.MongoError.buildErrorMessage(cause), { cause }); + case 'timeout': + return new error_1.MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new error_1.MongoNetworkError('connection closed'); + case 'cancel': + return new error_1.MongoNetworkError('connection establishment was cancelled'); + default: + return new error_1.MongoNetworkError('unknown network error'); + } +} +//# sourceMappingURL=connect.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connect.js.map b/nodejs/node_modules/mongodb/lib/cmap/connect.js.map new file mode 100644 index 00000000..ea24bc80 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/cmap/connect.ts"],"names":[],"mappings":";;;AACA,2BAA2B;AAE3B,2BAA2B;AAG3B,4CAAoD;AACpD,kCAAkD;AAClD,oCASkB;AAClB,oCAAiE;AACjE,wDAAmD;AACnD,gDAAiD;AACjD,6CAKsB;AACtB,yDAKmC;AAK5B,KAAK,UAAU,OAAO,CAAC,OAA0B;IACtD,IAAI,UAAU,GAAsB,IAAI,CAAC;IACzC,IAAI;QACF,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;QACzC,UAAU,GAAG,cAAc,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC7C,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACnD,OAAO,UAAU,CAA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OAAO,MAAM,UAAU,CAAC;YACtB,GAAG,OAAO;YACV,cAAc,EAAE,MAAM;YACtB,SAAS,EAAE,SAAS;SACrB,CAAC,CAAC;KACJ;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;KAC9C;AACH,CAAC;AAID,SAAS,sBAAsB,CAC7B,IAA8C,EAC9C,KAAa;IAEb,QAAQ,IAAI,EAAE;QACZ,KAAK,OAAO;YACV,OAAO,IAAI,yBAAiB,CAAC,kBAAU,CAAC,iBAAiB,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/E,KAAK,SAAS;YACZ,OAAO,IAAI,gCAAwB,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO;YACV,OAAO,IAAI,yBAAiB,CAAC,mBAAmB,CAAC,CAAC;QACpD,KAAK,QAAQ;YACX,OAAO,IAAI,yBAAiB,CAAC,wCAAwC,CAAC,CAAC;QACzE;YACE,OAAO,IAAI,yBAAiB,CAAC,uBAAuB,CAAC,CAAC;KACzD;AACH,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connection.js b/nodejs/node_modules/mongodb/lib/cmap/connection.js new file mode 100644 index 00000000..686c14fc --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connection.js @@ -0,0 +1,457 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CryptoConnection = exports.SizedMessageTransform = exports.Connection = exports.hasSessionSupport = void 0; +const stream_1 = require("stream"); +const timers_1 = require("timers"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_logger_1 = require("../mongo_logger"); +const mongo_types_1 = require("../mongo_types"); +const read_preference_1 = require("../read_preference"); +const common_1 = require("../sdam/common"); +const sessions_1 = require("../sessions"); +const utils_1 = require("../utils"); +const command_monitoring_events_1 = require("./command_monitoring_events"); +const commands_1 = require("./commands"); +const stream_description_1 = require("./stream_description"); +const compression_1 = require("./wire_protocol/compression"); +const on_data_1 = require("./wire_protocol/on_data"); +const shared_1 = require("./wire_protocol/shared"); +/** @internal */ +function hasSessionSupport(conn) { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null; +} +exports.hasSessionSupport = hasSessionSupport; +function streamIdentifier(stream, options) { + if (options.proxyHost) { + // If proxy options are specified, the properties of `stream` itself + // will not accurately reflect what endpoint this is connected to. + return options.hostAddress.toString(); + } + const { remoteAddress, remotePort } = stream; + if (typeof remoteAddress === 'string' && typeof remotePort === 'number') { + return utils_1.HostAddress.fromHostPort(remoteAddress, remotePort).toString(); + } + return (0, utils_1.uuidV4)().toString('hex'); +} +/** @internal */ +class Connection extends mongo_types_1.TypedEventEmitter { + constructor(stream, options) { + super(); + this.lastHelloMS = -1; + this.helloOk = false; + this.delayedTimeoutId = null; + /** Indicates that the connection (including underlying TCP socket) has been closed. */ + this.closed = false; + this.clusterTime = null; + this.error = null; + this.dataEvents = null; + this.socket = stream; + this.id = options.id; + this.address = streamIdentifier(stream, options); + this.socketTimeoutMS = options.socketTimeoutMS ?? 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.mongoLogger = options.mongoLogger; + this.established = false; + this.description = new stream_description_1.StreamDescription(this.address, options); + this.generation = options.generation; + this.lastUseTime = (0, utils_1.now)(); + this.messageStream = this.socket + .on('error', this.onError.bind(this)) + .pipe(new SizedMessageTransform({ connection: this })) + .on('error', this.onError.bind(this)); + this.socket.on('close', this.onClose.bind(this)); + this.socket.on('timeout', this.onTimeout.bind(this)); + } + get hello() { + return this.description.hello; + } + // the `connect` method stores the result of the handshake hello on the connection + set hello(response) { + this.description.receiveResponse(response); + Object.freeze(this.description); + } + get serviceId() { + return this.hello?.serviceId; + } + get loadBalanced() { + return this.description.loadBalanced; + } + get idleTime() { + return (0, utils_1.calculateDurationInMs)(this.lastUseTime); + } + get hasSessionSupport() { + return this.description.logicalSessionTimeoutMinutes != null; + } + get supportsOpMsg() { + return (this.description != null && + (0, utils_1.maxWireVersion)(this) >= 6 && + !this.description.__nodejs_mock_server__); + } + get shouldEmitAndLogCommand() { + return ((this.monitorCommands || + (this.established && + !this.authContext?.reauthenticating && + this.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.COMMAND, mongo_logger_1.SeverityLevel.DEBUG))) ?? + false); + } + markAvailable() { + this.lastUseTime = (0, utils_1.now)(); + } + onError(error) { + this.cleanup(error); + } + onClose() { + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(new error_1.MongoNetworkError(message)); + } + onTimeout() { + this.delayedTimeoutId = (0, timers_1.setTimeout)(() => { + const message = `connection ${this.id} to ${this.address} timed out`; + const beforeHandshake = this.hello == null; + this.cleanup(new error_1.MongoNetworkTimeoutError(message, { beforeHandshake })); + }, 1).unref(); // No need for this timer to hold the event loop open + } + destroy() { + if (this.closed) { + return; + } + // load balanced mode requires that these listeners remain on the connection + // after cleanup on timeouts, errors or close so we remove them before calling + // cleanup. + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(new error_1.MongoNetworkError(message)); + } + /** + * A method that cleans up the connection. When `force` is true, this method + * forcibly destroys the socket. + * + * If an error is provided, any in-flight operations will be closed with the error. + * + * This method does nothing if the connection is already closed. + */ + cleanup(error) { + if (this.closed) { + return; + } + this.socket.destroy(); + this.error = error; + this.dataEvents?.throw(error).then(undefined, () => null); // squash unhandled rejection + this.closed = true; + this.emit(Connection.CLOSE); + } + prepareCommand(db, command, options) { + let cmd = { ...command }; + const readPreference = (0, shared_1.getReadPreference)(options); + const session = options?.session; + let clusterTime = this.clusterTime; + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + cmd.apiVersion = version; + if (strict != null) + cmd.apiStrict = strict; + if (deprecationErrors != null) + cmd.apiDeprecationErrors = deprecationErrors; + } + if (this.hasSessionSupport && session) { + if (session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) { + clusterTime = session.clusterTime; + } + const sessionError = (0, sessions_1.applySession)(session, cmd, options); + if (sessionError) + throw sessionError; + } + else if (session?.explicit) { + throw new error_1.MongoCompatibilityError('Current topology does not support sessions'); + } + // if we have a known cluster time, gossip it + if (clusterTime) { + cmd.$clusterTime = clusterTime; + } + // For standalone, drivers MUST NOT set $readPreference. + if (this.description.type !== common_1.ServerType.Standalone) { + if (!(0, shared_1.isSharded)(this) && + !this.description.loadBalanced && + this.supportsOpMsg && + options.directConnection === true && + readPreference?.mode === 'primary') { + // For mongos and load balancers with 'primary' mode, drivers MUST NOT set $readPreference. + // For all other types with a direct connection, if the read preference is 'primary' + // (driver sets 'primary' as default if no read preference is configured), + // the $readPreference MUST be set to 'primaryPreferred' + // to ensure that any server type can handle the request. + cmd.$readPreference = read_preference_1.ReadPreference.primaryPreferred.toJSON(); + } + else if ((0, shared_1.isSharded)(this) && !this.supportsOpMsg && readPreference?.mode !== 'primary') { + // When sending a read operation via OP_QUERY and the $readPreference modifier, + // the query MUST be provided using the $query modifier. + cmd = { + $query: cmd, + $readPreference: readPreference.toJSON() + }; + } + else if (readPreference?.mode !== 'primary') { + // For mode 'primary', drivers MUST NOT set $readPreference. + // For all other read preference modes (i.e. 'secondary', 'primaryPreferred', ...), + // drivers MUST set $readPreference + cmd.$readPreference = readPreference.toJSON(); + } + } + const commandOptions = { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + secondaryOk: readPreference.secondaryOk(), + ...options + }; + const message = this.supportsOpMsg + ? new commands_1.OpMsgRequest(db, cmd, commandOptions) + : new commands_1.OpQueryRequest(db, cmd, commandOptions); + return message; + } + async *sendWire(message, options) { + this.throwIfAborted(); + if (typeof options.socketTimeoutMS === 'number') { + this.socket.setTimeout(options.socketTimeoutMS); + } + else if (this.socketTimeoutMS !== 0) { + this.socket.setTimeout(this.socketTimeoutMS); + } + try { + await this.writeCommand(message, { + agreedCompressor: this.description.compressor ?? 'none', + zlibCompressionLevel: this.description.zlibCompressionLevel + }); + if (options.noResponse) { + yield { ok: 1 }; + return; + } + this.throwIfAborted(); + for await (const response of this.readMany()) { + this.socket.setTimeout(0); + response.parse(options); + const [document] = response.documents; + if (!Buffer.isBuffer(document)) { + const { session } = options; + if (session) { + (0, sessions_1.updateSessionFromResponse)(session, document); + } + if (document.$clusterTime) { + this.clusterTime = document.$clusterTime; + this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + } + yield document; + this.throwIfAborted(); + if (typeof options.socketTimeoutMS === 'number') { + this.socket.setTimeout(options.socketTimeoutMS); + } + else if (this.socketTimeoutMS !== 0) { + this.socket.setTimeout(this.socketTimeoutMS); + } + } + } + finally { + this.socket.setTimeout(0); + } + } + async *sendCommand(ns, command, options = {}) { + const message = this.prepareCommand(ns.db, command, options); + let started = 0; + if (this.shouldEmitAndLogCommand) { + started = (0, utils_1.now)(); + this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_STARTED, message.databaseName, this.established, new command_monitoring_events_1.CommandStartedEvent(this, message, this.description.serverConnectionId)); + } + let document; + try { + this.throwIfAborted(); + for await (document of this.sendWire(message, options)) { + if (!Buffer.isBuffer(document) && document.writeConcernError) { + throw new error_1.MongoWriteConcernError(document.writeConcernError, document); + } + if (!Buffer.isBuffer(document) && + (document.ok === 0 || document.$err || document.errmsg || document.code)) { + throw new error_1.MongoServerError(document); + } + if (this.shouldEmitAndLogCommand) { + this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : document, started, this.description.serverConnectionId)); + } + yield document; + this.throwIfAborted(); + } + } + catch (error) { + if (this.shouldEmitAndLogCommand) { + if (error.name === 'MongoWriteConcernError') { + this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : document, started, this.description.serverConnectionId)); + } + else { + this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_FAILED, message.databaseName, this.established, new command_monitoring_events_1.CommandFailedEvent(this, message, error, started, this.description.serverConnectionId)); + } + } + throw error; + } + } + async command(ns, command, options = {}) { + this.throwIfAborted(); + for await (const document of this.sendCommand(ns, command, options)) { + return document; + } + throw new error_1.MongoUnexpectedServerResponseError('Unable to get response from server'); + } + exhaustCommand(ns, command, options, replyListener) { + const exhaustLoop = async () => { + this.throwIfAborted(); + for await (const reply of this.sendCommand(ns, command, options)) { + replyListener(undefined, reply); + this.throwIfAborted(); + } + throw new error_1.MongoUnexpectedServerResponseError('Server ended moreToCome unexpectedly'); + }; + exhaustLoop().catch(replyListener); + } + throwIfAborted() { + if (this.error) + throw this.error; + } + /** + * @internal + * + * Writes an OP_MSG or OP_QUERY request to the socket, optionally compressing the command. This method + * waits until the socket's buffer has emptied (the Nodejs socket `drain` event has fired). + */ + async writeCommand(command, options) { + const finalCommand = options.agreedCompressor === 'none' || !commands_1.OpCompressedRequest.canCompress(command) + ? command + : new commands_1.OpCompressedRequest(command, { + agreedCompressor: options.agreedCompressor ?? 'none', + zlibCompressionLevel: options.zlibCompressionLevel ?? 0 + }); + const buffer = Buffer.concat(await finalCommand.toBin()); + if (this.socket.write(buffer)) + return; + return (0, utils_1.once)(this.socket, 'drain'); + } + /** + * @internal + * + * Returns an async generator that yields full wire protocol messages from the underlying socket. This function + * yields messages until `moreToCome` is false or not present in a response, or the caller cancels the request + * by calling `return` on the generator. + * + * Note that `for-await` loops call `return` automatically when the loop is exited. + */ + async *readMany() { + try { + this.dataEvents = (0, on_data_1.onData)(this.messageStream); + for await (const message of this.dataEvents) { + const response = await (0, compression_1.decompressResponse)(message); + yield response; + if (!response.moreToCome) { + return; + } + } + } + finally { + this.dataEvents = null; + this.throwIfAborted(); + } + } +} +/** @event */ +Connection.COMMAND_STARTED = constants_1.COMMAND_STARTED; +/** @event */ +Connection.COMMAND_SUCCEEDED = constants_1.COMMAND_SUCCEEDED; +/** @event */ +Connection.COMMAND_FAILED = constants_1.COMMAND_FAILED; +/** @event */ +Connection.CLUSTER_TIME_RECEIVED = constants_1.CLUSTER_TIME_RECEIVED; +/** @event */ +Connection.CLOSE = constants_1.CLOSE; +/** @event */ +Connection.PINNED = constants_1.PINNED; +/** @event */ +Connection.UNPINNED = constants_1.UNPINNED; +exports.Connection = Connection; +/** @internal */ +class SizedMessageTransform extends stream_1.Transform { + constructor({ connection }) { + super({ objectMode: false }); + this.bufferPool = new utils_1.BufferPool(); + this.connection = connection; + } + _transform(chunk, encoding, callback) { + if (this.connection.delayedTimeoutId != null) { + (0, timers_1.clearTimeout)(this.connection.delayedTimeoutId); + this.connection.delayedTimeoutId = null; + } + this.bufferPool.append(chunk); + const sizeOfMessage = this.bufferPool.getInt32(); + if (sizeOfMessage == null) { + return callback(); + } + if (sizeOfMessage < 0) { + return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, too small`)); + } + if (sizeOfMessage > this.bufferPool.length) { + return callback(); + } + const message = this.bufferPool.read(sizeOfMessage); + return callback(null, message); + } +} +exports.SizedMessageTransform = SizedMessageTransform; +/** @internal */ +class CryptoConnection extends Connection { + constructor(stream, options) { + super(stream, options); + this.autoEncrypter = options.autoEncrypter; + } + /** @internal @override */ + async command(ns, cmd, options) { + const { autoEncrypter } = this; + if (!autoEncrypter) { + throw new error_1.MongoMissingDependencyError('No AutoEncrypter available for encryption'); + } + const serverWireVersion = (0, utils_1.maxWireVersion)(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options); + } + if (serverWireVersion < 8) { + throw new error_1.MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2'); + } + // Save sort or indexKeys based on the command being run + // the encrypt API serializes our JS objects to BSON to pass to the native code layer + // and then deserializes the encrypted result, the protocol level components + // of the command (ex. sort) are then converted to JS objects potentially losing + // import key order information. These fields are never encrypted so we can save the values + // from before the encryption and replace them after encryption has been performed + const sort = cmd.find || cmd.findAndModify ? cmd.sort : null; + const indexKeys = cmd.createIndexes + ? cmd.indexes.map((index) => index.key) + : null; + const encrypted = await autoEncrypter.encrypt(ns.toString(), cmd, options); + // Replace the saved values + if (sort != null && (cmd.find || cmd.findAndModify)) { + encrypted.sort = sort; + } + if (indexKeys != null && cmd.createIndexes) { + for (const [offset, index] of indexKeys.entries()) { + // @ts-expect-error `encrypted` is a generic "command", but we've narrowed for only `createIndexes` commands here + encrypted.indexes[offset].key = index; + } + } + const response = await super.command(ns, encrypted, options); + return autoEncrypter.decrypt(response, options); + } +} +exports.CryptoConnection = CryptoConnection; +//# sourceMappingURL=connection.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connection.js.map b/nodejs/node_modules/mongodb/lib/cmap/connection.js.map new file mode 100644 index 00000000..00c0b8ac --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/cmap/connection.ts"],"names":[],"mappings":";;;AAAA,mCAA0E;AAC1E,mCAAkD;AAIlD,4CAQsB;AACtB,oCASkB;AAGlB,kDAA0F;AAC1F,gDAA2E;AAC3E,wDAA6E;AAC7E,2CAA4C;AAC5C,0CAA0F;AAC1F,oCAUkB;AAIlB,2EAIqC;AACrC,yCAOoB;AAGpB,6DAAwF;AACxF,6DAAsF;AACtF,qDAAiD;AACjD,mDAAsE;AA4EtE,gBAAgB;AAChB,SAAgB,iBAAiB,CAAC,IAAgB;IAChD,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;IACrC,OAAO,WAAW,CAAC,4BAA4B,IAAI,IAAI,CAAC;AAC1D,CAAC;AAHD,8CAGC;AAED,SAAS,gBAAgB,CAAC,MAAc,EAAE,OAA0B;IAClE,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,oEAAoE;QACpE,kEAAkE;QAClE,OAAO,OAAO,CAAC,WAAW,CAAC,Q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ACjH,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC;aACvC;SACF;QAED,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAE7D,OAAO,aAAa,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;CACF;AA7DD,4CA6DC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connection_pool.js b/nodejs/node_modules/mongodb/lib/cmap/connection_pool.js new file mode 100644 index 00000000..d091b555 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connection_pool.js @@ -0,0 +1,564 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPool = exports.PoolState = void 0; +const timers_1 = require("timers"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +const connect_1 = require("./connect"); +const connection_1 = require("./connection"); +const connection_pool_events_1 = require("./connection_pool_events"); +const errors_1 = require("./errors"); +const metrics_1 = require("./metrics"); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPending = Symbol('pending'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); +/** @internal */ +const kPoolState = Symbol('poolState'); +/** @internal */ +exports.PoolState = Object.freeze({ + paused: 'paused', + ready: 'ready', + closed: 'closed' +}); +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +class ConnectionPool extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + super(); + this.options = Object.freeze({ + connectionType: connection_1.Connection, + ...options, + maxPoolSize: options.maxPoolSize ?? 100, + minPoolSize: options.minPoolSize ?? 0, + maxConnecting: options.maxConnecting ?? 2, + maxIdleTimeMS: options.maxIdleTimeMS ?? 0, + waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, + minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, + autoEncrypter: options.autoEncrypter + }); + if (this.options.minPoolSize > this.options.maxPoolSize) { + throw new error_1.MongoInvalidArgumentError('Connection pool minimum size must not be greater than maximum pool size'); + } + this[kPoolState] = exports.PoolState.paused; + this[kServer] = server; + this[kConnections] = new utils_1.List(); + this[kPending] = 0; + this[kCheckedOut] = new Set(); + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = (0, utils_1.makeCounter)(1); + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new utils_1.List(); + this[kMetrics] = new metrics_1.ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + this.mongoLogger = this[kServer].topology.client?.mongoLogger; + this.component = 'connection'; + process.nextTick(() => { + this.emitAndLog(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); + }); + } + /** The address of the endpoint the pool is connected to */ + get address() { + return this.options.hostAddress.toString(); + } + /** + * Check if the pool has been closed + * + * TODO(NODE-3263): We can remove this property once shell no longer needs it + */ + get closed() { + return this[kPoolState] === exports.PoolState.closed; + } + /** An integer representing the SDAM generation of the pool */ + get generation() { + return this[kGeneration]; + } + /** An integer expressing how many total connections (available + pending + in use) the pool currently has */ + get totalConnectionCount() { + return (this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount); + } + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount() { + return this[kConnections].length; + } + get pendingConnectionCount() { + return this[kPending]; + } + get currentCheckedOutCount() { + return this[kCheckedOut].size; + } + get waitQueueSize() { + return this[kWaitQueue].length; + } + get loadBalanced() { + return this.options.loadBalanced; + } + get serviceGenerations() { + return this[kServiceGenerations]; + } + get serverError() { + return this[kServer].description.error; + } + /** + * This is exposed ONLY for use in mongosh, to enable + * killing all connections if a user quits the shell with + * operations in progress. + * + * This property may be removed as a part of NODE-3263. + */ + get checkedOutConnections() { + return this[kCheckedOut]; + } + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + waitQueueErrorMetrics() { + return this[kMetrics].info(this.options.maxPoolSize); + } + /** + * Set the pool state to "ready" + */ + ready() { + if (this[kPoolState] !== exports.PoolState.paused) { + return; + } + this[kPoolState] = exports.PoolState.ready; + this.emitAndLog(ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this)); + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this.ensureMinPoolSize(); + } + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + */ + async checkOut() { + this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this)); + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + const { promise, resolve, reject } = (0, utils_1.promiseWithResolvers)(); + const waitQueueMember = { + resolve, + reject, + timeoutController: new utils_1.TimeoutController(waitQueueTimeoutMS) + }; + waitQueueMember.timeoutController.signal.addEventListener('abort', () => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timeoutController.clear(); + this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'timeout')); + waitQueueMember.reject(new errors_1.WaitQueueTimeoutError(this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', this.address)); + }); + this[kWaitQueue].push(waitQueueMember); + process.nextTick(() => this.processWaitQueue()); + return promise; + } + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection) { + if (!this[kCheckedOut].has(connection)) { + return; + } + const poolClosed = this.closed; + const stale = this.connectionIsStale(connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + this[kCheckedOut].delete(connection); + this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + this.destroyConnection(connection, reason); + } + process.nextTick(() => this.processWaitQueue()); + } + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear(options = {}) { + if (this.closed) { + return; + } + // handle load balanced case + if (this.loadBalanced) { + const { serviceId } = options; + if (!serviceId) { + throw new error_1.MongoRuntimeError('ConnectionPool.clear() called in load balanced mode with no serviceId.'); + } + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + throw new error_1.MongoRuntimeError('Service generations are required in load balancer mode.'); + } + else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); + } + this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId })); + return; + } + // handle non load-balanced case + const interruptInUseConnections = options.interruptInUseConnections ?? false; + const oldGeneration = this[kGeneration]; + this[kGeneration] += 1; + const alreadyPaused = this[kPoolState] === exports.PoolState.paused; + this[kPoolState] = exports.PoolState.paused; + this.clearMinPoolSizeTimer(); + if (!alreadyPaused) { + this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { + interruptInUseConnections + })); + } + if (interruptInUseConnections) { + process.nextTick(() => this.interruptInUseConnections(oldGeneration)); + } + this.processWaitQueue(); + } + /** + * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. + * + * Only connections where `connection.generation <= minGeneration` are killed. + */ + interruptInUseConnections(minGeneration) { + for (const connection of this[kCheckedOut]) { + if (connection.generation <= minGeneration) { + connection.onError(new errors_1.PoolClearedOnNetworkError(this)); + this.checkIn(connection); + } + } + } + /** Close the pool */ + close() { + if (this.closed) { + return; + } + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + this[kPoolState] = exports.PoolState.closed; + this.clearMinPoolSizeTimer(); + this.processWaitQueue(); + for (const conn of this[kConnections]) { + this.emitAndLog(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, 'poolClosed')); + conn.destroy(); + } + this[kConnections].clear(); + this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.ConnectionPoolClosedEvent(this)); + } + /** + * @internal + * Reauthenticate a connection + */ + async reauthenticate(connection) { + const authContext = connection.authContext; + if (!authContext) { + throw new error_1.MongoRuntimeError('No auth context found on connection.'); + } + const credentials = authContext.credentials; + if (!credentials) { + throw new error_1.MongoMissingCredentialsError('Connection is missing credentials when asked to reauthenticate'); + } + const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello); + const provider = this[kServer].topology.client.s.authProviders.getOrCreateProvider(resolvedCredentials.mechanism); + if (!provider) { + throw new error_1.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${credentials.mechanism}`); + } + await provider.reauth(authContext); + return; + } + /** Clear the min pool size timer */ + clearMinPoolSizeTimer() { + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + (0, timers_1.clearTimeout)(minPoolSizeTimer); + } + } + destroyConnection(connection, reason) { + this.emitAndLog(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason)); + // destroy the connection + connection.destroy(); + } + connectionIsStale(connection) { + const serviceId = connection.serviceId; + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + return connection.generation !== generation; + } + return connection.generation !== this[kGeneration]; + } + connectionIsIdle(connection) { + return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); + } + /** + * Destroys a connection if the connection is perished. + * + * @returns `true` if the connection was destroyed, `false` otherwise. + */ + destroyConnectionIfPerished(connection) { + const isStale = this.connectionIsStale(connection); + const isIdle = this.connectionIsIdle(connection); + if (!isStale && !isIdle && !connection.closed) { + return false; + } + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + this.destroyConnection(connection, reason); + return true; + } + createConnection(callback) { + const connectOptions = { + ...this.options, + id: this[kConnectionCounter].next().value, + generation: this[kGeneration], + cancellationToken: this[kCancellationToken], + mongoLogger: this.mongoLogger, + authProviders: this[kServer].topology.client.s.authProviders + }; + this[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + this.emitAndLog(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id })); + (0, connect_1.connect)(connectOptions).then(connection => { + // The pool might have closed since we started trying to create a connection + if (this[kPoolState] !== exports.PoolState.ready) { + this[kPending]--; + connection.destroy(); + callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this)); + return; + } + // forward all events from the connection to the pool + for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e) => this.emit(event, e)); + } + if (this.loadBalanced) { + connection.on(connection_1.Connection.PINNED, pinType => this[kMetrics].markPinned(pinType)); + connection.on(connection_1.Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType)); + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = this.serviceGenerations.get(sid))) { + connection.generation = generation; + } + else { + this.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + connection.markAvailable(); + this.emitAndLog(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection)); + this[kPending]--; + callback(undefined, connection); + }, error => { + this[kPending]--; + this.emitAndLog(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, { id: connectOptions.id, serviceId: undefined }, 'error', + // TODO(NODE-5192): Remove this cast + error)); + if (error instanceof error_1.MongoNetworkError || error instanceof error_1.MongoServerError) { + error.connectionGeneration = connectOptions.generation; + } + callback(error ?? new error_1.MongoRuntimeError('Connection creation failed without error')); + }); + } + ensureMinPoolSize() { + const minPoolSize = this.options.minPoolSize; + if (this[kPoolState] !== exports.PoolState.ready || minPoolSize === 0) { + return; + } + this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection)); + if (this.totalConnectionCount < minPoolSize && + this.pendingConnectionCount < this.options.maxConnecting) { + // NOTE: ensureMinPoolSize should not try to get all the pending + // connection permits because that potentially delays the availability of + // the connection to a checkout request + this.createConnection((err, connection) => { + if (err) { + this[kServer].handleError(err); + } + if (!err && connection) { + this[kConnections].push(connection); + process.nextTick(() => this.processWaitQueue()); + } + if (this[kPoolState] === exports.PoolState.ready) { + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); + } + }); + } + else { + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); + } + } + processWaitQueue() { + if (this[kProcessingWaitQueue]) { + return; + } + this[kProcessingWaitQueue] = true; + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].first(); + if (!waitQueueMember) { + this[kWaitQueue].shift(); + continue; + } + if (waitQueueMember[kCancelled]) { + this[kWaitQueue].shift(); + continue; + } + if (this[kPoolState] !== exports.PoolState.ready) { + const reason = this.closed ? 'poolClosed' : 'connectionError'; + const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this); + this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason, error)); + waitQueueMember.timeoutController.clear(); + this[kWaitQueue].shift(); + waitQueueMember.reject(error); + continue; + } + if (!this.availableConnectionCount) { + break; + } + const connection = this[kConnections].shift(); + if (!connection) { + break; + } + if (!this.destroyConnectionIfPerished(connection)) { + this[kCheckedOut].add(connection); + this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection)); + waitQueueMember.timeoutController.clear(); + this[kWaitQueue].shift(); + waitQueueMember.resolve(connection); + } + } + const { maxPoolSize, maxConnecting } = this.options; + while (this.waitQueueSize > 0 && + this.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) { + const waitQueueMember = this[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + this.createConnection((err, connection) => { + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + this[kConnections].push(connection); + } + } + else { + if (err) { + this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + // TODO(NODE-5192): Remove this cast + new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'connectionError', err)); + waitQueueMember.reject(err); + } + else if (connection) { + this[kCheckedOut].add(connection); + this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection)); + waitQueueMember.resolve(connection); + } + waitQueueMember.timeoutController.clear(); + } + process.nextTick(() => this.processWaitQueue()); + }); + } + this[kProcessingWaitQueue] = false; + } +} +/** + * Emitted when the connection pool is created. + * @event + */ +ConnectionPool.CONNECTION_POOL_CREATED = constants_1.CONNECTION_POOL_CREATED; +/** + * Emitted once when the connection pool is closed + * @event + */ +ConnectionPool.CONNECTION_POOL_CLOSED = constants_1.CONNECTION_POOL_CLOSED; +/** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ +ConnectionPool.CONNECTION_POOL_CLEARED = constants_1.CONNECTION_POOL_CLEARED; +/** + * Emitted each time the connection pool is marked ready + * @event + */ +ConnectionPool.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY; +/** + * Emitted when a connection is created. + * @event + */ +ConnectionPool.CONNECTION_CREATED = constants_1.CONNECTION_CREATED; +/** + * Emitted when a connection becomes established, and is ready to use + * @event + */ +ConnectionPool.CONNECTION_READY = constants_1.CONNECTION_READY; +/** + * Emitted when a connection is closed + * @event + */ +ConnectionPool.CONNECTION_CLOSED = constants_1.CONNECTION_CLOSED; +/** + * Emitted when an attempt to check out a connection begins + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_STARTED = constants_1.CONNECTION_CHECK_OUT_STARTED; +/** + * Emitted when an attempt to check out a connection fails + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_FAILED = constants_1.CONNECTION_CHECK_OUT_FAILED; +/** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_OUT = constants_1.CONNECTION_CHECKED_OUT; +/** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_IN = constants_1.CONNECTION_CHECKED_IN; +exports.ConnectionPool = ConnectionPool; +//# sourceMappingURL=connection_pool.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connection_pool.js.map b/nodejs/node_modules/mongodb/lib/cmap/connection_pool.js.map new file mode 100644 index 00000000..21445389 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connection_pool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_pool.js","sourceRoot":"","sources":["../../src/cmap/connection_pool.ts"],"names":[],"mappings":";;;AAAA,mCAAkD;AAGlD,4CAasB;AACtB,oCAQkB;AAClB,gDAAsE;AAEtE,oCAMkB;AAClB,uCAAoC;AACpC,6CAAyF;AACzF,qEAYkC;AAClC,qCAKkB;AAClB,uCAAkD;AAElD,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACnC,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,iBAAiB,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrD,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,mBAAmB,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AACzD,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACnC,gBAAgB;AAChB,MAAM,oBAAoB,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;AA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CAAqB,CAAC;AA5EnD,wCAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connection_pool_events.js b/nodejs/node_modules/mongodb/lib/cmap/connection_pool_events.js new file mode 100644 index 00000000..a08d5ac1 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connection_pool_events.js @@ -0,0 +1,186 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPoolClearedEvent = exports.ConnectionCheckedInEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolReadyEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolMonitoringEvent = void 0; +const constants_1 = require("../constants"); +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +class ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + this.time = new Date(); + this.address = pool.address; + } +} +exports.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent; +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_POOL_CREATED; + const { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS } = pool.options; + this.options = { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS }; + } +} +exports.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent; +/** + * An event published when a connection pool is ready + * @public + * @category Event + */ +class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_POOL_READY; + } +} +exports.ConnectionPoolReadyEvent = ConnectionPoolReadyEvent; +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_POOL_CLOSED; + } +} +exports.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent; +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_CREATED; + this.connectionId = connection.id; + } +} +exports.ConnectionCreatedEvent = ConnectionCreatedEvent; +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_READY; + this.connectionId = connection.id; + } +} +exports.ConnectionReadyEvent = ConnectionReadyEvent; +/** + * An event published when a connection is closed + * @public + * @category Event + */ +class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection, reason, error) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_CLOSED; + this.connectionId = connection.id; + this.reason = reason; + this.serviceId = connection.serviceId; + this.error = error ?? null; + } +} +exports.ConnectionClosedEvent = ConnectionClosedEvent; +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_CHECK_OUT_STARTED; + } +} +exports.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent; +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, reason, error) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_CHECK_OUT_FAILED; + this.reason = reason; + this.error = error; + } +} +exports.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent; +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_CHECKED_OUT; + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent; +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_CHECKED_IN; + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedInEvent = ConnectionCheckedInEvent; +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, options = {}) { + super(pool); + /** @internal */ + this.name = constants_1.CONNECTION_POOL_CLEARED; + this.serviceId = options.serviceId; + this.interruptInUseConnections = options.interruptInUseConnections; + } +} +exports.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; +//# sourceMappingURL=connection_pool_events.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/connection_pool_events.js.map b/nodejs/node_modules/mongodb/lib/cmap/connection_pool_events.js.map new file mode 100644 index 00000000..35418c72 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/connection_pool_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_pool_events.js","sourceRoot":"","sources":["../../src/cmap/connection_pool_events.ts"],"names":[],"mappings":";;;AACA,4CAYsB;AAKtB;;;;GAIG;AACH,MAAsB,6BAA6B;IAmBjD,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AAx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AG,kCAAsB,CAAC;QAK5B,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AAXD,8DAWC;AAED;;;;GAIG;AACH,MAAa,wBAAyB,SAAQ,6BAA6B;IAMzE,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAsB;QACtD,KAAK,CAAC,IAAI,CAAC,CAAC;QALd,gBAAgB;QAChB,SAAI,GAAG,iCAAqB,CAAC;QAK3B,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AAXD,4DAWC;AAED;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,6BAA6B;IAQ3E,gBAAgB;IAChB,YACE,IAAoB,EACpB,UAAyE,EAAE;QAE3E,KAAK,CAAC,IAAI,CAAC,CAAC;QARd,gBAAgB;QAChB,SAAI,GAAG,mCAAuB,CAAC;QAQ7B,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IACrE,CAAC;CACF;AAjBD,gEAiBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/errors.js b/nodejs/node_modules/mongodb/lib/cmap/errors.js new file mode 100644 index 00000000..b215a296 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/errors.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WaitQueueTimeoutError = exports.PoolClearedOnNetworkError = exports.PoolClearedError = exports.PoolClosedError = void 0; +const error_1 = require("../error"); +/** + * An error indicating a connection pool is closed + * @category Error + */ +class PoolClosedError extends error_1.MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(pool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + get name() { + return 'MongoPoolClosedError'; + } +} +exports.PoolClosedError = PoolClosedError; +/** + * An error indicating a connection pool is currently paused + * @category Error + */ +class PoolClearedError extends error_1.MongoNetworkError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(pool, message) { + const errorMessage = message + ? message + : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; + super(errorMessage, pool.serverError ? { cause: pool.serverError } : undefined); + this.address = pool.address; + this.addErrorLabel(error_1.MongoErrorLabel.PoolRequstedRetry); + } + get name() { + return 'MongoPoolClearedError'; + } +} +exports.PoolClearedError = PoolClearedError; +/** + * An error indicating that a connection pool has been cleared after the monitor for that server timed out. + * @category Error + */ +class PoolClearedOnNetworkError extends PoolClearedError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(pool) { + super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); + } + get name() { + return 'PoolClearedOnNetworkError'; + } +} +exports.PoolClearedOnNetworkError = PoolClearedOnNetworkError; +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +class WaitQueueTimeoutError extends error_1.MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, address) { + super(message); + this.address = address; + } + get name() { + return 'MongoWaitQueueTimeoutError'; + } +} +exports.WaitQueueTimeoutError = WaitQueueTimeoutError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/errors.js.map b/nodejs/node_modules/mongodb/lib/cmap/errors.js.map new file mode 100644 index 00000000..fcdf5c69 --- /dev/null +++ b/nodejs/node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C,CAAC;CACF;AAnBD,8DAmBC;AAED;;;GAGG;AACH,MAAa,qBAAsB,SAAQ,wBAAgB;IAIzD;;;;;;;;;;QAUI;IACJ,YAAY,OAAe,EAAE,OAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,IAAa,IAAI;QACf,OAAO,4BAA4B,CAAC;IACtC,CAAC;CACF;AAvBD,sDAuBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/handshake/client_metadata.js b/nodejs/node_modules/mongodb/lib/cmap/handshake/client_metadata.js new file mode 100644 index 00000000..84f2cb2f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/handshake/client_metadata.js @@ -0,0 +1,216 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getFAASEnv = exports.addContainerMetadata = exports.makeClientMetadata = exports.LimitedSizeDocument = void 0; +const fs_1 = require("fs"); +const os = require("os"); +const process = require("process"); +const bson_1 = require("../../bson"); +const error_1 = require("../../error"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = require('../../../package.json').version; +/** @internal */ +class LimitedSizeDocument { + constructor(maxSize) { + this.maxSize = maxSize; + this.document = new Map(); + /** BSON overhead: Int32 + Null byte */ + this.documentSize = 5; + } + /** Only adds key/value if the bsonByteLength is less than MAX_SIZE */ + ifItFitsItSits(key, value) { + // The BSON byteLength of the new element is the same as serializing it to its own document + // subtracting the document size int32 and the null terminator. + const newElementSize = bson_1.BSON.serialize(new Map().set(key, value)).byteLength - 5; + if (newElementSize + this.documentSize > this.maxSize) { + return false; + } + this.documentSize += newElementSize; + this.document.set(key, value); + return true; + } + toObject() { + return bson_1.BSON.deserialize(bson_1.BSON.serialize(this.document), { + promoteLongs: false, + promoteBuffers: false, + promoteValues: false, + useBigInt64: false + }); + } +} +exports.LimitedSizeDocument = LimitedSizeDocument; +/** + * From the specs: + * Implementors SHOULD cumulatively update fields in the following order until the document is under the size limit: + * 1. Omit fields from `env` except `env.name`. + * 2. Omit fields from `os` except `os.type`. + * 3. Omit the `env` document entirely. + * 4. Truncate `platform`. -- special we do not truncate this field + */ +function makeClientMetadata(options) { + const metadataDocument = new LimitedSizeDocument(512); + const { appName = '' } = options; + // Add app name first, it must be sent + if (appName.length > 0) { + const name = Buffer.byteLength(appName, 'utf8') <= 128 + ? options.appName + : Buffer.from(appName, 'utf8').subarray(0, 128).toString('utf8'); + metadataDocument.ifItFitsItSits('application', { name }); + } + const { name = '', version = '', platform = '' } = options.driverInfo; + const driverInfo = { + name: name.length > 0 ? `nodejs|${name}` : 'nodejs', + version: version.length > 0 ? `${NODE_DRIVER_VERSION}|${version}` : NODE_DRIVER_VERSION + }; + if (!metadataDocument.ifItFitsItSits('driver', driverInfo)) { + throw new error_1.MongoInvalidArgumentError('Unable to include driverInfo name and version, metadata cannot exceed 512 bytes'); + } + let runtimeInfo = getRuntimeInfo(); + if (platform.length > 0) { + runtimeInfo = `${runtimeInfo}|${platform}`; + } + if (!metadataDocument.ifItFitsItSits('platform', runtimeInfo)) { + throw new error_1.MongoInvalidArgumentError('Unable to include driverInfo platform, metadata cannot exceed 512 bytes'); + } + // Note: order matters, os.type is last so it will be removed last if we're at maxSize + const osInfo = new Map() + .set('name', process.platform) + .set('architecture', process.arch) + .set('version', os.release()) + .set('type', os.type()); + if (!metadataDocument.ifItFitsItSits('os', osInfo)) { + for (const key of osInfo.keys()) { + osInfo.delete(key); + if (osInfo.size === 0) + break; + if (metadataDocument.ifItFitsItSits('os', osInfo)) + break; + } + } + const faasEnv = getFAASEnv(); + if (faasEnv != null) { + if (!metadataDocument.ifItFitsItSits('env', faasEnv)) { + for (const key of faasEnv.keys()) { + faasEnv.delete(key); + if (faasEnv.size === 0) + break; + if (metadataDocument.ifItFitsItSits('env', faasEnv)) + break; + } + } + } + return metadataDocument.toObject(); +} +exports.makeClientMetadata = makeClientMetadata; +let dockerPromise; +/** @internal */ +async function getContainerMetadata() { + const containerMetadata = {}; + dockerPromise ??= fs_1.promises.access('/.dockerenv').then(() => true, () => false); + const isDocker = await dockerPromise; + const { KUBERNETES_SERVICE_HOST = '' } = process.env; + const isKubernetes = KUBERNETES_SERVICE_HOST.length > 0 ? true : false; + if (isDocker) + containerMetadata.runtime = 'docker'; + if (isKubernetes) + containerMetadata.orchestrator = 'kubernetes'; + return containerMetadata; +} +/** + * @internal + * Re-add each metadata value. + * Attempt to add new env container metadata, but keep old data if it does not fit. + */ +async function addContainerMetadata(originalMetadata) { + const containerMetadata = await getContainerMetadata(); + if (Object.keys(containerMetadata).length === 0) + return originalMetadata; + const extendedMetadata = new LimitedSizeDocument(512); + const extendedEnvMetadata = { ...originalMetadata?.env, container: containerMetadata }; + for (const [key, val] of Object.entries(originalMetadata)) { + if (key !== 'env') { + extendedMetadata.ifItFitsItSits(key, val); + } + else { + if (!extendedMetadata.ifItFitsItSits('env', extendedEnvMetadata)) { + // add in old data if newer / extended metadata does not fit + extendedMetadata.ifItFitsItSits('env', val); + } + } + } + if (!('env' in originalMetadata)) { + extendedMetadata.ifItFitsItSits('env', extendedEnvMetadata); + } + return extendedMetadata.toObject(); +} +exports.addContainerMetadata = addContainerMetadata; +/** + * Collects FaaS metadata. + * - `name` MUST be the last key in the Map returned. + */ +function getFAASEnv() { + const { AWS_EXECUTION_ENV = '', AWS_LAMBDA_RUNTIME_API = '', FUNCTIONS_WORKER_RUNTIME = '', K_SERVICE = '', FUNCTION_NAME = '', VERCEL = '', AWS_LAMBDA_FUNCTION_MEMORY_SIZE = '', AWS_REGION = '', FUNCTION_MEMORY_MB = '', FUNCTION_REGION = '', FUNCTION_TIMEOUT_SEC = '', VERCEL_REGION = '' } = process.env; + const isAWSFaaS = AWS_EXECUTION_ENV.startsWith('AWS_Lambda_') || AWS_LAMBDA_RUNTIME_API.length > 0; + const isAzureFaaS = FUNCTIONS_WORKER_RUNTIME.length > 0; + const isGCPFaaS = K_SERVICE.length > 0 || FUNCTION_NAME.length > 0; + const isVercelFaaS = VERCEL.length > 0; + // Note: order matters, name must always be the last key + const faasEnv = new Map(); + // When isVercelFaaS is true so is isAWSFaaS; Vercel inherits the AWS env + if (isVercelFaaS && !(isAzureFaaS || isGCPFaaS)) { + if (VERCEL_REGION.length > 0) { + faasEnv.set('region', VERCEL_REGION); + } + faasEnv.set('name', 'vercel'); + return faasEnv; + } + if (isAWSFaaS && !(isAzureFaaS || isGCPFaaS || isVercelFaaS)) { + if (AWS_REGION.length > 0) { + faasEnv.set('region', AWS_REGION); + } + if (AWS_LAMBDA_FUNCTION_MEMORY_SIZE.length > 0 && + Number.isInteger(+AWS_LAMBDA_FUNCTION_MEMORY_SIZE)) { + faasEnv.set('memory_mb', new bson_1.Int32(AWS_LAMBDA_FUNCTION_MEMORY_SIZE)); + } + faasEnv.set('name', 'aws.lambda'); + return faasEnv; + } + if (isAzureFaaS && !(isGCPFaaS || isAWSFaaS || isVercelFaaS)) { + faasEnv.set('name', 'azure.func'); + return faasEnv; + } + if (isGCPFaaS && !(isAzureFaaS || isAWSFaaS || isVercelFaaS)) { + if (FUNCTION_REGION.length > 0) { + faasEnv.set('region', FUNCTION_REGION); + } + if (FUNCTION_MEMORY_MB.length > 0 && Number.isInteger(+FUNCTION_MEMORY_MB)) { + faasEnv.set('memory_mb', new bson_1.Int32(FUNCTION_MEMORY_MB)); + } + if (FUNCTION_TIMEOUT_SEC.length > 0 && Number.isInteger(+FUNCTION_TIMEOUT_SEC)) { + faasEnv.set('timeout_sec', new bson_1.Int32(FUNCTION_TIMEOUT_SEC)); + } + faasEnv.set('name', 'gcp.func'); + return faasEnv; + } + return null; +} +exports.getFAASEnv = getFAASEnv; +/** + * @internal + * Get current JavaScript runtime platform + * + * NOTE: The version information fetching is intentionally written defensively + * to avoid having a released driver version that becomes incompatible + * with a future change to these global objects. + */ +function getRuntimeInfo() { + if ('Deno' in globalThis) { + const version = typeof Deno?.version?.deno === 'string' ? Deno?.version?.deno : '0.0.0-unknown'; + return `Deno v${version}, ${os.endianness()}`; + } + if ('Bun' in globalThis) { + const version = typeof Bun?.version === 'string' ? Bun?.version : '0.0.0-unknown'; + return `Bun v${version}, ${os.endianness()}`; + } + return `Node.js ${process.version}, ${os.endianness()}`; +} +//# sourceMappingURL=client_metadata.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/handshake/client_metadata.js.map b/nodejs/node_modules/mongodb/lib/cmap/handshake/client_metadata.js.map new file mode 100644 index 00000000..e9d77a38 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/handshake/client_metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client_metadata.js","sourceRoot":"","sources":["../../../src/cmap/handshake/client_metadata.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AACpC,yBAAyB;AACzB,mCAAmC;AAEnC,qCAAwD;AACxD,uCAAwD;AAGxD,8DAA8D;AAC9D,MAAM,mBAAmB,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC,OAAO,CAAC;AAyCrE,gBAAgB;AAChB,MAAa,mBAAmB;IAI9B,YAAoB,OAAe;QAAf,YAAO,GAAP,OAAO,CAAQ;QAH3B,aAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,uCAAuC;QAC/B,iBAAY,GAAG,CAAC,CAAC;IACa,CAAC;IAEvC,sEAAsE;IAC/D,cAAc,CAAC,GAAW,EAAE,KAAmC;QACpE,2FAA2F;QAC3F,+DAA+D;QAC/D,MAAM,cAAc,GAAG,WAAI,CAAC,SAAS,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC;QAEhF,IAAI,cAAc,GAAG,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,OAAO,EAAE;YACrD,OAAO,KAAK,CAAC;SACd;QAED,IAAI,CAAC,YAAY,IAAI,cAAc,CAAC;QAEpC,IAAI,CAAC,QAAQ,CAAC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;KAC9C;IAED,OAAO,WAAW,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,UAAU,EAAE,EAAE,CAAC;AAC1D,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/metrics.js b/nodejs/node_modules/mongodb/lib/cmap/metrics.js new file mode 100644 index 00000000..b510164b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/metrics.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPoolMetrics = void 0; +/** @internal */ +class ConnectionPoolMetrics { + constructor() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; + } + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; + } + else { + this.otherConnections += 1; + } + } + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; + } + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; + } + else { + this.otherConnections -= 1; + } + } + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize) { + return ('Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}`); + } + /** + * Reset the metrics to the initial values. + */ + reset() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} +ConnectionPoolMetrics.TXN = 'txn'; +ConnectionPoolMetrics.CURSOR = 'cursor'; +ConnectionPoolMetrics.OTHER = 'other'; +exports.ConnectionPoolMetrics = ConnectionPoolMetrics; +//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/metrics.js.map b/nodejs/node_modules/mongodb/lib/cmap/metrics.js.map new file mode 100644 index 00000000..c3b5fe25 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/metrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../src/cmap/metrics.ts"],"names":[],"mappings":";;;AAAA,gBAAgB;AAChB,MAAa,qBAAqB;IAAlC;QAKE,mBAAc,GAAG,CAAC,CAAC;QACnB,sBAAiB,GAAG,CAAC,CAAC;QACtB,qBAAgB,GAAG,CAAC,CAAC;IAiDvB,CAAC;IA/CC;;OAEG;IACH,UAAU,CAAC,OAAe;QACxB,IAAI,OAAO,KAAK,qBAAqB,CAAC,GAAG,EAAE;YACzC,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;SAC1B;aAAM,IAAI,OAAO,KAAK,qBAAqB,CAAC,MAAM,EAAE;YACnD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;SAC7B;aAAM;YACL,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;IAED;;OAEG;IACH,YAAY,CAAC,OAAe;QAC1B,IAAI,OAAO,KAAK,qBAAqB,CAAC,GAAG,EAAE;YACzC,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;SAC1B;aAAM,IAAI,OAAO,KAAK,qBAAqB,CAAC,MAAM,EAAE;YACnD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;SAC7B;aAAM;YACL,IAAI,CAAC,gBAAgB,IAAI,CAAC,CAAC;SAC5B;IACH,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,WAAmB;QACtB,OAAO,CACL,kEAAkE;YAClE,gBAAgB,WAAW,IAAI;YAC/B,kCAAkC,IAAI,CAAC,iBAAiB,IAAI;YAC5D,uCAAuC,IAAI,CAAC,cAAc,IAAI;YAC9D,2CAA2C,IAAI,CAAC,gBAAgB,EAAE,CACnE,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,gBAAgB,GAAG,CAAC,CAAC;IAC5B,CAAC;;AAtDe,yBAAG,GAAG,KAAc,AAAjB,CAAkB;AACrB,4BAAM,GAAG,QAAiB,AAApB,CAAqB;AAC3B,2BAAK,GAAG,OAAgB,AAAnB,CAAoB;AAH9B,sDAAqB"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/stream_description.js b/nodejs/node_modules/mongodb/lib/cmap/stream_description.js new file mode 100644 index 00000000..1665c6eb --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/stream_description.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamDescription = void 0; +const bson_1 = require("../bson"); +const common_1 = require("../sdam/common"); +const server_description_1 = require("../sdam/server_description"); +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +]; +/** @public */ +class StreamDescription { + constructor(address, options) { + this.hello = null; + this.address = address; + this.type = common_1.ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options?.logicalSessionTimeoutMinutes; + this.loadBalanced = !!options?.loadBalanced; + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + this.serverConnectionId = null; + } + receiveResponse(response) { + if (response == null) { + return; + } + this.hello = response; + this.type = (0, server_description_1.parseServerType)(response); + if ('connectionId' in response) { + this.serverConnectionId = this.parseServerConnectionID(response.connectionId); + } + else { + this.serverConnectionId = null; + } + for (const field of RESPONSE_FIELDS) { + if (response[field] != null) { + this[field] = response[field]; + } + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; + } + } + if (response.compression) { + this.compressor = this.compressors.filter(c => response.compression?.includes(c))[0]; + } + } + /* @internal */ + parseServerConnectionID(serverConnectionId) { + // Connection ids are always integral, so it's safe to coerce doubles as well as + // any integral type. + return bson_1.Long.isLong(serverConnectionId) + ? serverConnectionId.toBigInt() + : // @ts-expect-error: Doubles are coercible to number + BigInt(serverConnectionId); + } +} +exports.StreamDescription = StreamDescription; +//# sourceMappingURL=stream_description.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/stream_description.js.map b/nodejs/node_modules/mongodb/lib/cmap/stream_description.js.map new file mode 100644 index 00000000..f05a5f0b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/stream_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream_description.js","sourceRoot":"","sources":["../../src/cmap/stream_description.ts"],"names":[],"mappings":";;;AAAA,kCAA2D;AAC3D,2CAA4C;AAC5C,mEAA6D;AAG7D,MAAM,eAAe,GAAG;IACtB,gBAAgB;IAChB,gBAAgB;IAChB,mBAAmB;IACnB,qBAAqB;IACrB,mBAAmB;IACnB,8BAA8B;CACtB,CAAC;AASX,cAAc;AACd,MAAa,iBAAiB;IAoB5B,YAAY,OAAe,EAAE,OAAkC;QAFxD,UAAK,GAAoB,IAAI,CAAC;QAGnC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,mBAAU,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,QAAQ,CAAC;QAClC,IAAI,CAAC,mBAAmB,GAAG,QAAQ,CAAC;QACpC,IAAI,CAAC,iBAAiB,GAAG,MAAM,CAAC;QAChC,IAAI,CAAC,4BAA4B,GAAG,OAAO,EAAE,4BAA4B,CAAC;QAC1E,IAA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AAmD;QACzE,gFAAgF;QAChF,qBAAqB;QACrB,OAAO,WAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC;YACpC,CAAC,CAAC,kBAAkB,CAAC,QAAQ,EAAE;YAC/B,CAAC,CAAC,oDAAoD;gBACpD,MAAM,CAAC,kBAAkB,CAAC,CAAC;IACjC,CAAC;CACF;AAzED,8CAyEC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/compression.js b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/compression.js new file mode 100644 index 00000000..eab3b0d2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/compression.js @@ -0,0 +1,163 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decompressResponse = exports.compressCommand = exports.decompress = exports.compress = exports.uncompressibleCommands = exports.Compressor = void 0; +const util_1 = require("util"); +const zlib = require("zlib"); +const constants_1 = require("../../constants"); +const deps_1 = require("../../deps"); +const error_1 = require("../../error"); +const commands_1 = require("../commands"); +const constants_2 = require("./constants"); +/** @public */ +exports.Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2, + zstd: 3 +}); +exports.uncompressibleCommands = new Set([ + constants_1.LEGACY_HELLO_COMMAND, + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); +const ZSTD_COMPRESSION_LEVEL = 3; +const zlibInflate = (0, util_1.promisify)(zlib.inflate.bind(zlib)); +const zlibDeflate = (0, util_1.promisify)(zlib.deflate.bind(zlib)); +let zstd; +let Snappy = null; +function loadSnappy() { + if (Snappy == null) { + const snappyImport = (0, deps_1.getSnappy)(); + if ('kModuleError' in snappyImport) { + throw snappyImport.kModuleError; + } + Snappy = snappyImport; + } + return Snappy; +} +// Facilitate compressing a message using an agreed compressor +async function compress(options, dataToBeCompressed) { + const zlibOptions = {}; + switch (options.agreedCompressor) { + case 'snappy': { + Snappy ??= loadSnappy(); + return Snappy.compress(dataToBeCompressed); + } + case 'zstd': { + loadZstd(); + if ('kModuleError' in zstd) { + throw zstd['kModuleError']; + } + return zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); + } + case 'zlib': { + if (options.zlibCompressionLevel) { + zlibOptions.level = options.zlibCompressionLevel; + } + return zlibDeflate(dataToBeCompressed, zlibOptions); + } + default: { + throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`); + } + } +} +exports.compress = compress; +// Decompress a message using the given compressor +async function decompress(compressorID, compressedData) { + if (compressorID !== exports.Compressor.snappy && + compressorID !== exports.Compressor.zstd && + compressorID !== exports.Compressor.zlib && + compressorID !== exports.Compressor.none) { + throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`); + } + switch (compressorID) { + case exports.Compressor.snappy: { + Snappy ??= loadSnappy(); + return Snappy.uncompress(compressedData, { asBuffer: true }); + } + case exports.Compressor.zstd: { + loadZstd(); + if ('kModuleError' in zstd) { + throw zstd['kModuleError']; + } + return zstd.decompress(compressedData); + } + case exports.Compressor.zlib: { + return zlibInflate(compressedData); + } + default: { + return compressedData; + } + } +} +exports.decompress = decompress; +/** + * Load ZStandard if it is not already set. + */ +function loadZstd() { + if (!zstd) { + zstd = (0, deps_1.getZstdLibrary)(); + } +} +const MESSAGE_HEADER_SIZE = 16; +/** + * @internal + * + * Compresses an OP_MSG or OP_QUERY message, if compression is configured. This method + * also serializes the command to BSON. + */ +async function compressCommand(command, description) { + const finalCommand = description.agreedCompressor === 'none' || !commands_1.OpCompressedRequest.canCompress(command) + ? command + : new commands_1.OpCompressedRequest(command, { + agreedCompressor: description.agreedCompressor ?? 'none', + zlibCompressionLevel: description.zlibCompressionLevel ?? 0 + }); + const data = await finalCommand.toBin(); + return Buffer.concat(data); +} +exports.compressCommand = compressCommand; +/** + * @internal + * + * Decompresses an OP_MSG or OP_QUERY response from the server, if compression is configured. + * + * This method does not parse the response's BSON. + */ +async function decompressResponse(message) { + const messageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + if (messageHeader.opCode !== constants_2.OP_COMPRESSED) { + const ResponseType = messageHeader.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpQueryResponse; + const messageBody = message.subarray(MESSAGE_HEADER_SIZE); + return new ResponseType(message, messageHeader, messageBody); + } + const header = { + ...messageHeader, + fromCompressed: true, + opCode: message.readInt32LE(MESSAGE_HEADER_SIZE), + length: message.readInt32LE(MESSAGE_HEADER_SIZE + 4) + }; + const compressorID = message[MESSAGE_HEADER_SIZE + 8]; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + // recalculate based on wrapped opcode + const ResponseType = header.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpQueryResponse; + const messageBody = await decompress(compressorID, compressedBuffer); + if (messageBody.length !== header.length) { + throw new error_1.MongoDecompressionError('Message body and message header must be the same length'); + } + return new ResponseType(message, header, messageBody); +} +exports.decompressResponse = decompressResponse; +//# sourceMappingURL=compression.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map new file mode 100644 index 00000000..b91f1c37 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/compression.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AACjC,6BAA6B;AAE7B,+CAAuD;AACvD,qCAAuF;AACvF,uCAAiF;AACjF,0CAMqB;AACrB,2CAAoD;AAEpD,cAAc;AACD,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,IAAI,E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,CAAC,mBAAmB,CAAC,CAAC;QAC1D,OAAO,IAAI,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC;KAC9D;IAED,MAAM,MAAM,GAAkB;QAC5B,GAAG,aAAa;QAChB,cAAc,EAAE,IAAI;QACpB,MAAM,EAAE,OAAO,CAAC,WAAW,CAAC,mBAAmB,CAAC;QAChD,MAAM,EAAE,OAAO,CAAC,WAAW,CAAC,mBAAmB,GAAG,CAAC,CAAC;KACrD,CAAC;IACF,MAAM,YAAY,GAAG,OAAO,CAAC,mBAAmB,GAAG,CAAC,CAAC,CAAC;IACtD,MAAM,gBAAgB,GAAG,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,CAAC,CAAC,CAAC;IAEhE,sCAAsC;IACtC,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,KAAK,kBAAM,CAAC,CAAC,CAAC,wBAAa,CAAC,CAAC,CAAC,0BAAe,CAAC;IAChF,MAAM,WAAW,GAAG,MAAM,UAAU,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC;IACrE,IAAI,WAAW,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE;QACxC,MAAM,IAAI,+BAAuB,CAAC,yDAAyD,CAAC,CAAC;KAC9F;IACD,OAAO,IAAI,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AACxD,CAAC;AAhCD,gDAgCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/constants.js b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/constants.js new file mode 100644 index 00000000..b250859a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/constants.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_DELETE = exports.OP_QUERY = exports.OP_INSERT = exports.OP_UPDATE = exports.OP_REPLY = exports.MIN_SUPPORTED_QE_SERVER_VERSION = exports.MIN_SUPPORTED_QE_WIRE_VERSION = exports.MAX_SUPPORTED_WIRE_VERSION = exports.MIN_SUPPORTED_WIRE_VERSION = exports.MAX_SUPPORTED_SERVER_VERSION = exports.MIN_SUPPORTED_SERVER_VERSION = void 0; +exports.MIN_SUPPORTED_SERVER_VERSION = '3.6'; +exports.MAX_SUPPORTED_SERVER_VERSION = '7.0'; +exports.MIN_SUPPORTED_WIRE_VERSION = 6; +exports.MAX_SUPPORTED_WIRE_VERSION = 21; +exports.MIN_SUPPORTED_QE_WIRE_VERSION = 21; +exports.MIN_SUPPORTED_QE_SERVER_VERSION = '7.0'; +exports.OP_REPLY = 1; +exports.OP_UPDATE = 2001; +exports.OP_INSERT = 2002; +exports.OP_QUERY = 2004; +exports.OP_DELETE = 2006; +exports.OP_COMPRESSED = 2012; +exports.OP_MSG = 2013; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map new file mode 100644 index 00000000..6aa9450b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,4BAA4B,GAAG,KAAK,CAAC;AACrC,QAAA,4BAA4B,GAAG,KAAK,CAAC;AACrC,QAAA,0BAA0B,GAAG,CAAC,CAAC;AAC/B,QAAA,0BAA0B,GAAG,EAAE,CAAC;AAChC,QAAA,6BAA6B,GAAG,EAAE,CAAC;AACnC,QAAA,+BAA+B,GAAG,KAAK,CAAC;AACxC,QAAA,QAAQ,GAAG,CAAC,CAAC;AACb,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,QAAQ,GAAG,IAAI,CAAC;AAChB,QAAA,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,aAAa,GAAG,IAAI,CAAC;AACrB,QAAA,MAAM,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js new file mode 100644 index 00000000..74706c50 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.onData = void 0; +const utils_1 = require("../../utils"); +/** + * onData is adapted from Node.js' events.on helper + * https://nodejs.org/api/events.html#eventsonemitter-eventname-options + * + * Returns an AsyncIterator that iterates each 'data' event emitted from emitter. + * It will reject upon an error event. + */ +function onData(emitter) { + // Setup pending events and pending promise lists + /** + * When the caller has not yet called .next(), we store the + * value from the event in this list. Next time they call .next() + * we pull the first value out of this list and resolve a promise with it. + */ + const unconsumedEvents = new utils_1.List(); + /** + * When there has not yet been an event, a new promise will be created + * and implicitly stored in this list. When an event occurs we take the first + * promise in this list and resolve it. + */ + const unconsumedPromises = new utils_1.List(); + /** + * Stored an error created by an error event. + * This error will turn into a rejection for the subsequent .next() call + */ + let error = null; + /** Set to true only after event listeners have been removed. */ + let finished = false; + const iterator = { + next() { + // First, we consume all unread events + const value = unconsumedEvents.shift(); + if (value != null) { + return Promise.resolve({ value, done: false }); + } + // Then we error, if an error happened + // This happens one time if at all, because after 'error' + // we stop listening + if (error != null) { + const p = Promise.reject(error); + // Only the first element errors + error = null; + return p; + } + // If the iterator is finished, resolve to done + if (finished) + return closeHandler(); + // Wait until an event happens + const { promise, resolve, reject } = (0, utils_1.promiseWithResolvers)(); + unconsumedPromises.push({ resolve, reject }); + return promise; + }, + return() { + return closeHandler(); + }, + throw(err) { + errorHandler(err); + return Promise.resolve({ value: undefined, done: true }); + }, + [Symbol.asyncIterator]() { + return this; + } + }; + // Adding event handlers + emitter.on('data', eventHandler); + emitter.on('error', errorHandler); + return iterator; + function eventHandler(value) { + const promise = unconsumedPromises.shift(); + if (promise != null) + promise.resolve({ value, done: false }); + else + unconsumedEvents.push(value); + } + function errorHandler(err) { + const promise = unconsumedPromises.shift(); + if (promise != null) + promise.reject(err); + else + error = err; + void closeHandler(); + } + function closeHandler() { + // Adding event handlers + emitter.off('data', eventHandler); + emitter.off('error', errorHandler); + finished = true; + const doneResult = { value: undefined, done: finished }; + for (const promise of unconsumedPromises) { + promise.resolve(doneResult); + } + return Promise.resolve(doneResult); + } +} +exports.onData = onData; +//# sourceMappingURL=on_data.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js.map b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js.map new file mode 100644 index 00000000..8fed2f98 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/on_data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"on_data.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/on_data.ts"],"names":[],"mappings":";;;AAEA,uCAAyD;AAWzD;;;;;;GAMG;AACH,SAAgB,MAAM,CAAC,OAAqB;IAC1C,iDAAiD;IACjD;;;;OAIG;IACH,MAAM,gBAAgB,GAAG,IAAI,YAAI,EAAU,CAAC;IAC5C;;;;OAIG;IACH,MAAM,kBAAkB,GAAG,IAAI,YAAI,EAAmB,CAAC;IAEvD;;;OAGG;IACH,IAAI,KAAK,GAAiB,IAAI,CAAC;IAE/B,gEAAgE;IAChE,IAAI,QAAQ,GAAG,KAAK,CAAC;IAErB,MAAM,QAAQ,GAA2B;QACvC,IAAI;YACF,sCAAsC;YACtC,MAAM,KAAK,GAAG,gBAAgB,CAAC,KAAK,EAAE,CAAC;YACvC,IAAI,KAAK,IAAI,IAAI,EAAE;gBACjB,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;aAChD;YAED,sCAAs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AAS,YAAY,CAAC,GAAU;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,CAAC;QAC3C,IAAI,OAAO,IAAI,IAAI;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;;YACpC,KAAK,GAAG,GAAG,CAAC;QACjB,KAAK,YAAY,EAAE,CAAC;IACtB,CAAC;IAED,SAAS,YAAY;QACnB,wBAAwB;QACxB,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAClC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;QACnC,QAAQ,GAAG,IAAI,CAAC;QAChB,MAAM,UAAU,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAW,CAAC;QAEjE,KAAK,MAAM,OAAO,IAAI,kBAAkB,EAAE;YACxC,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;SAC7B;QAED,OAAO,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrC,CAAC;AACH,CAAC;AAjGD,wBAiGC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/shared.js b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/shared.js new file mode 100644 index 00000000..f4d4eeef --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/shared.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isSharded = exports.getReadPreference = void 0; +const error_1 = require("../../error"); +const read_preference_1 = require("../../read_preference"); +const common_1 = require("../../sdam/common"); +const topology_description_1 = require("../../sdam/topology_description"); +function getReadPreference(options) { + // Default to command version of the readPreference. + let readPreference = options?.readPreference ?? read_preference_1.ReadPreference.primary; + if (typeof readPreference === 'string') { + readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + if (!(readPreference instanceof read_preference_1.ReadPreference)) { + throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance'); + } + return readPreference; +} +exports.getReadPreference = getReadPreference; +function isSharded(topologyOrServer) { + if (topologyOrServer == null) { + return false; + } + if (topologyOrServer.description && topologyOrServer.description.type === common_1.ServerType.Mongos) { + return true; + } + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof topology_description_1.TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server) => server.type === common_1.ServerType.Mongos); + } + return false; +} +exports.isSharded = isSharded; +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map new file mode 100644 index 00000000..0861cb85 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../../src/cmap/wire_protocol/shared.ts"],"names":[],"mappings":";;;AAAA,uCAAwD;AAExD,2DAAuD;AACvD,8CAA+C;AAI/C,0EAAsE;AAOtE,SAAgB,iBAAiB,CAAC,OAA8B;IAC9D,oDAAoD;IACpD,IAAI,cAAc,GAAG,OAAO,EAAE,cAAc,IAAI,gCAAc,CAAC,OAAO,CAAC;IAEvE,IAAI,OAAO,cAAc,KAAK,QAAQ,EAAE;QACtC,cAAc,GAAG,gCAAc,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;KAC5D;IAED,IAAI,CAAC,CAAC,cAAc,YAAY,gCAAc,CAAC,EAAE;QAC/C,MAAM,IAAI,iCAAyB,CACjC,2DAA2D,CAC5D,CAAC;KACH;IAED,OAAO,cAAc,CAAC;AACxB,CAAC;AAfD,8CAeC;AAED,SAAgB,SAAS,CAAC,gBAAiD;IACzE,IAAI,gBAAgB,IAAI,IAAI,EAAE;QAC5B,OAAO,KAAK,CAAC;KACd;IAED,IAAI,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,WAAW,CAAC,IAAI,KAAK,mBAAU,CAAC,MAAM,EAAE;QAC3F,OAAO,IAAI,CAAC;KACb;IAED,wFAAwF;IACxF,4CAA4C;IAC5C,IAAI,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,WAAW,YAAY,0CAAmB,EAAE;QAC/F,MAAM,OAAO,GAAwB,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC/F,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAyB,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,mBAAU,CAAC,MAAM,CAAC,CAAC;KACvF;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAjBD,8BAiBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/collection.js b/nodejs/node_modules/mongodb/lib/collection.js new file mode 100644 index 00000000..2cef655b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/collection.js @@ -0,0 +1,630 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Collection = void 0; +const bson_1 = require("./bson"); +const ordered_1 = require("./bulk/ordered"); +const unordered_1 = require("./bulk/unordered"); +const change_stream_1 = require("./change_stream"); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +const find_cursor_1 = require("./cursor/find_cursor"); +const list_indexes_cursor_1 = require("./cursor/list_indexes_cursor"); +const list_search_indexes_cursor_1 = require("./cursor/list_search_indexes_cursor"); +const error_1 = require("./error"); +const bulk_write_1 = require("./operations/bulk_write"); +const count_1 = require("./operations/count"); +const count_documents_1 = require("./operations/count_documents"); +const delete_1 = require("./operations/delete"); +const distinct_1 = require("./operations/distinct"); +const drop_1 = require("./operations/drop"); +const estimated_document_count_1 = require("./operations/estimated_document_count"); +const execute_operation_1 = require("./operations/execute_operation"); +const find_and_modify_1 = require("./operations/find_and_modify"); +const indexes_1 = require("./operations/indexes"); +const insert_1 = require("./operations/insert"); +const is_capped_1 = require("./operations/is_capped"); +const options_operation_1 = require("./operations/options_operation"); +const rename_1 = require("./operations/rename"); +const create_1 = require("./operations/search_indexes/create"); +const drop_2 = require("./operations/search_indexes/drop"); +const update_1 = require("./operations/search_indexes/update"); +const update_2 = require("./operations/update"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +class Collection { + /** + * Create a new Collection instance + * @internal + */ + constructor(db, name, options) { + // Internal state + this.s = { + db, + options, + namespace: new utils_1.MongoDBCollectionNamespace(db.databaseName, name), + pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY, + readPreference: read_preference_1.ReadPreference.fromOptions(options), + bsonOptions: (0, bson_1.resolveBSONOptions)(options, db), + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options) + }; + this.client = db.client; + } + /** + * The name of the database this collection belongs to + */ + get dbName() { + return this.s.namespace.db; + } + /** + * The name of this collection + */ + get collectionName() { + return this.s.namespace.collection; + } + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace() { + return this.fullNamespace.toString(); + } + /** + * @internal + * + * The `MongoDBNamespace` for the collection. + */ + get fullNamespace() { + return this.s.namespace; + } + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } + /** The current index hint for the collection */ + get hint() { + return this.s.collectionHint; + } + set hint(v) { + this.s.collectionHint = (0, utils_1.normalizeHintField)(v); + } + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + */ + async insertOne(doc, options) { + return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + */ + async insertMany(docs, options) { + return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true }))); + } + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @throws MongoDriverError if operations is not an array + */ + async bulkWrite(operations, options) { + if (!Array.isArray(operations)) { + throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + return (0, execute_operation_1.executeOperation)(this.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options ?? { ordered: true }))); + } + /** + * Update a single document in a collection + * + * The value of `update` can be either: + * - UpdateFilter - A document that contains update operator expressions, + * - Document[] - an aggregation pipeline. + * + * @param filter - The filter used to select the document to update + * @param update - The modifications to apply + * @param options - Optional settings for the command + */ + async updateOne(filter, update, options) { + return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + */ + async replaceOne(filter, replacement, options) { + return (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Update multiple documents in a collection + * + * The value of `update` can be either: + * - UpdateFilter - A document that contains update operator expressions, + * - Document[] - an aggregation pipeline. + * + * @param filter - The filter used to select the document to update + * @param update - The modifications to apply + * @param options - Optional settings for the command + */ + async updateMany(filter, update, options) { + return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async deleteOne(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + async deleteMany(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + */ + async rename(newName, options) { + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, { + ...options, + readPreference: read_preference_1.ReadPreference.PRIMARY + })); + } + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + async drop(options) { + return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options)); + } + async findOne(filter = {}, options = {}) { + const cursor = this.find(filter, options).limit(-1).batchSize(1); + const res = await cursor.next(); + await cursor.close(); + return res; + } + find(filter = {}, options = {}) { + return new find_cursor_1.FindCursor(this.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + */ + async options(options) { + return (0, execute_operation_1.executeOperation)(this.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + async isCapped(options) { + return (0, execute_operation_1.executeOperation)(this.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * + * @example + * ```ts + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + async createIndex(indexSpec, options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * + * @example + * ```ts + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + async createIndexes(indexSpecs, options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: undefined }))); + } + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + async dropIndex(indexName, options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, { + ...(0, utils_1.resolveOptions)(this, options), + readPreference: read_preference_1.ReadPreference.primary + })); + } + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + async dropIndexes(options) { + try { + await (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, '*', (0, utils_1.resolveOptions)(this, options))); + return true; + } + catch { + return false; + } + } + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options) { + return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + */ + async indexExists(indexes, options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + async indexInformation(options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * This will always run a count command on all server versions. + * + * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, + * which estimatedDocumentCount uses in its implementation, was not included in v1 of + * the Stable API, and so users of the Stable API with estimatedDocumentCount are + * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid + * encountering errors. + * + * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior} + * @param options - Optional settings for the command + */ + async estimatedDocumentCount(options) { + return (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/ + * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ + * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center + * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * + * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/ + * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ + * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center + * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + async countDocuments(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + async distinct(key, filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + async indexes(options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + async findOneAndDelete(filter, options) { + return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + async findOneAndReplace(filter, replacement, options) { + return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options))); + } + async findOneAndUpdate(filter, update, options) { + return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (!Array.isArray(pipeline)) { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); + } + return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to override the schema that may be defined for this specific collection + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * @example + * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` + * ```ts + * collection.watch<{ _id: number }>() + * .on('change', change => console.log(change._id.toFixed(4))); + * ``` + * + * @example + * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. + * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. + * No need start from scratch on the ChangeStreamInsertDocument type! + * By using an intersection we can save time and ensure defaults remain the same type! + * ```ts + * collection + * .watch & { comment: string }>([ + * { $addFields: { comment: 'big changes' } }, + * { $match: { operationType: 'insert' } } + * ]) + * .on('change', change => { + * change.comment.startsWith('big'); + * change.operationType === 'insert'; + * // No need to narrow in code because the generics did that for us! + * expectType(change.fullDocument); + * }); + * ``` + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TLocal - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeUnorderedBulkOp(options) { + return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options) { + return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); + } + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + */ + async count(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options))); + } + listSearchIndexes(indexNameOrOptions, options) { + options = + typeof indexNameOrOptions === 'object' ? indexNameOrOptions : options == null ? {} : options; + const indexName = indexNameOrOptions == null + ? null + : typeof indexNameOrOptions === 'object' + ? null + : indexNameOrOptions; + return new list_search_indexes_cursor_1.ListSearchIndexesCursor(this, indexName, options); + } + /** + * Creates a single search index for the collection. + * + * @param description - The index description for the new search index. + * @returns A promise that resolves to the name of the new search index. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + async createSearchIndex(description) { + const [index] = await this.createSearchIndexes([description]); + return index; + } + /** + * Creates multiple search indexes for the current collection. + * + * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes. + * @returns A promise that resolves to an array of the newly created search index names. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + * @returns + */ + async createSearchIndexes(descriptions) { + return (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions)); + } + /** + * Deletes a search index by index name. + * + * @param name - The name of the search index to be deleted. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + async dropSearchIndex(name) { + return (0, execute_operation_1.executeOperation)(this.client, new drop_2.DropSearchIndexOperation(this, name)); + } + /** + * Updates a search index by replacing the existing index definition with the provided definition. + * + * @param name - The name of the search index to update. + * @param definition - The new search index definition. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + async updateSearchIndex(name, definition) { + return (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition)); + } +} +exports.Collection = Collection; +//# sourceMappingURL=collection.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/collection.js.map b/nodejs/node_modules/mongodb/lib/collection.js.map new file mode 100644 index 00000000..58fc915f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collection.js","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":";;;AAAA,iCAAsF;AAEtF,4CAAsD;AACtD,gDAA0D;AAC1D,mDAAoG;AACpG,oEAAgE;AAChE,sDAAkD;AAClD,sEAAiE;AACjE,oFAG6C;AAE7C,mCAAoD;AAYpD,wDAA6D;AAE7D,8CAAuE;AACvE,kEAAmG;AACnG,gDAK6B;AAC7B,oDAAgF;AAChF,4CAAwF;AACxF,oFAG+C;AAC/C,sEAAkE;AAElE,kEAOsC;AACtC,kDAY8B;AAC9B,gDAM6B;AAC7B,sDAA2D;AAE3D,sEAAkE;AAClE,gDAA0E;AAC1E,+DAG4C;AAC5C,2DAA4E;AAC5E,+DAAgF;AAChF,gDAO6B;AAC7B,iDAAmE;AACnE,uDAA4E;AAC5E,mCAKiB;AACjB,mDAAyE;AA8BzE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,UAAU;IAOrB;;;OAGG;IACH,YAAY,EAAM,EAAE,IAAY,EAAE,OAA2B;QAC3D,iBAAiB;QACjB,IAAI,CAAC,CAAC,GAAG;YACP,EAAE;YACF,OAAO;YACP,SAAS,EAAE,IAAI,kCAA0B,CAAC,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;YAChE,SAAS,EAAE,EAAE,CAAC,OAAO,EAAE,SAAS,IAAI,0BAAkB;YACtD,cAAc,EAAE,gCAAc,CAAC,WAAW,CAAC,O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,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,eAAe,CAAC,IAAY;QAChC,OAAO,IAAA,oCAAgB,EACrB,IAAI,CAAC,MAAM,EACX,IAAI,+BAAwB,CAAC,IAAsB,EAAE,IAAI,CAAC,CAC3D,CAAC;IACJ,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,iBAAiB,CAAC,IAAY,EAAE,UAAoB;QACxD,OAAO,IAAA,oCAAgB,EACrB,IAAI,CAAC,MAAM,EACX,IAAI,mCAA0B,CAAC,IAAsB,EAAE,IAAI,EAAE,UAAU,CAAC,CACzE,CAAC;IACJ,CAAC;CACF;AAx9BD,gCAw9BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/connection_string.js b/nodejs/node_modules/mongodb/lib/connection_string.js new file mode 100644 index 00000000..b8c8828a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/connection_string.js @@ -0,0 +1,1110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FEATURE_FLAGS = exports.DEFAULT_OPTIONS = exports.OPTIONS = exports.parseOptions = exports.resolveSRVRecord = void 0; +const dns = require("dns"); +const mongodb_connection_string_url_1 = require("mongodb-connection-string-url"); +const url_1 = require("url"); +const mongo_credentials_1 = require("./cmap/auth/mongo_credentials"); +const providers_1 = require("./cmap/auth/providers"); +const client_metadata_1 = require("./cmap/handshake/client_metadata"); +const compression_1 = require("./cmap/wire_protocol/compression"); +const encrypter_1 = require("./encrypter"); +const error_1 = require("./error"); +const mongo_client_1 = require("./mongo_client"); +const mongo_logger_1 = require("./mongo_logger"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const monitor_1 = require("./sdam/monitor"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = 'loadBalanced option not supported when directConnection is provided'; +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +async function resolveSRVRecord(options) { + if (typeof options.srvHost !== 'string') { + throw new error_1.MongoAPIError('Option "srvHost" must not be empty'); + } + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + throw new error_1.MongoAPIError('URI must include hostname, domain name, and tld'); + } + // Asynchronously start TXT resolution so that we do not have to wait until + // the SRV record is resolved before starting a second DNS query. + const lookupAddress = options.srvHost; + const txtResolutionPromise = dns.promises.resolveTxt(lookupAddress); + txtResolutionPromise.catch(() => { + /* rejections will be handled later */ + }); + // Resolve the SRV record and use the result as the list of hosts to connect to. + const addresses = await dns.promises.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`); + if (addresses.length === 0) { + throw new error_1.MongoAPIError('No addresses found at host'); + } + for (const { name } of addresses) { + if (!(0, utils_1.matchesParentDomain)(name, lookupAddress)) { + throw new error_1.MongoAPIError('Server record does not share hostname with parent URI'); + } + } + const hostAddresses = addresses.map(r => utils_1.HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); + validateLoadBalancedOptions(hostAddresses, options, true); + // Use the result of resolving the TXT record and add options from there if they exist. + let record; + try { + record = await txtResolutionPromise; + } + catch (error) { + if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { + throw error; + } + return hostAddresses; + } + if (record.length > 1) { + throw new error_1.MongoParseError('Multiple text records not allowed'); + } + const txtRecordOptions = new url_1.URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); + } + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + throw new error_1.MongoParseError('Cannot have empty URI params in DNS TXT Record'); + } + const source = txtRecordOptions.get('authSource') ?? undefined; + const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined; + const loadBalanced = txtRecordOptions.get('loadBalanced') ?? undefined; + if (!options.userSpecifiedAuthSource && + source && + options.credentials && + !providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism)) { + options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + if (options.replicaSet && options.srvMaxHosts > 0) { + throw new error_1.MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); + } + validateLoadBalancedOptions(hostAddresses, options, true); + return hostAddresses; +} +exports.resolveSRVRecord = resolveSRVRecord; +/** + * Checks if TLS options are valid + * + * @param allOptions - All options provided by user or included in default options map + * @throws MongoAPIError if TLS options are invalid + */ +function checkTLSOptions(allOptions) { + if (!allOptions) + return; + const check = (a, b) => { + if (allOptions.has(a) && allOptions.has(b)) { + throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} +function getBoolean(name, value) { + if (typeof value === 'boolean') + return value; + switch (value) { + case 'true': + return true; + case 'false': + return false; + default: + throw new error_1.MongoParseError(`${name} must be either "true" or "false"`); + } +} +function getIntFromOptions(name, value) { + const parsedInt = (0, utils_1.parseInteger)(value); + if (parsedInt != null) { + return parsedInt; + } + throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} +function getUIntFromOptions(name, value) { + const parsedValue = getIntFromOptions(name, value); + if (parsedValue < 0) { + throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} +function* entriesFromString(value) { + if (value === '') { + return; + } + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(/:(.*)/); + if (value == null) { + throw new error_1.MongoParseError('Cannot have undefined values in key value pairs'); + } + yield [key, value]; + } +} +class CaseInsensitiveMap extends Map { + constructor(entries = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + has(k) { + return super.has(k.toLowerCase()); + } + get(k) { + return super.get(k.toLowerCase()); + } + set(k, v) { + return super.set(k.toLowerCase(), v); + } + delete(k) { + return super.delete(k.toLowerCase()); + } +} +function parseOptions(uri, mongoClient = undefined, options = {}) { + if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + // validate BSONOptions + if (options.useBigInt64 && typeof options.promoteLongs === 'boolean' && !options.promoteLongs) { + throw new error_1.MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + if (options.useBigInt64 && typeof options.promoteValues === 'boolean' && !options.promoteValues) { + throw new error_1.MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + const url = new mongodb_connection_string_url_1.default(uri); + const { hosts, isSRV } = url; + const mongoOptions = Object.create(null); + // Feature flags + for (const flag of Object.getOwnPropertySymbols(options)) { + if (exports.FEATURE_FLAGS.has(flag)) { + mongoOptions[flag] = options[flag]; + } + } + mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString); + const urlOptions = new CaseInsensitiveMap(); + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent(url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname); + if (dbName) { + urlOptions.set('dbName', [dbName]); + } + } + if (url.username !== '') { + const auth = { + username: decodeURIComponent(url.username) + }; + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); + } + urlOptions.set('auth', [auth]); + } + for (const key of url.searchParams.keys()) { + const values = url.searchParams.getAll(key); + const isReadPreferenceTags = /readPreferenceTags/i.test(key); + if (!isReadPreferenceTags && values.length > 1) { + throw new error_1.MongoInvalidArgumentError(`URI option "${key}" cannot appear more than once in the connection string`); + } + if (!isReadPreferenceTags && values.includes('')) { + throw new error_1.MongoAPIError(`URI option "${key}" cannot be specified with no value`); + } + if (!urlOptions.has(key)) { + urlOptions.set(key, values); + } + } + const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null)); + // Validate options that can only be provided by one of uri or object + if (urlOptions.has('serverApi')) { + throw new error_1.MongoParseError('URI cannot contain `serverApi`, it can only be passed to the client'); + } + const uriMechanismProperties = urlOptions.get('authMechanismProperties'); + if (uriMechanismProperties) { + for (const property of uriMechanismProperties) { + if (/(^|,)ALLOWED_HOSTS:/.test(property)) { + throw new error_1.MongoParseError('Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.'); + } + } + } + if (objectOptions.has('loadBalanced')) { + throw new error_1.MongoParseError('loadBalanced is only a valid option in the URI'); + } + // All option collection + const allProvidedOptions = new CaseInsensitiveMap(); + const allProvidedKeys = new Set([...urlOptions.keys(), ...objectOptions.keys()]); + for (const key of allProvidedKeys) { + const values = []; + const objectOptionValue = objectOptions.get(key); + if (objectOptionValue != null) { + values.push(objectOptionValue); + } + const urlValues = urlOptions.get(key) ?? []; + values.push(...urlValues); + allProvidedOptions.set(key, values); + } + if (allProvidedOptions.has('tls') || allProvidedOptions.has('ssl')) { + const tlsAndSslOpts = (allProvidedOptions.get('tls') || []) + .concat(allProvidedOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new error_1.MongoParseError('All values of tls/ssl must be the same.'); + } + } + checkTLSOptions(allProvidedOptions); + const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports.OPTIONS)).map(s => s.toLowerCase())); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`); + } + // Option parsing and setting + for (const [key, descriptor] of Object.entries(exports.OPTIONS)) { + const values = allProvidedOptions.get(key); + if (!values || values.length === 0) { + if (exports.DEFAULT_OPTIONS.has(key)) { + setOption(mongoOptions, key, descriptor, [exports.DEFAULT_OPTIONS.get(key)]); + } + } + else { + const { deprecated } = descriptor; + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`); + } + setOption(mongoOptions, key, descriptor, values); + } + } + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_AWS; + const isOidc = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_OIDC; + if ((isGssapi || isX509) && + allProvidedOptions.has('authSource') && + mongoOptions.credentials.source !== '$external') { + // If authSource was explicitly given and its incorrect, we error + throw new error_1.MongoParseError(`authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'`); + } + if (!(isGssapi || isX509 || isAws || isOidc) && + mongoOptions.dbName && + !allProvidedOptions.has('authSource')) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName + }); + } + if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { + throw new error_1.MongoMissingCredentialsError(`When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified`); + } + mongoOptions.credentials.validate(); + // Check if the only auth related option provided was authSource, if so we can remove credentials + if (mongoOptions.credentials.password === '' && + mongoOptions.credentials.username === '' && + mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && + Object.keys(mongoOptions.credentials.mechanismProperties).length === 0) { + delete mongoOptions.credentials; + } + } + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + if (mongoClient && mongoOptions.autoEncryption) { + encrypter_1.Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + // Potential SRV Overrides and SRV connection string validations + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + if (mongoOptions.directConnection) { + throw new error_1.MongoAPIError('SRV URI does not support directConnection'); + } + if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') { + throw new error_1.MongoParseError('Cannot use srvMaxHosts option with replicaSet'); + } + // SRV turns on TLS by default, but users can override and turn it off + const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls'); + const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl'); + if (noUserSpecifiedTLS && noUserSpecifiedSSL) { + mongoOptions.tls = true; + } + } + else { + const userSpecifiedSrvOptions = urlOptions.has('srvMaxHosts') || + objectOptions.has('srvMaxHosts') || + urlOptions.has('srvServiceName') || + objectOptions.has('srvServiceName'); + if (userSpecifiedSrvOptions) { + throw new error_1.MongoParseError('Cannot use srvMaxHosts or srvServiceName with a non-srv connection string'); + } + } + if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) { + throw new error_1.MongoParseError('directConnection option requires exactly one host'); + } + if (!mongoOptions.proxyHost && + (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword)) { + throw new error_1.MongoParseError('Must specify proxyHost if other proxy options are passed'); + } + if ((mongoOptions.proxyUsername && !mongoOptions.proxyPassword) || + (!mongoOptions.proxyUsername && mongoOptions.proxyPassword)) { + throw new error_1.MongoParseError('Can only specify both of proxy username/password or neither'); + } + const proxyOptions = ['proxyHost', 'proxyPort', 'proxyUsername', 'proxyPassword'].map(key => urlOptions.get(key) ?? []); + if (proxyOptions.some(options => options.length > 1)) { + throw new error_1.MongoParseError('Proxy options cannot be specified multiple times in the connection string'); + } + const loggerFeatureFlag = Symbol.for('@@mdb.enableMongoLogger'); + mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false; + let loggerEnvOptions = {}; + let loggerClientOptions = {}; + if (mongoOptions[loggerFeatureFlag]) { + loggerEnvOptions = { + MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, + MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, + MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, + MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, + MONGODB_LOG_CLIENT: process.env.MONGODB_LOG_CLIENT, + MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, + MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, + MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH, + ...mongoOptions[Symbol.for('@@mdb.internalLoggerConfig')] + }; + loggerClientOptions = { + mongodbLogPath: mongoOptions.mongodbLogPath, + mongodbLogComponentSeverities: mongoOptions.mongodbLogComponentSeverities, + mongodbLogMaxDocumentLength: mongoOptions.mongodbLogMaxDocumentLength + }; + } + mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions(loggerEnvOptions, loggerClientOptions); + mongoOptions.metadata = (0, client_metadata_1.makeClientMetadata)(mongoOptions); + mongoOptions.extendedMetadata = (0, client_metadata_1.addContainerMetadata)(mongoOptions.metadata).catch(() => { + /* rejections will be handled later */ + }); + return mongoOptions; +} +exports.parseOptions = parseOptions; +/** + * #### Throws if LB mode is true: + * - hosts contains more than one host + * - there is a replicaSet name set + * - directConnection is set + * - if srvMaxHosts is used when an srv connection string is passed in + * + * @throws MongoParseError + */ +function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + if (isSrv && mongoOptions.srvMaxHosts > 0) { + throw new error_1.MongoParseError('Cannot limit srv hosts with loadBalanced enabled'); + } + } + return; +} +function setOption(mongoOptions, key, descriptor, values) { + const { target, type, transform } = descriptor; + const name = target ?? key; + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getIntFromOptions(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUIntFromOptions(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!(0, utils_1.isRecord)(values[0])) { + throw new error_1.MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new error_1.MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; + } + } +} +exports.OPTIONS = { + appName: { + type: 'string' + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }) { + if (!(0, utils_1.isRecord)(value, ['username', 'password'])) { + throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password + }); + } + }, + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }) { + const mechanisms = Object.values(providers_1.AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw `\b${value}\b`, 'i'))); + if (!mechanism) { + throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = options.credentials?.source; + if (mechanism === providers_1.AuthMechanism.MONGODB_PLAIN || + providers_1.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism)) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + let password = options.credentials?.password; + if (mechanism === providers_1.AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); + } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values }) { + // We can have a combination of options passed in the URI and options passed + // as an object to the MongoClient. So we must transform the string options + // as well as merge them together with a potentially provided object. + let mechanismProperties = Object.create(null); + for (const optionValue of values) { + if (typeof optionValue === 'string') { + for (const [key, value] of entriesFromString(optionValue)) { + try { + mechanismProperties[key] = getBoolean(key, value); + } + catch { + mechanismProperties[key] = value; + } + } + } + else { + if (!(0, utils_1.isRecord)(optionValue)) { + throw new error_1.MongoParseError('AuthMechanismProperties must be an object'); + } + mechanismProperties = { ...optionValue }; + } + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanismProperties + }); + } + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }) { + const source = String(value); + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }) { + const serverApiToValidate = typeof version === 'string' ? { version } : version; + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + if (!Object.values(mongo_client_1.ServerApiVersion).some(v => v === versionToValidate)) { + throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new error_1.MongoInvalidArgumentError('compressors must be an array or a comma-delimited list of strings'); + } + for (const c of compValArray) { + if (Object.keys(compression_1.Compressor).includes(String(c))) { + compressionList.add(String(c)); + } + else { + throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`); + } + } + } + return [...compressionList]; + } + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + default: {}, + type: 'record' + }, + enableUtf8Validation: { type: 'boolean', default: true }, + family: { + transform({ name, values: [value] }) { + const transformValue = getIntFromOptions(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; + } + throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; + } + }, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }) { + const maxConnecting = getUIntFromOptions(name, value); + if (maxConnecting === 0) { + throw new error_1.MongoInvalidArgumentError('maxConnecting must be > 0 if specified'); + } + return maxConnecting; + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUIntFromOptions(name, value); + if (options.readPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } + }); + } + else { + return new read_preference_1.ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + }, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: utils_1.DEFAULT_PK_FACTORY, + transform({ values: [value] }) { + if ((0, utils_1.isRecord)(value, ['createPk']) && typeof value.createPk === 'function') { + return value; + } + throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`); + } + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + useBigInt64: { + type: 'boolean' + }, + proxyHost: { + type: 'string' + }, + proxyPassword: { + type: 'string' + }, + proxyPort: { + type: 'uint' + }, + proxyUsername: { + type: 'string' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ['level'])) { + return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value }); + } + throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return read_concern_1.ReadConcern.fromOptions({ + ...options.readConcern, + level: level + }); + } + }, + readPreference: { + default: read_preference_1.ReadPreference.primary, + transform({ values: [value], options }) { + if (value instanceof read_preference_1.ReadPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + } + if ((0, utils_1.isRecord)(value, ['mode'])) { + const rp = read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + if (rp) + return rp; + else + throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: options.readPreference?.hedge, + maxStalenessSeconds: options.readPreference?.maxStalenessSeconds + }; + return new read_preference_1.ReadPreference(value, options.readPreference?.tags, rpOpts); + } + throw new error_1.MongoParseError(`Unknown ReadPreference value: ${value}`); + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ values, options }) { + const tags = Array.isArray(values[0]) + ? values[0] + : values; + const readPreferenceTags = []; + for (const tag of tags) { + const readPreferenceTag = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of entriesFromString(tag)) { + readPreferenceTag[k] = v; + } + } + if ((0, utils_1.isRecord)(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } + } + readPreferenceTags.push(readPreferenceTag); + } + return read_preference_1.ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); + } + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverMonitoringMode: { + default: 'auto', + transform({ values: [value] }) { + if (!Object.values(monitor_1.ServerMonitoringMode).includes(value)) { + throw new error_1.MongoParseError('serverMonitoringMode must be one of `auto`, `poll`, or `stream`'); + } + return value; + } + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + srvMaxHosts: { + type: 'uint', + default: 0 + }, + srvServiceName: { + type: 'string', + default: 'mongodb' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + timeoutMS: { + type: 'uint' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + type: 'string' + }, + tlsCRLFile: { + type: 'string' + }, + tlsCertificateKeyFile: { + type: 'string' + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } + else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; + } + return tlsInsecure; + } + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); + } + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } + }); + } + else if (value === 'majority' || typeof value === 'number') { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); + } + throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUIntFromOptions('wtimeout', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUIntFromOptions('wtimeoutMS', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy options from v3 era + useNewUrlParser: { + type: 'boolean', + deprecated: 'useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version' + }, + useUnifiedTopology: { + type: 'boolean', + deprecated: 'useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version' + }, + // MongoLogger + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogPath: { + transform({ values: [value] }) { + if (!((typeof value === 'string' && ['stderr', 'stdout'].includes(value)) || + (value && + typeof value === 'object' && + 'write' in value && + typeof value.write === 'function'))) { + throw new error_1.MongoAPIError(`Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable`); + } + return value; + } + }, + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogComponentSeverities: { + transform({ values: [value] }) { + if (typeof value !== 'object' || !value) { + throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' must be a non-null object`); + } + for (const [k, v] of Object.entries(value)) { + if (typeof v !== 'string' || typeof k !== 'string') { + throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value`); + } + if (!Object.values(mongo_logger_1.MongoLoggableComponent).some(val => val === k) && k !== 'default') { + throw new error_1.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${k}`); + } + if (!Object.values(mongo_logger_1.SeverityLevel).some(val => val === v)) { + throw new error_1.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${v} as a value for ${k}`); + } + } + return value; + } + }, + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogMaxDocumentLength: { type: 'uint' } +}; +exports.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports.OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default])); +/** + * Set of permitted feature flags + * @internal + */ +exports.FEATURE_FLAGS = new Set([ + Symbol.for('@@mdb.skipPingOnConnect'), + Symbol.for('@@mdb.enableMongoLogger'), + Symbol.for('@@mdb.internalLoggerConfig') +]); +//# sourceMappingURL=connection_string.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/connection_string.js.map b/nodejs/node_modules/mongodb/lib/connection_string.js.map new file mode 100644 index 00000000..2edb74ce --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/connection_string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_string.js","sourceRoot":"","sources":["../src/connection_string.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,iFAA6D;AAC7D,6BAAsC;AAGtC,qEAAiE;AACjE,qDAAoF;AACpF,sEAA4F;AAC5F,kEAAmF;AACnF,2CAAwC;AACxC,mCAKiB;AACjB,iDAOwB;AACxB,iDAMwB;AACxB,iDAAoE;AACpE,uDAA4E;AAC5E,4CAAsD;AAEtD,mCAQiB;AACjB,mDAAuD;AAEvD,MAAM,iBAAiB,GAAG,CAAC,YAAY,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;AAEvE,MAAM,oBAAoB,GAAG,kEAAkE,CAAC;AAChG,MAAM,oBAAoB,GAAG,4DAA4D,CAAC;AAC1F,MAAM,0BAA0B,GAC9B,qEAAqE,CAAC;AAExE;;;;;;GAMG;AACI,KAAK,UAAU,gBAAgB,CAAC,OAAqB;IAC1D,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;QACvC,MAAM,IAAI,qBAAa,CAAC,oCAAoC,CAAC,CAAC;KAC/D;IAED,IAAI,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;QAC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yB,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC;CACzC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/constants.js b/nodejs/node_modules/mongodb/lib/constants.js new file mode 100644 index 00000000..4191097a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/constants.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.END = exports.CHANGE = exports.INIT = exports.MORE = exports.RESPONSE = exports.SERVER_HEARTBEAT_FAILED = exports.SERVER_HEARTBEAT_SUCCEEDED = exports.SERVER_HEARTBEAT_STARTED = exports.COMMAND_FAILED = exports.COMMAND_SUCCEEDED = exports.COMMAND_STARTED = exports.CLUSTER_TIME_RECEIVED = exports.CONNECTION_CHECKED_IN = exports.CONNECTION_CHECKED_OUT = exports.CONNECTION_CHECK_OUT_FAILED = exports.CONNECTION_CHECK_OUT_STARTED = exports.CONNECTION_CLOSED = exports.CONNECTION_READY = exports.CONNECTION_CREATED = exports.CONNECTION_POOL_READY = exports.CONNECTION_POOL_CLEARED = exports.CONNECTION_POOL_CLOSED = exports.CONNECTION_POOL_CREATED = exports.WAITING_FOR_SUITABLE_SERVER = exports.SERVER_SELECTION_SUCCEEDED = exports.SERVER_SELECTION_FAILED = exports.SERVER_SELECTION_STARTED = exports.TOPOLOGY_DESCRIPTION_CHANGED = exports.TOPOLOGY_CLOSED = exports.TOPOLOGY_OPENING = exports.SERVER_DESCRIPTION_CHANGED = exports.SERVER_CLOSED = exports.SERVER_OPENING = exports.DESCRIPTION_RECEIVED = exports.UNPINNED = exports.PINNED = exports.MESSAGE = exports.ENDED = exports.CLOSED = exports.CONNECT = exports.OPEN = exports.CLOSE = exports.TIMEOUT = exports.ERROR = exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = void 0; +exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports.LEGACY_HELLO_COMMAND = exports.MONGO_CLIENT_EVENTS = exports.LOCAL_SERVER_EVENTS = exports.SERVER_RELAY_EVENTS = exports.APM_EVENTS = exports.TOPOLOGY_EVENTS = exports.CMAP_EVENTS = exports.HEARTBEAT_EVENTS = exports.RESUME_TOKEN_CHANGED = void 0; +exports.SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +exports.SYSTEM_INDEX_COLLECTION = 'system.indexes'; +exports.SYSTEM_PROFILE_COLLECTION = 'system.profile'; +exports.SYSTEM_USER_COLLECTION = 'system.users'; +exports.SYSTEM_COMMAND_COLLECTION = '$cmd'; +exports.SYSTEM_JS_COLLECTION = 'system.js'; +// events +exports.ERROR = 'error'; +exports.TIMEOUT = 'timeout'; +exports.CLOSE = 'close'; +exports.OPEN = 'open'; +exports.CONNECT = 'connect'; +exports.CLOSED = 'closed'; +exports.ENDED = 'ended'; +exports.MESSAGE = 'message'; +exports.PINNED = 'pinned'; +exports.UNPINNED = 'unpinned'; +exports.DESCRIPTION_RECEIVED = 'descriptionReceived'; +/** @internal */ +exports.SERVER_OPENING = 'serverOpening'; +/** @internal */ +exports.SERVER_CLOSED = 'serverClosed'; +/** @internal */ +exports.SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged'; +/** @internal */ +exports.TOPOLOGY_OPENING = 'topologyOpening'; +/** @internal */ +exports.TOPOLOGY_CLOSED = 'topologyClosed'; +/** @internal */ +exports.TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged'; +/** @internal */ +exports.SERVER_SELECTION_STARTED = 'serverSelectionStarted'; +/** @internal */ +exports.SERVER_SELECTION_FAILED = 'serverSelectionFailed'; +/** @internal */ +exports.SERVER_SELECTION_SUCCEEDED = 'serverSelectionSucceeded'; +/** @internal */ +exports.WAITING_FOR_SUITABLE_SERVER = 'waitingForSuitableServer'; +/** @internal */ +exports.CONNECTION_POOL_CREATED = 'connectionPoolCreated'; +/** @internal */ +exports.CONNECTION_POOL_CLOSED = 'connectionPoolClosed'; +/** @internal */ +exports.CONNECTION_POOL_CLEARED = 'connectionPoolCleared'; +/** @internal */ +exports.CONNECTION_POOL_READY = 'connectionPoolReady'; +/** @internal */ +exports.CONNECTION_CREATED = 'connectionCreated'; +/** @internal */ +exports.CONNECTION_READY = 'connectionReady'; +/** @internal */ +exports.CONNECTION_CLOSED = 'connectionClosed'; +/** @internal */ +exports.CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted'; +/** @internal */ +exports.CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed'; +/** @internal */ +exports.CONNECTION_CHECKED_OUT = 'connectionCheckedOut'; +/** @internal */ +exports.CONNECTION_CHECKED_IN = 'connectionCheckedIn'; +exports.CLUSTER_TIME_RECEIVED = 'clusterTimeReceived'; +/** @internal */ +exports.COMMAND_STARTED = 'commandStarted'; +/** @internal */ +exports.COMMAND_SUCCEEDED = 'commandSucceeded'; +/** @internal */ +exports.COMMAND_FAILED = 'commandFailed'; +/** @internal */ +exports.SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted'; +/** @internal */ +exports.SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded'; +/** @internal */ +exports.SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed'; +exports.RESPONSE = 'response'; +exports.MORE = 'more'; +exports.INIT = 'init'; +exports.CHANGE = 'change'; +exports.END = 'end'; +exports.RESUME_TOKEN_CHANGED = 'resumeTokenChanged'; +/** @public */ +exports.HEARTBEAT_EVENTS = Object.freeze([ + exports.SERVER_HEARTBEAT_STARTED, + exports.SERVER_HEARTBEAT_SUCCEEDED, + exports.SERVER_HEARTBEAT_FAILED +]); +/** @public */ +exports.CMAP_EVENTS = Object.freeze([ + exports.CONNECTION_POOL_CREATED, + exports.CONNECTION_POOL_READY, + exports.CONNECTION_POOL_CLEARED, + exports.CONNECTION_POOL_CLOSED, + exports.CONNECTION_CREATED, + exports.CONNECTION_READY, + exports.CONNECTION_CLOSED, + exports.CONNECTION_CHECK_OUT_STARTED, + exports.CONNECTION_CHECK_OUT_FAILED, + exports.CONNECTION_CHECKED_OUT, + exports.CONNECTION_CHECKED_IN +]); +/** @public */ +exports.TOPOLOGY_EVENTS = Object.freeze([ + exports.SERVER_OPENING, + exports.SERVER_CLOSED, + exports.SERVER_DESCRIPTION_CHANGED, + exports.TOPOLOGY_OPENING, + exports.TOPOLOGY_CLOSED, + exports.TOPOLOGY_DESCRIPTION_CHANGED, + exports.ERROR, + exports.TIMEOUT, + exports.CLOSE +]); +/** @public */ +exports.APM_EVENTS = Object.freeze([ + exports.COMMAND_STARTED, + exports.COMMAND_SUCCEEDED, + exports.COMMAND_FAILED +]); +/** + * All events that we relay to the `Topology` + * @internal + */ +exports.SERVER_RELAY_EVENTS = Object.freeze([ + exports.SERVER_HEARTBEAT_STARTED, + exports.SERVER_HEARTBEAT_SUCCEEDED, + exports.SERVER_HEARTBEAT_FAILED, + exports.COMMAND_STARTED, + exports.COMMAND_SUCCEEDED, + exports.COMMAND_FAILED, + ...exports.CMAP_EVENTS +]); +/** + * All events we listen to from `Server` instances, but do not forward to the client + * @internal + */ +exports.LOCAL_SERVER_EVENTS = Object.freeze([ + exports.CONNECT, + exports.DESCRIPTION_RECEIVED, + exports.CLOSED, + exports.ENDED +]); +/** @public */ +exports.MONGO_CLIENT_EVENTS = Object.freeze([ + ...exports.CMAP_EVENTS, + ...exports.APM_EVENTS, + ...exports.TOPOLOGY_EVENTS, + ...exports.HEARTBEAT_EVENTS +]); +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +exports.LEGACY_HELLO_COMMAND = 'ismaster'; +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = 'isMaster'; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/constants.js.map b/nodejs/node_modules/mongodb/lib/constants.js.map new file mode 100644 index 00000000..aae3eb05 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;;AAAa,QAAA,2BAA2B,GAAG,mBAAmB,CAAC;AAClD,QAAA,uBAAuB,GAAG,gBAAgB,CAAC;AAC3C,QAAA,yBAAyB,GAAG,gBAAgB,CAAC;AAC7C,QAAA,sBAAsB,GAAG,cAAc,CAAC;AACxC,QAAA,yBAAyB,GAAG,MAAM,CAAC;AACnC,QAAA,oBAAoB,GAAG,WAAW,CAAC;AAEhD,SAAS;AACI,QAAA,KAAK,GAAG,OAAgB,CAAC;AACzB,QAAA,OAAO,GAAG,SAAkB,CAAC;AAC7B,QAAA,KAAK,GAAG,OAAgB,CAAC;AACzB,QAAA,IAAI,GAAG,MAAe,CAAC;AACvB,QAAA,OAAO,GAAG,SAAkB,CAAC;AAC7B,QAAA,MAAM,GAAG,QAAiB,CAAC;AAC3B,QAAA,KAAK,GAAG,OAAgB,CAAC;AACzB,QAAA,OAAO,GAAG,SAAkB,CAAC;AAC7B,QAAA,MAAM,GAAG,QAAiB,CAAC;AAC3B,QAAA,QAAQ,GAAG,UAAmB,CAAC;AAC/B,QAAA,oBAAoB,GAAG,qBAAqB,CAAC;AAC1D,gBAAgB;AACH,QAAA,cAAc,GAAG,eAAwB,CAAC;AACvD,gBAAgB;AACH,QAAA,aAAa,GAAG,cAAuB,CAAC;AACrD,gBAAgB;AACH,QAAA,0BAA0B,GAAG,0BAAmC,CAAC;AAC9E,gBAAgB;AACH,QAAA,gBAAgB,GAAG,iBAA0B,CAAC;AAC3D,gBAAgB;AACH,QAAA,eAAe,GAAG,gBAAyB,CAAC;AACzD,gBAAgB;AACH,QAAA,4BAA4B,GAAG,4BAAqC,CAAC;AAClF,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,GAAG,mBAAW;IACd,GAAG,kBAAU;IACb,GAAG,uBAAe;IAClB,GAAG,wBAAgB;CACX,CAAC,CAAC;AAEZ;;;GAGG;AACU,QAAA,oBAAoB,GAAG,UAAU,CAAC;AAE/C;;;GAGG;AACU,QAAA,+BAA+B,GAAG,UAAU,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/abstract_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/abstract_cursor.js new file mode 100644 index 00000000..2557b917 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/abstract_cursor.js @@ -0,0 +1,705 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertUninitialized = exports.AbstractCursor = exports.CURSOR_FLAGS = void 0; +const stream_1 = require("stream"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const execute_operation_1 = require("../operations/execute_operation"); +const get_more_1 = require("../operations/get_more"); +const kill_cursors_1 = require("../operations/kill_cursors"); +const read_concern_1 = require("../read_concern"); +const read_preference_1 = require("../read_preference"); +const sessions_1 = require("../sessions"); +const utils_1 = require("../utils"); +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kClient = Symbol('client'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); +/** @internal */ +const kInit = Symbol('kInit'); +/** @public */ +exports.CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class AbstractCursor extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(client, namespace, options = {}) { + super(); + if (!client.s.isMongoClient) { + throw new error_1.MongoRuntimeError('Cursor must be constructed with MongoClient'); + } + this[kClient] = client; + this[kNamespace] = namespace; + this[kId] = null; + this[kDocuments] = new utils_1.List(); + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference + ? options.readPreference + : read_preference_1.ReadPreference.primary, + ...(0, bson_1.pluckBSONSerializeOptions)(options) + }; + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this[kOptions].comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + if (typeof options.maxAwaitTimeMS === 'number') { + this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS; + } + if (options.session instanceof sessions_1.ClientSession) { + this[kSession] = options.session; + } + else { + this[kSession] = this[kClient].startSession({ owner: this, explicit: false }); + } + } + get id() { + return this[kId] ?? undefined; + } + /** @internal */ + get isDead() { + return (this[kId]?.isZero() ?? false) || this[kClosed] || this[kKilled]; + } + /** @internal */ + get client() { + return this[kClient]; + } + /** @internal */ + get server() { + return this[kServer]; + } + get namespace() { + return this[kNamespace]; + } + get readPreference() { + return this[kOptions].readPreference; + } + get readConcern() { + return this[kOptions].readConcern; + } + /** @internal */ + get session() { + return this[kSession]; + } + set session(clientSession) { + this[kSession] = clientSession; + } + /** @internal */ + get cursorOptions() { + return this[kOptions]; + } + get closed() { + return this[kClosed]; + } + get killed() { + return this[kKilled]; + } + get loadBalanced() { + return !!this[kClient].topology?.loadBalanced; + } + /** Returns current buffered documents length */ + bufferedCount() { + return this[kDocuments].length; + } + /** Returns current buffered documents */ + readBufferedDocuments(number) { + const bufferedDocs = []; + const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length); + for (let count = 0; count < documentsToRead; count++) { + const document = this[kDocuments].shift(); + if (document != null) { + bufferedDocs.push(document); + } + } + return bufferedDocs; + } + async *[Symbol.asyncIterator]() { + if (this.closed) { + return; + } + try { + while (true) { + const document = await this.next(); + // Intentional strict null check, because users can map cursors to falsey values. + // We allow mapping to all values except for null. + // eslint-disable-next-line no-restricted-syntax + if (document === null) { + if (!this.closed) { + const message = 'Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.'; + await cleanupCursor(this, { needsToEmitClosed: true }).catch(() => null); + throw new error_1.MongoAPIError(message); + } + break; + } + yield document; + if (this[kId] === bson_1.Long.ZERO) { + // Cursor exhausted + break; + } + } + } + finally { + // Only close the cursor if it has not already been closed. This finally clause handles + // the case when a user would break out of a for await of loop early. + if (!this.closed) { + await this.close().catch(() => null); + } + } + } + stream(options) { + if (options?.transform) { + const transform = options.transform; + const readable = new ReadableCursorStream(this); + const transformedStream = readable.pipe(new stream_1.Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } + catch (err) { + callback(err); + } + } + })); + // Bubble errors to transformed stream, because otherwise no way + // to handle this error. + readable.on('error', err => transformedStream.emit('error', err)); + return transformedStream; + } + return new ReadableCursorStream(this); + } + async hasNext() { + if (this[kId] === bson_1.Long.ZERO) { + return false; + } + if (this[kDocuments].length !== 0) { + return true; + } + const doc = await next(this, { blocking: true, transform: false }); + if (doc) { + this[kDocuments].unshift(doc); + return true; + } + return false; + } + /** Get the next available document from the cursor, returns null if no more documents are available. */ + async next() { + if (this[kId] === bson_1.Long.ZERO) { + throw new error_1.MongoCursorExhaustedError(); + } + return next(this, { blocking: true, transform: true }); + } + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + async tryNext() { + if (this[kId] === bson_1.Long.ZERO) { + throw new error_1.MongoCursorExhaustedError(); + } + return next(this, { blocking: false, transform: true }); + } + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + * @deprecated - Will be removed in a future release. Use for await...of instead. + */ + async forEach(iterator) { + if (typeof iterator !== 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + for await (const document of this) { + const result = iterator(document); + if (result === false) { + break; + } + } + } + async close() { + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + await cleanupCursor(this, { needsToEmitClosed }); + } + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + */ + async toArray() { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag, value) { + assertUninitialized(this); + if (!exports.CURSOR_FLAGS.includes(flag)) { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports.CURSOR_FLAGS}`); + } + if (typeof value !== 'boolean') { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + this[kOptions][flag] = value; + return this; + } + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * + * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform) { + assertUninitialized(this); + const oldTransform = this[kTransform]; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; + } + else { + this[kTransform] = transform; + } + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference) { + assertUninitialized(this); + if (readPreference instanceof read_preference_1.ReadPreference) { + this[kOptions].readPreference = readPreference; + } + else if (typeof readPreference === 'string') { + this[kOptions].readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + else { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); + } + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern) { + assertUninitialized(this); + const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kOptions].maxTimeMS = value; + return this; + } + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}. + */ + batchSize(value) { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + this[kOptions].batchSize = value; + return this; + } + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind() { + if (!this[kInitialized]) { + return; + } + this[kId] = null; + this[kDocuments].clear(); + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false) { + if (!session.hasEnded) { + session.endSession().catch(() => null); + } + this[kSession] = this.client.startSession({ owner: this, explicit: false }); + } + } + } + /** @internal */ + async getMore(batchSize) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new get_more_1.GetMoreOperation(this[kNamespace], this[kId], this[kServer], { + ...this[kOptions], + session: this[kSession], + batchSize + }); + return (0, execute_operation_1.executeOperation)(this[kClient], getMoreOperation); + } + /** + * @internal + * + * This function is exposed for the unified test runner's createChangeStream + * operation. We cannot refactor to use the abstract _initialize method without + * a significant refactor. + */ + async [kInit]() { + try { + const state = await this._initialize(this[kSession]); + const response = state.response; + this[kServer] = state.server; + if (response.cursor) { + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this[kId] = + typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? bson_1.Long.fromBigInt(response.cursor.id) + : response.cursor.id; + if (response.cursor.ns) { + this[kNamespace] = (0, utils_1.ns)(response.cursor.ns); + } + this[kDocuments].pushMany(response.cursor.firstBatch); + } + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (this[kId] == null) { + this[kId] = bson_1.Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + this[kDocuments].push(state.response); + } + // the cursor is now initialized, even if it is dead + this[kInitialized] = true; + } + catch (error) { + // the cursor is now initialized, even if an error occurred + this[kInitialized] = true; + await cleanupCursor(this, { error }); + throw error; + } + if (this.isDead) { + await cleanupCursor(this, undefined); + } + return; + } +} +/** @event */ +AbstractCursor.CLOSE = 'close'; +exports.AbstractCursor = AbstractCursor; +/** + * @param cursor - the cursor on which to call `next` + * @param blocking - a boolean indicating whether or not the cursor should `block` until data + * is available. Generally, this flag is set to `false` because if the getMore returns no documents, + * the cursor has been exhausted. In certain scenarios (ChangeStreams, tailable await cursors and + * `tryNext`, for example) blocking is necessary because a getMore returning no documents does + * not indicate the end of the cursor. + * @param transform - if true, the cursor's transform function is applied to the result document (if the transform exists) + * @returns the next document in the cursor, or `null`. When `blocking` is `true`, a `null` document means + * the cursor has been exhausted. Otherwise, it means that there is no document available in the cursor's buffer. + */ +async function next(cursor, { blocking, transform }) { + if (cursor.closed) { + return null; + } + do { + if (cursor[kId] == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + await cursor[kInit](); + } + if (cursor[kDocuments].length !== 0) { + const doc = cursor[kDocuments].shift(); + if (doc != null && transform && cursor[kTransform]) { + try { + return cursor[kTransform](doc); + } + catch (error) { + // `cleanupCursorAsync` should never throw, but if it does we want to throw the original + // error instead. + await cleanupCursor(cursor, { error, needsToEmitClosed: true }).catch(() => null); + throw error; + } + } + return doc; + } + if (cursor.isDead) { + // if the cursor is dead, we clean it up + // cleanupCursorAsync should never throw, but if it does it indicates a bug in the driver + // and we should surface the error + await cleanupCursor(cursor, {}); + return null; + } + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + try { + const response = await cursor.getMore(batchSize); + if (response) { + const cursorId = typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? bson_1.Long.fromBigInt(response.cursor.id) + : response.cursor.id; + cursor[kDocuments].pushMany(response.cursor.nextBatch); + cursor[kId] = cursorId; + } + } + catch (error) { + // `cleanupCursorAsync` should never throw, but if it does we want to throw the original + // error instead. + await cleanupCursor(cursor, { error }).catch(() => null); + throw error; + } + if (cursor.isDead) { + // If we successfully received a response from a cursor BUT the cursor indicates that it is exhausted, + // we intentionally clean up the cursor to release its session back into the pool before the cursor + // is iterated. This prevents a cursor that is exhausted on the server from holding + // onto a session indefinitely until the AbstractCursor is iterated. + // + // cleanupCursorAsync should never throw, but if it does it indicates a bug in the driver + // and we should surface the error + await cleanupCursor(cursor, {}); + } + if (cursor[kDocuments].length === 0 && blocking === false) { + return null; + } + } while (!cursor.isDead || cursor[kDocuments].length !== 0); + return null; +} +async function cleanupCursor(cursor, options) { + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options?.error; + // Cursors only emit closed events once the client-side cursor has been exhausted fully or there + // was an error. Notably, when the server returns a cursor id of 0 and a non-empty batch, we + // cleanup the cursor but don't emit a `close` event. + const needsToEmitClosed = options?.needsToEmitClosed ?? cursor[kDocuments].length === 0; + if (error) { + if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) { + return completeCleanup(); + } + } + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = bson_1.Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); + } + if (session) { + if (session.owner === cursor) { + await session.endSession({ error }); + return; + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + return; + } + async function completeCleanup() { + if (session) { + if (session.owner === cursor) { + try { + await session.endSession({ error }); + } + finally { + cursor.emit(AbstractCursor.CLOSE); + } + return; + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + cursor.emit(AbstractCursor.CLOSE); + return; + } + cursor[kKilled] = true; + if (session.hasEnded) { + return completeCleanup(); + } + try { + await (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session })).catch(() => null); + } + finally { + await completeCleanup(); + } +} +/** @internal */ +function assertUninitialized(cursor) { + if (cursor[kInitialized]) { + throw new error_1.MongoCursorInUseError(); + } +} +exports.assertUninitialized = assertUninitialized; +class ReadableCursorStream extends stream_1.Readable { + constructor(cursor) { + super({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + this._readInProgress = false; + this._cursor = cursor; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _read(size) { + if (!this._readInProgress) { + this._readInProgress = true; + this._readNext(); + } + } + _destroy(error, callback) { + this._cursor.close().then(() => callback(error), closeError => callback(closeError)); + } + _readNext() { + next(this._cursor, { blocking: true, transform: true }).then(result => { + if (result == null) { + this.push(null); + } + else if (this.destroyed) { + this._cursor.close().catch(() => null); + } + else { + if (this.push(result)) { + return this._readNext(); + } + this._readInProgress = false; + } + }, err => { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + this._cursor.close().catch(() => null); + return this.push(null); + } + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation was interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/operation was interrupted/)) { + return this.push(null); + } + // NOTE: The two above checks on the message of the error will cause a null to be pushed + // to the stream, thus closing the stream before the destroy call happens. This means + // that either of those error messages on a change stream will not get a proper + // 'error' event to be emitted (the error passed to destroy). Change stream resumability + // relies on that error event to be emitted to create its new cursor and thus was not + // working on 4.4 servers because the error emitted on failover was "interrupted at + // shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down". + // See NODE-4475. + return this.destroy(err); + }); + } +} +//# sourceMappingURL=abstract_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/abstract_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/abstract_cursor.js.map new file mode 100644 index 00000000..a716a3a7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/abstract_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract_cursor.js","sourceRoot":"","sources":["../../src/cursor/abstract_cursor.ts"],"names":[],"mappings":";;;AAAA,mCAA6C;AAE7C,kCAAoG;AACpG,oCASkB;AAElB,gDAAwE;AACxE,uEAAyF;AACzF,qDAA0D;AAC1D,6DAAkE;AAClE,kDAAoE;AACpE,wDAA6E;AAE7E,0CAAwE;AACxE,oCAA2D;AAE3D,gBAAgB;AAChB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AACzB,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACnC,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACnC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAE9B,cAAc;AAC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AAC,IAAI,CAAC,CAAC;gBACvC,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACxB;YAED,wFAAwF;YACxF,0FAA0F;YAC1F,uFAAuF;YACvF,kFAAkF;YAClF,6EAA6E;YAC7E,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,2BAA2B,CAAC,EAAE;gBAClD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACxB;YAED,wFAAwF;YACxF,2FAA2F;YAC3F,qFAAqF;YACrF,8FAA8F;YAC9F,2FAA2F;YAC3F,yFAAyF;YACzF,0FAA0F;YAC1F,uBAAuB;YACvB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC3B,CAAC,CACF,CAAC;IACJ,CAAC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/aggregation_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/aggregation_cursor.js new file mode 100644 index 00000000..bd38d86e --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/aggregation_cursor.js @@ -0,0 +1,165 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregationCursor = void 0; +const aggregate_1 = require("../operations/aggregate"); +const execute_operation_1 = require("../operations/execute_operation"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +class AggregationCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(client, namespace, pipeline = [], options = {}) { + super(client, namespace, options); + this[kPipeline] = pipeline; + this[kOptions] = options; + } + get pipeline() { + return this[kPipeline]; + } + clone() { + const clonedOptions = (0, utils_1.mergeOptions)({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.client, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + async _initialize(session) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + const response = await (0, execute_operation_1.executeOperation)(this.client, aggregateOperation); + // TODO: NODE-2882 + return { server: aggregateOperation.server, session, response }; + } + /** Execute the explain for the cursor */ + async explain(verbosity) { + return (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + explain: verbosity ?? true + })); + } + group($group) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $group }); + return this; + } + /** Add a limit stage to the aggregation pipeline */ + limit($limit) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $limit }); + return this; + } + /** Add a match stage to the aggregation pipeline */ + match($match) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $match }); + return this; + } + /** Add an out stage to the aggregation pipeline */ + out($out) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $out }); + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $project }); + return this; + } + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $lookup }); + return this; + } + /** Add a redact stage to the aggregation pipeline */ + redact($redact) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $redact }); + return this; + } + /** Add a skip stage to the aggregation pipeline */ + skip($skip) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $skip }); + return this; + } + /** Add a sort stage to the aggregation pipeline */ + sort($sort) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $sort }); + return this; + } + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $unwind }); + return this; + } + /** Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} +exports.AggregationCursor = AggregationCursor; +//# sourceMappingURL=aggregation_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map new file mode 100644 index 00000000..bd8b306e --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregation_cursor.js","sourceRoot":"","sources":["../../src/cursor/aggregation_cursor.ts"],"names":[],"mappings":";;;AAGA,u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E,OAAO,EAAE,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,sDAAsD;IACtD,OAAO,CAAC,QAAkB;QACxB,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlLD,8CAkLC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/change_stream_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/change_stream_cursor.js new file mode 100644 index 00000000..a132bc5c --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/change_stream_cursor.js @@ -0,0 +1,107 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStreamCursor = void 0; +const change_stream_1 = require("../change_stream"); +const constants_1 = require("../constants"); +const aggregate_1 = require("../operations/aggregate"); +const execute_operation_1 = require("../operations/execute_operation"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +class ChangeStreamCursor extends abstract_cursor_1.AbstractCursor { + constructor(client, namespace, pipeline = [], options = {}) { + super(client, namespace, options); + this.pipeline = pipeline; + this.options = options; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + if (options.startAfter) { + this.resumeToken = options.startAfter; + } + else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + set resumeToken(token) { + this._resumeToken = token; + this.emit(change_stream_1.ChangeStream.RESUME_TOKEN_CHANGED, token); + } + get resumeToken() { + return this._resumeToken; + } + get resumeOptions() { + const options = { + ...this.options + }; + for (const key of ['resumeAfter', 'startAfter', 'startAtOperationTime']) { + delete options[key]; + } + if (this.resumeToken != null) { + if (this.options.startAfter && !this.hasReceived) { + options.startAfter = this.resumeToken; + } + else { + options.resumeAfter = this.resumeToken; + } + } + else if (this.startAtOperationTime != null && (0, utils_1.maxWireVersion)(this.server) >= 7) { + options.startAtOperationTime = this.startAtOperationTime; + } + return options; + } + cacheResumeToken(resumeToken) { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } + else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + _processBatch(response) { + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = response.cursor.postBatchResumeToken; + const batch = 'firstBatch' in response.cursor ? response.cursor.firstBatch : response.cursor.nextBatch; + if (batch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + clone() { + return new ChangeStreamCursor(this.client, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + async _initialize(session) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + const response = await (0, execute_operation_1.executeOperation)(session.client, aggregateOperation); + const server = aggregateOperation.server; + this.maxWireVersion = (0, utils_1.maxWireVersion)(server); + if (this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + this.maxWireVersion >= 7) { + this.startAtOperationTime = response.operationTime; + } + this._processBatch(response); + this.emit(constants_1.INIT, response); + this.emit(constants_1.RESPONSE); + // TODO: NODE-2882 + return { server, session, response }; + } + async getMore(batchSize) { + const response = await super.getMore(batchSize); + this.maxWireVersion = (0, utils_1.maxWireVersion)(this.server); + this._processBatch(response); + this.emit(change_stream_1.ChangeStream.MORE, response); + this.emit(change_stream_1.ChangeStream.RESPONSE); + return response; + } +} +exports.ChangeStreamCursor = ChangeStreamCursor; +//# sourceMappingURL=change_stream_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map new file mode 100644 index 00000000..bb52a6d6 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"change_stream_cursor.js","sour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AC,QAAmD,CAAC,CAAC;QAExE,IAAI,CAAC,IAAI,CAAC,4BAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACvC,IAAI,CAAC,IAAI,CAAC,4BAAY,CAAC,QAAQ,CAAC,CAAC;QACjC,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF;AA/ID,gDA+IC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/find_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/find_cursor.js new file mode 100644 index 00000000..e27b87e2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/find_cursor.js @@ -0,0 +1,378 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindCursor = exports.FLAGS = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const count_1 = require("../operations/count"); +const execute_operation_1 = require("../operations/execute_operation"); +const find_1 = require("../operations/find"); +const sort_1 = require("../sort"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); +/** @public Flags allowed for cursor */ +exports.FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class FindCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(client, namespace, filter = {}, options = {}) { + super(client, namespace, options); + this[kFilter] = filter; + this[kBuiltOptions] = options; + if (options.sort != null) { + this[kBuiltOptions].sort = (0, sort_1.formatSort)(options.sort); + } + } + clone() { + const clonedOptions = (0, utils_1.mergeOptions)({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.client, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + async _initialize(session) { + const findOperation = new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + session + }); + const response = await (0, execute_operation_1.executeOperation)(this.client, findOperation); + // the response is not a cursor when `explain` is enabled + this[kNumReturned] = response.cursor?.firstBatch?.length; + // TODO: NODE-2882 + return { server: findOperation.server, session, response }; + } + /** @internal */ + async getMore(batchSize) { + const numReturned = this[kNumReturned]; + if (numReturned) { + // TODO(DRIVERS-1448): Remove logic to enforce `limit` in the driver + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + if (batchSize <= 0) { + // this is an optimization for the special case of a limit for a find command to avoid an + // extra getMore when the limit has been reached and the limit is a multiple of the batchSize. + // This is a consequence of the new query engine in 5.0 having no knowledge of the limit as it + // produces results for the find command. Once a batch is filled up, it is returned and only + // on the subsequent getMore will the query framework consider the limit, determine the cursor + // is exhausted and return a cursorId of zero. + // instead, if we determine there are no more documents to request from the server, we preemptively + // close the cursor + await this.close().catch(() => null); + return { cursor: { id: bson_1.Long.ZERO, nextBatch: [] } }; + } + } + const response = await super.getMore(batchSize); + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + return response; + } + /** + * Get the count of documents for this cursor + * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead + */ + async count(options) { + (0, utils_1.emitWarningOnce)('cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead '); + if (typeof options === 'boolean') { + throw new error_1.MongoInvalidArgumentError('Invalid first parameter to count'); + } + return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + ...options + })); + } + /** Execute the explain for the cursor */ + async explain(verbosity) { + return (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + explain: verbosity ?? true + })); + } + /** Set the cursor query */ + filter(filter) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kFilter] = filter; + return this; + } + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].hint = hint; + return this; + } + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].min = min; + return this; + } + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].max = max; + return this; + } + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].returnKey = value; + return this; + } + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name, value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (name[0] !== '$') { + throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + // Strip of the $ + const field = name.substr(1); + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value; + break; + case 'explain': + this[kBuiltOptions].explain = value; + break; + case 'hint': + this[kBuiltOptions].hint = value; + break; + case 'max': + this[kBuiltOptions].max = value; + break; + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value; + break; + case 'min': + this[kBuiltOptions].min = value; + break; + case 'orderby': + this[kBuiltOptions].sort = (0, sort_1.formatSort)(value); + break; + case 'query': + this[kFilter] = value; + break; + case 'returnKey': + this[kBuiltOptions].returnKey = value; + break; + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value; + break; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`); + } + return this; + } + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].comment = value; + return this; + } + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + this[kBuiltOptions].maxAwaitTimeMS = value; + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kBuiltOptions].maxTimeMS = value; + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].projection = value; + return this; + } + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort, direction) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support sorting'); + } + this[kBuiltOptions].sort = (0, sort_1.formatSort)(sort, direction); + return this; + } + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(allow = true) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (!this[kBuiltOptions].sort) { + throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + // As of 6.0 the default is true. This allows users to get back to the old behavior. + if (!allow) { + this[kBuiltOptions].allowDiskUse = false; + return this; + } + this[kBuiltOptions].allowDiskUse = true; + return this; + } + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].collation = value; + return this; + } + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support limit'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + this[kBuiltOptions].limit = value; + return this; + } + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support skip'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + this[kBuiltOptions].skip = value; + return this; + } +} +exports.FindCursor = FindCursor; +//# sourceMappingURL=find_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/find_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/find_cursor.js.map new file mode 100644 index 00000000..0eff14be --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/find_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_cursor.js","sourceRoot":"","sources":["../../src/cursor/find_cursor.ts"],"names":[],"mappings":";;;AAAA,kCAA8C;AAC9C,oCAA+E;AAI/E,+CAAwE;AACxE,uEAAyF;AACzF,6CAAqE;AAGrE,kCAAoE;AACpE,oCAAgF;AAChF,uDAAwE;AAExE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAE7C,uCAAuC;AAC1B,QAAA,KAAK,GAAG;IACnB,UAAU;IACV,aAAa;IACb,iBAAiB;IACjB,WAAW;IACX,SAAS;IACT,SA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I,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,SAAS,CAAC,KAAuB;QAC/B,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,aAAa,CAAC,CAAC,SAAS,GAAG,KAAK,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAa;QACjB,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,IAAI,CAAC,aAAa,CAAC,CAAC,QAAQ,EAAE;YAChC,MAAM,IAAI,gCAAwB,CAAC,wCAAwC,CAAC,CAAC;SAC9E;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,MAAM,IAAI,iCAAyB,CAAC,uCAAuC,CAAC,CAAC;SAC9E;QAED,IAAI,CAAC,aAAa,CAAC,CAAC,KAAK,GAAG,KAAK,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,KAAa;QAChB,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,IAAI,CAAC,aAAa,CAAC,CAAC,QAAQ,EAAE;YAChC,MAAM,IAAI,gCAAwB,CAAC,uCAAuC,CAAC,CAAC;SAC7E;QAED,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,MAAM,IAAI,iCAAyB,CAAC,sCAAsC,CAAC,CAAC;SAC7E;QAED,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAraD,gCAqaC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/list_collections_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/list_collections_cursor.js new file mode 100644 index 00000000..91463b7b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/list_collections_cursor.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListCollectionsCursor = void 0; +const execute_operation_1 = require("../operations/execute_operation"); +const list_collections_1 = require("../operations/list_collections"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @public */ +class ListCollectionsCursor extends abstract_cursor_1.AbstractCursor { + constructor(db, filter, options) { + super(db.client, db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + clone() { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + async _initialize(session) { + const operation = new list_collections_1.ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + const response = await (0, execute_operation_1.executeOperation)(this.parent.client, operation); + // TODO: NODE-2882 + return { server: operation.server, session, response }; + } +} +exports.ListCollectionsCursor = ListCollectionsCursor; +//# sourceMappingURL=list_collections_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map new file mode 100644 index 00000000..160c468f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_collections_cursor.js","sourceRoot":"","sources":["../../src/cursor/list_collections_cursor.ts"],"names":[],"mappings":";;;AAEA,uEAAyF;AACzF,qEAIwC;AAExC,uDAAmD;AAEnD,cAAc;AACd,MAAa,qBAIX,SAAQ,gCAAiB;IAKzB,YAAY,EAAM,EAAE,MAAgB,EAAE,OAAgC;QACpE,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK;QACH,OAAO,IAAI,qBAAqB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE;YACzD,GAAG,IAAI,CAAC,OAAO;YACf,GAAG,IAAI,CAAC,aAAa;SACtB,CAAC,CAAC;IACL,CAAC;IAED,gBAAgB;IAChB,KAAK,CAAC,WAAW,CAAC,OAAkC;QAClD,MAAM,SAAS,GAAG,IAAI,2CAAwB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE;YACvE,GAAG,IAAI,CAAC,aAAa;YACrB,GAAG,IAAI,CAAC,OAAO;YACf,OAAO;SACR,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,MAAM,IAAA,oCAAgB,EAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAEvE,kBAAkB;QAClB,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACzD,CAAC;CACF;AApCD,sDAoCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/list_indexes_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/list_indexes_cursor.js new file mode 100644 index 00000000..9f2cb730 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/list_indexes_cursor.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListIndexesCursor = void 0; +const execute_operation_1 = require("../operations/execute_operation"); +const indexes_1 = require("../operations/indexes"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @public */ +class ListIndexesCursor extends abstract_cursor_1.AbstractCursor { + constructor(collection, options) { + super(collection.client, collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + clone() { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + async _initialize(session) { + const operation = new indexes_1.ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + const response = await (0, execute_operation_1.executeOperation)(this.parent.client, operation); + // TODO: NODE-2882 + return { server: operation.server, session, response }; + } +} +exports.ListIndexesCursor = ListIndexesCursor; +//# sourceMappingURL=list_indexes_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map new file mode 100644 index 00000000..eb0c7877 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_indexes_cursor.js","sourceRoot":"","sources":["../../src/cursor/list_indexes_cursor.ts"],"names":[],"mappings":";;;AACA,uEAAyF;AACzF,mDAAsF;AAEtF,uDAAmD;AAEnD,cAAc;AACd,MAAa,iBAAkB,SAAQ,gCAAc;IAInD,YAAY,UAAsB,EAAE,OAA4B;QAC9D,KAAK,CAAC,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1D,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,KAAK;QACH,OAAO,IAAI,iBAAiB,CAAC,IAAI,CAAC,MAAM,EAAE;YACxC,GAAG,IAAI,CAAC,OAAO;YACf,GAAG,IAAI,CAAC,aAAa;SACtB,CAAC,CAAC;IACL,CAAC;IAED,gBAAgB;IAChB,KAAK,CAAC,WAAW,CAAC,OAAkC;QAClD,MAAM,SAAS,GAAG,IAAI,8BAAoB,CAAC,IAAI,CAAC,MAAM,EAAE;YACtD,GAAG,IAAI,CAAC,aAAa;YACrB,GAAG,IAAI,CAAC,OAAO;YACf,OAAO;SACR,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,MAAM,IAAA,oCAAgB,EAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAEvE,kBAAkB;QAClB,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACzD,CAAC;CACF;AA9BD,8CA8BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js new file mode 100644 index 00000000..d9c39c70 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListSearchIndexesCursor = void 0; +const aggregation_cursor_1 = require("./aggregation_cursor"); +/** @public */ +class ListSearchIndexesCursor extends aggregation_cursor_1.AggregationCursor { + /** @internal */ + constructor({ fullNamespace: ns, client }, name, options = {}) { + const pipeline = name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }]; + super(client, ns, pipeline, options); + } +} +exports.ListSearchIndexesCursor = ListSearchIndexesCursor; +//# sourceMappingURL=list_search_indexes_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js.map new file mode 100644 index 00000000..6353a21a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/list_search_indexes_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_search_indexes_cursor.js","sourceRoot":"","sources":["../../src/cursor/list_search_indexes_cursor.ts"],"names":[],"mappings":";;;AAEA,6DAAyD;AAKzD,cAAc;AACd,MAAa,uBAAwB,SAAQ,sCAAmC;IAC9E,gBAAgB;IAChB,YACE,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,EAAc,EACzC,IAAmB,EACnB,UAAoC,EAAE;QAEtC,MAAM,QAAQ,GACZ,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;QACnF,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACvC,CAAC;CACF;AAXD,0DAWC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/run_command_cursor.js b/nodejs/node_modules/mongodb/lib/cursor/run_command_cursor.js new file mode 100644 index 00000000..3fbf8581 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/run_command_cursor.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RunCommandCursor = void 0; +const error_1 = require("../error"); +const execute_operation_1 = require("../operations/execute_operation"); +const get_more_1 = require("../operations/get_more"); +const run_command_1 = require("../operations/run_command"); +const utils_1 = require("../utils"); +const abstract_cursor_1 = require("./abstract_cursor"); +/** @public */ +class RunCommandCursor extends abstract_cursor_1.AbstractCursor { + /** + * Controls the `getMore.comment` field + * @param comment - any BSON value + */ + setComment(comment) { + this.getMoreOptions.comment = comment; + return this; + } + /** + * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await + * @param maxTimeMS - the number of milliseconds to wait for new data + */ + setMaxTimeMS(maxTimeMS) { + this.getMoreOptions.maxAwaitTimeMS = maxTimeMS; + return this; + } + /** + * Controls the `getMore.batchSize` field + * @param maxTimeMS - the number documents to return in the `nextBatch` + */ + setBatchSize(batchSize) { + this.getMoreOptions.batchSize = batchSize; + return this; + } + /** Unsupported for RunCommandCursor */ + clone() { + throw new error_1.MongoAPIError('Clone not supported, create a new cursor with db.runCursorCommand'); + } + /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */ + withReadConcern(_) { + throw new error_1.MongoAPIError('RunCommandCursor does not support readConcern it must be attached to the command being run'); + } + /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */ + addCursorFlag(_, __) { + throw new error_1.MongoAPIError('RunCommandCursor does not support cursor flags, they must be attached to the command being run'); + } + /** Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document */ + maxTimeMS(_) { + throw new error_1.MongoAPIError('maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()'); + } + /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */ + batchSize(_) { + throw new error_1.MongoAPIError('batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()'); + } + /** @internal */ + constructor(db, command, options = {}) { + super(db.client, (0, utils_1.ns)(db.namespace), options); + this.getMoreOptions = {}; + this.db = db; + this.command = Object.freeze({ ...command }); + } + /** @internal */ + async _initialize(session) { + const operation = new run_command_1.RunCommandOperation(this.db, this.command, { + ...this.cursorOptions, + session: session, + readPreference: this.cursorOptions.readPreference + }); + const response = await (0, execute_operation_1.executeOperation)(this.client, operation); + if (response.cursor == null) { + throw new error_1.MongoUnexpectedServerResponseError('Expected server to respond with cursor'); + } + return { + server: operation.server, + session, + response + }; + } + /** @internal */ + async getMore(_batchSize) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new get_more_1.GetMoreOperation(this.namespace, this.id, this.server, { + ...this.cursorOptions, + session: this.session, + ...this.getMoreOptions + }); + return (0, execute_operation_1.executeOperation)(this.client, getMoreOperation); + } +} +exports.RunCommandCursor = RunCommandCursor; +//# sourceMappingURL=run_command_cursor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/cursor/run_command_cursor.js.map b/nodejs/node_modules/mongodb/lib/cursor/run_command_cursor.js.map new file mode 100644 index 00000000..2a6a374d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/cursor/run_command_cursor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"run_command_cursor.js","sourceRoot":"","sources":["../../src/cursor/run_command_cursor.ts"],"names":[],"mappings":";;;AAEA,oCAA6E;AAC7E,uEAAyF;AACzF,qDAA0D;AAC1D,2DAAgE;AAIhE,oCAA8B;AAC9B,uDAAmD;AAcnD,cAAc;AACd,MAAa,gBAAiB,SAAQ,gCAAc;I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AAC;IAC/C,CAAC;IAED,gBAAgB;IACN,KAAK,CAAC,WAAW,CAAC,OAAsB;QAChD,MAAM,SAAS,GAAG,IAAI,iCAAmB,CAA2B,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE;YACzF,GAAG,IAAI,CAAC,aAAa;YACrB,OAAO,EAAE,OAAO;YAChB,cAAc,EAAE,IAAI,CAAC,aAAa,CAAC,cAAc;SAClD,CAAC,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,IAAA,oCAAgB,EAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAChE,IAAI,QAAQ,CAAC,MAAM,IAAI,IAAI,EAAE;YAC3B,MAAM,IAAI,0CAAkC,CAAC,wCAAwC,CAAC,CAAC;SACxF;QACD,OAAO;YACL,MAAM,EAAE,SAAS,CAAC,MAAM;YACxB,OAAO;YACP,QAAQ;SACT,CAAC;IACJ,CAAC;IAED,gBAAgB;IACP,KAAK,CAAC,OAAO,CAAC,UAAkB;QACvC,oEAAoE;QACpE,MAAM,gBAAgB,GAAG,IAAI,2BAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,EAAG,EAAE,IAAI,CAAC,MAAO,EAAE;YACpF,GAAG,IAAI,CAAC,aAAa;YACrB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,GAAG,IAAI,CAAC,cAAc;SACvB,CAAC,CAAC;QAEH,OAAO,IAAA,oCAAgB,EAAC,IAAI,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IACzD,CAAC;CACF;AA3GD,4CA2GC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/db.js b/nodejs/node_modules/mongodb/lib/db.js new file mode 100644 index 00000000..b304e6bb --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/db.js @@ -0,0 +1,356 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Db = void 0; +const admin_1 = require("./admin"); +const bson_1 = require("./bson"); +const change_stream_1 = require("./change_stream"); +const collection_1 = require("./collection"); +const CONSTANTS = require("./constants"); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +const list_collections_cursor_1 = require("./cursor/list_collections_cursor"); +const run_command_cursor_1 = require("./cursor/run_command_cursor"); +const error_1 = require("./error"); +const collections_1 = require("./operations/collections"); +const create_collection_1 = require("./operations/create_collection"); +const drop_1 = require("./operations/drop"); +const execute_operation_1 = require("./operations/execute_operation"); +const indexes_1 = require("./operations/indexes"); +const profiling_level_1 = require("./operations/profiling_level"); +const remove_user_1 = require("./operations/remove_user"); +const rename_1 = require("./operations/rename"); +const run_command_1 = require("./operations/run_command"); +const set_profiling_level_1 = require("./operations/set_profiling_level"); +const stats_1 = require("./operations/stats"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'useBigInt64', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +class Db { + /** + * Creates a new Db instance. + * + * Db name cannot contain a dot, the server may apply more restrictions when an operation is run. + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction. + */ + constructor(client, databaseName, options) { + options = options ?? {}; + // Filter the options + options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST); + // Ensure there are no dots in database name + if (typeof databaseName === 'string' && databaseName.includes('.')) { + throw new error_1.MongoInvalidArgumentError(`Database names cannot contain the character '.'`); + } + // Internal state of the db object + this.s = { + // Options + options, + // Unpack read preference + readPreference: read_preference_1.ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: (0, bson_1.resolveBSONOptions)(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Namespace + namespace: new utils_1.MongoDBNamespace(databaseName) + }; + this.client = client; + } + get databaseName() { + return this.s.namespace.db; + } + // Options + get options() { + return this.s.options; + } + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk() { + return this.s.readPreference?.preference !== 'primary' || false; + } + get readConcern() { + return this.s.readConcern; + } + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.client.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + // get the write Concern + get writeConcern() { + return this.s.writeConcern; + } + get namespace() { + return this.s.namespace.toString(); + } + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/ + * + * Collection namespace validation is performed server-side. + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + */ + async createCollection(name, options) { + return (0, execute_operation_1.executeOperation)(this.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * The driver will ensure the following fields are attached to the command sent to the server: + * - `lsid` - sourced from an implicit session or options.session + * - `$readPreference` - defaults to primary or can be configured by options.readPreference + * - `$db` - sourced from the name of this database + * + * If the client has a serverApi setting: + * - `apiVersion` + * - `apiStrict` + * - `apiDeprecationErrors` + * + * When in a transaction: + * - `readConcern` - sourced from readConcern set on the TransactionOptions + * - `writeConcern` - sourced from writeConcern set on the TransactionOptions + * + * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. + * + * @param command - The command to run + * @param options - Optional settings for the command + */ + async command(command, options) { + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this, command, { + ...(0, bson_1.resolveBSONOptions)(options), + session: options?.session, + readPreference: options?.readPreference + })); + } + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the Admin db instance */ + admin() { + return new admin_1.Admin(this); + } + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * Collection namespace validation is performed server-side. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name, options = {}) { + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + async stats(options) { + return (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + listCollections(filter = {}, options = {}) { + return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + */ + async renameCollection(fromCollection, toCollection, options) { + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary })); + } + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + */ + async dropCollection(name, options) { + return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + async dropDatabase(options) { + return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + async collections(options) { + return (0, execute_operation_1.executeOperation)(this.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + */ + async createIndex(name, indexSpec, options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username, options) { + return (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + async setProfilingLevel(level, options) { + return (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + async profilingLevel(options) { + return (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + async indexInformation(name, options) { + return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to provide the schema that may be defined for all the collections within this database + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** + * A low level cursor API providing basic driver functionality: + * - ClientSession management + * - ReadPreference for server selection + * - Running getMores automatically when a local batch is exhausted + * + * @param command - The command that will start a cursor on the server. + * @param options - Configurations for running the command, bson options will apply to getMores + */ + runCursorCommand(command, options) { + return new run_command_cursor_1.RunCommandCursor(this, command, options); + } +} +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; +exports.Db = Db; +//# sourceMappingURL=db.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/db.js.map b/nodejs/node_modules/mongodb/lib/db.js.map new file mode 100644 index 00000000..31a2cb12 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/db.js.map @@ -0,0 +1 @@ +{"version":3,"file":"db.js","sourceRoot":"","sources":["../src/db.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAChC,iCAAsF;AACtF,mDAAoG;AACpG,6CAAkE;AAClE,yCAAyC;AACzC,oEAAgE;AAChE,8EAAyE;AACzE,oEAA6F;AAC7F,mCAAoD;AAIpD,0DAAgE;AAEhE,sEAGwC;AACxC,4CAK2B;AAC3B,sEAAkE;AAClE,kDAK8B;AAE9B,kEAAmG;AACnG,0DAAuF;AACvF,gDAA0E;AAC1E,0DAAuF;AACvF,0EAI0C;AAC1C,8CAA2E;AAC3E,iDAA6C;AAC7C,uDAA4E;AAC5E,mCAA8F;AAC9F,mDAAyE;AAEzE,qBAAqB;AACrB,MAAM,qBAAqB,GAAG;IAC5B,cAAc;IACd,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;IACf,qBAAqB;IACrB,WAAW;IACX,oBAAoB;IACpB,KAAK;IACL,YAAY;IACZ,iBAAiB;IACjB,aAAa;IACb,kBAAkB;IAClB,iBAAiB;IACjB,aAAa;IACb,gBAAgB;IAChB,cAAc;IACd,YAAY;IACZ,sBAAsB;IACtB,eAAe;IACf,aAAa;IACb,aAAa;CACd,CAAC;AA6BF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,EAAE;IAcb;;;;;;;;OAQG;IACH,YAAY,MAAmB,EAAE,YAAoB,EAAE,OAAmB;QACxE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAExB,qBAAqB;QACrB,OAAO,GAAG,IAAA,qBAAa,EAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;QAExD,4CAA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mongodb/lib/deps.js b/nodejs/node_modules/mongodb/lib/deps.js new file mode 100644 index 00000000..31987844 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/deps.js @@ -0,0 +1,112 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getMongoDBClientEncryption = exports.aws4 = exports.getSocks = exports.getSnappy = exports.getGcpMetadata = exports.getAwsCredentialProvider = exports.getZstdLibrary = exports.ZStandard = exports.getKerberos = exports.Kerberos = void 0; +const error_1 = require("./error"); +function makeErrorModule(error) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_, key) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; + } + }); +} +exports.Kerberos = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `kerberos` not found. Please install it to enable kerberos authentication')); +function getKerberos() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Kerberos = require('kerberos'); + return exports.Kerberos; + } + catch { + return exports.Kerberos; + } +} +exports.getKerberos = getKerberos; +exports.ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression')); +function getZstdLibrary() { + try { + exports.ZStandard = require('@mongodb-js/zstd'); + return exports.ZStandard; + } + catch { + return exports.ZStandard; + } +} +exports.getZstdLibrary = getZstdLibrary; +function getAwsCredentialProvider() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('@aws-sdk/credential-providers'); + return credentialProvider; + } + catch { + return makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `@aws-sdk/credential-providers` not found.' + + ' Please install it to enable getting aws credentials via the official sdk.')); + } +} +exports.getAwsCredentialProvider = getAwsCredentialProvider; +function getGcpMetadata() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('gcp-metadata'); + return credentialProvider; + } + catch { + return makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `gcp-metadata` not found.' + + ' Please install it to enable getting gcp credentials via the official sdk.')); + } +} +exports.getGcpMetadata = getGcpMetadata; +function getSnappy() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const value = require('snappy'); + return value; + } + catch (cause) { + const kModuleError = new error_1.MongoMissingDependencyError('Optional module `snappy` not found. Please install it to enable snappy compression', { cause }); + return { kModuleError }; + } +} +exports.getSnappy = getSnappy; +function getSocks() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const value = require('socks'); + return value; + } + catch (cause) { + const kModuleError = new error_1.MongoMissingDependencyError('Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy', { cause }); + return { kModuleError }; + } +} +exports.getSocks = getSocks; +exports.aws4 = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `aws4` not found. Please install it to enable AWS authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.aws4 = require('aws4'); +} +catch { } // eslint-disable-line +/** A utility function to get the instance of mongodb-client-encryption, if it exists. */ +function getMongoDBClientEncryption() { + let mongodbClientEncryption = null; + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require('mongodb-client-encryption'); + } + catch (cause) { + const kModuleError = new error_1.MongoMissingDependencyError('Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.', { cause }); + return { kModuleError }; + } + return mongodbClientEncryption; +} +exports.getMongoDBClientEncryption = getMongoDBClientEncryption; +//# sourceMappingURL=deps.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/deps.js.map b/nodejs/node_modules/mongodb/lib/deps.js.map new file mode 100644 index 00000000..cba89046 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/deps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deps.js","sourceRoot":"","sources":["../src/deps.ts"],"names":[],"mappings":";;;AAEA,mCAAsD;AAGtD,SAAS,eAAe,CAAC,KAAU;IAC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AAC;KAChE;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,YAAY,GAAG,IAAI,mCAA2B,CAClD,sHAAsH,EACtH,EAAE,KAAK,EAAE,CACV,CAAC;QACF,OAAO,EAAE,YAAY,EAAE,CAAC;KACzB;IAED,OAAO,uBAAuB,CAAC;AACjC,CAAC;AAnBD,gEAmBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/encrypter.js b/nodejs/node_modules/mongodb/lib/encrypter.js new file mode 100644 index 00000000..06ed119c --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/encrypter.js @@ -0,0 +1,105 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Encrypter = void 0; +const util_1 = require("util"); +const auto_encrypter_1 = require("./client-side-encryption/auto_encrypter"); +const constants_1 = require("./constants"); +const deps_1 = require("./deps"); +const error_1 = require("./error"); +const mongo_client_1 = require("./mongo_client"); +/** @internal */ +const kInternalClient = Symbol('internalClient'); +/** @internal */ +class Encrypter { + constructor(client, uri, options) { + if (typeof options.autoEncryption !== 'object') { + throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + // initialize to null, if we call getInternalClient, we may set this it is important to not overwrite those function calls. + this[kInternalClient] = null; + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; + } + else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); + } + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; + } + else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } + else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + if (options.proxyHost) { + options.autoEncryption.proxyOptions = { + proxyHost: options.proxyHost, + proxyPort: options.proxyPort, + proxyUsername: options.proxyUsername, + proxyPassword: options.proxyPassword + }; + } + this.autoEncrypter = new auto_encrypter_1.AutoEncrypter(client, options.autoEncryption); + } + getInternalClient(client, uri, options) { + // TODO(NODE-4144): Remove new variable for type narrowing + let internalClient = this[kInternalClient]; + if (internalClient == null) { + const clonedOptions = {}; + for (const key of [ + ...Object.getOwnPropertyNames(options), + ...Object.getOwnPropertySymbols(options) + ]) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); + } + clonedOptions.minPoolSize = 0; + internalClient = new mongo_client_1.MongoClient(uri, clonedOptions); + this[kInternalClient] = internalClient; + for (const eventName of constants_1.MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + internalClient.on(eventName, listener); + } + } + client.on('newListener', (eventName, listener) => { + internalClient?.on(eventName, listener); + }); + this.needsConnecting = true; + } + return internalClient; + } + async connectInternalClient() { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + await internalClient.connect(); + } + } + closeCallback(client, force, callback) { + (0, util_1.callbackify)(this.close.bind(this))(client, force, callback); + } + async close(client, force) { + const maybeError = await this.autoEncrypter.teardown(!!force).catch(e => e); + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + return internalClient.close(force); + } + if (maybeError) { + throw maybeError; + } + } + static checkForMongoCrypt() { + const mongodbClientEncryption = (0, deps_1.getMongoDBClientEncryption)(); + if ('kModuleError' in mongodbClientEncryption) { + throw new error_1.MongoMissingDependencyError('Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project'); + } + } +} +exports.Encrypter = Encrypter; +//# sourceMappingURL=encrypter.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/encrypter.js.map b/nodejs/node_modules/mongodb/lib/encrypter.js.map new file mode 100644 index 00000000..23901825 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/encrypter.js.map @@ -0,0 +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U,CAAC;SAClB;IACH,CAAC;IAED,MAAM,CAAC,kBAAkB;QACvB,MAAM,uBAAuB,GAAG,IAAA,iCAA0B,GAAE,CAAC;QAC7D,IAAI,cAAc,IAAI,uBAAuB,EAAE;YAC7C,MAAM,IAAI,mCAA2B,CACnC,8DAA8D;gBAC5D,wEAAwE,CAC3E,CAAC;SACH;IACH,CAAC;CACF;AA9GD,8BA8GC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/error.js b/nodejs/node_modules/mongodb/lib/error.js new file mode 100644 index 00000000..f50a21c2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/error.js @@ -0,0 +1,1188 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isResumableError = exports.isNetworkTimeoutError = exports.isSDAMUnrecoverableError = exports.isNodeShuttingDownError = exports.isRetryableReadError = exports.isRetryableWriteError = exports.needsRetryableWriteLabel = exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.isNetworkErrorBeforeHandshake = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoUnexpectedServerResponseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoAzureError = exports.MongoAWSError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.MongoErrorLabel = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = void 0; +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); +/** + * @internal + * The legacy error message from the server that indicates the node is not a writable primary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp('not master', 'i'); +/** + * @internal + * The legacy error message from the server that indicates the node is not a primary or secondary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp('not master or secondary', 'i'); +/** + * @internal + * The error message from the server that indicates the node is recovering + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp('node is recovering', 'i'); +/** @internal MongoDB Error Codes */ +exports.MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotWritablePrimary: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotPrimaryNoSecondaryOk: 13435, + NotPrimaryOrSecondary: 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, + Reauthenticate: 391 +}); +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +exports.GET_MORE_RESUMABLE_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.StaleShardVersion, + exports.MONGODB_ERROR_CODES.StaleEpoch, + exports.MONGODB_ERROR_CODES.StaleConfig, + exports.MONGODB_ERROR_CODES.RetryChangeStream, + exports.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + exports.MONGODB_ERROR_CODES.CursorNotFound +]); +/** @public */ +exports.MongoErrorLabel = Object.freeze({ + RetryableWriteError: 'RetryableWriteError', + TransientTransactionError: 'TransientTransactionError', + UnknownTransactionCommitResult: 'UnknownTransactionCommitResult', + ResumableChangeStreamError: 'ResumableChangeStreamError', + HandshakeError: 'HandshakeError', + ResetPool: 'ResetPool', + PoolRequstedRetry: 'PoolRequstedRetry', + InterruptInUseConnections: 'InterruptInUseConnections', + NoWritesPerformed: 'NoWritesPerformed' +}); +function isAggregateError(e) { + return e != null && typeof e === 'object' && 'errors' in e && Array.isArray(e.errors); +} +/** + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument + */ +class MongoError extends Error { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options) { + super(message, options); + this[kErrorLabels] = new Set(); + } + /** @internal */ + static buildErrorMessage(e) { + if (typeof e === 'string') { + return e; + } + if (isAggregateError(e) && e.message.length === 0) { + return e.errors.length === 0 + ? 'AggregateError has an empty errors array. Please check the `cause` property for more information.' + : e.errors.map(({ message }) => message).join(', '); + } + return e != null && typeof e === 'object' && 'message' in e && typeof e.message === 'string' + ? e.message + : 'empty error message'; + } + get name() { + return 'MongoError'; + } + /** Legacy name for server error responses */ + get errmsg() { + return this.message; + } + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label) { + return this[kErrorLabels].has(label); + } + addErrorLabel(label) { + this[kErrorLabels].add(label); + } + get errorLabels() { + return Array.from(this[kErrorLabels]); + } +} +exports.MongoError = MongoError; +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +class MongoServerError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + this.errorResponse = message; + for (const name in message) { + if (name !== 'errorLabels' && + name !== 'errmsg' && + name !== 'message' && + name !== 'errorResponse') { + this[name] = message[name]; + } + } + } + get name() { + return 'MongoServerError'; + } +} +exports.MongoServerError = MongoServerError; +/** + * An error generated by the driver + * + * @public + * @category Error + */ +class MongoDriverError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoDriverError'; + } +} +exports.MongoDriverError = MongoDriverError; +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +class MongoAPIError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoAPIError'; + } +} +exports.MongoAPIError = MongoAPIError; +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +class MongoRuntimeError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoRuntimeError'; + } +} +exports.MongoRuntimeError = MongoRuntimeError; +/** + * An error generated when a batch command is re-executed after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +class MongoBatchReExecutionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + get name() { + return 'MongoBatchReExecutionError'; + } +} +exports.MongoBatchReExecutionError = MongoBatchReExecutionError; +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +class MongoDecompressionError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoDecompressionError'; + } +} +exports.MongoDecompressionError = MongoDecompressionError; +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +class MongoNotConnectedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoNotConnectedError'; + } +} +exports.MongoNotConnectedError = MongoNotConnectedError; +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +class MongoTransactionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoTransactionError'; + } +} +exports.MongoTransactionError = MongoTransactionError; +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +class MongoExpiredSessionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + get name() { + return 'MongoExpiredSessionError'; + } +} +exports.MongoExpiredSessionError = MongoExpiredSessionError; +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +class MongoKerberosError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoKerberosError'; + } +} +exports.MongoKerberosError = MongoKerberosError; +/** + * A error generated when the user attempts to authenticate + * via AWS, but fails + * + * @public + * @category Error + */ +class MongoAWSError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoAWSError'; + } +} +exports.MongoAWSError = MongoAWSError; +/** + * A error generated when the user attempts to authenticate + * via Azure, but fails. + * + * @public + * @category Error + */ +class MongoAzureError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoAzureError'; + } +} +exports.MongoAzureError = MongoAzureError; +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoChangeStreamError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoChangeStreamError'; + } +} +exports.MongoChangeStreamError = MongoChangeStreamError; +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +class MongoTailableCursorError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + get name() { + return 'MongoTailableCursorError'; + } +} +exports.MongoTailableCursorError = MongoTailableCursorError; +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoGridFSStreamError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSStreamError'; + } +} +exports.MongoGridFSStreamError = MongoGridFSStreamError; +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +class MongoGridFSChunkError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSChunkError'; + } +} +exports.MongoGridFSChunkError = MongoGridFSChunkError; +/** + * An error generated when a **parsable** unexpected response comes from the server. + * This is generally an error where the driver in a state expecting a certain behavior to occur in + * the next message from MongoDB but it receives something else. + * This error **does not** represent an issue with wire message formatting. + * + * #### Example + * When an operation fails, it is the driver's job to retry it. It must perform serverSelection + * again to make sure that it attempts the operation against a server in a good state. If server + * selection returns a server that does not support retryable operations, this error is used. + * This scenario is unlikely as retryable support would also have been determined on the first attempt + * but it is possible the state change could report a selectable server that does not support retries. + * + * @public + * @category Error + */ +class MongoUnexpectedServerResponseError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoUnexpectedServerResponseError'; + } +} +exports.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError; +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +class MongoCursorInUseError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Cursor is already initialized') { + super(message); + } + get name() { + return 'MongoCursorInUseError'; + } +} +exports.MongoCursorInUseError = MongoCursorInUseError; +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +class MongoServerClosedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Server is closed') { + super(message); + } + get name() { + return 'MongoServerClosedError'; + } +} +exports.MongoServerClosedError = MongoServerClosedError; +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +class MongoCursorExhaustedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message || 'Cursor is exhausted'); + } + get name() { + return 'MongoCursorExhaustedError'; + } +} +exports.MongoCursorExhaustedError = MongoCursorExhaustedError; +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +class MongoTopologyClosedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Topology is closed') { + super(message); + } + get name() { + return 'MongoTopologyClosedError'; + } +} +exports.MongoTopologyClosedError = MongoTopologyClosedError; +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +function isNetworkErrorBeforeHandshake(err) { + return err[kBeforeHandshake] === true; +} +exports.isNetworkErrorBeforeHandshake = isNetworkErrorBeforeHandshake; +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +class MongoNetworkError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options) { + super(message, { cause: options?.cause }); + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + get name() { + return 'MongoNetworkError'; + } +} +exports.MongoNetworkError = MongoNetworkError; +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption has a dependency on this error with an instanceof check + */ +class MongoNetworkTimeoutError extends MongoNetworkError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoNetworkTimeoutError'; + } +} +exports.MongoNetworkTimeoutError = MongoNetworkTimeoutError; +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +class MongoParseError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoParseError'; + } +} +exports.MongoParseError = MongoParseError; +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +class MongoInvalidArgumentError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoInvalidArgumentError'; + } +} +exports.MongoInvalidArgumentError = MongoInvalidArgumentError; +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +class MongoCompatibilityError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoCompatibilityError'; + } +} +exports.MongoCompatibilityError = MongoCompatibilityError; +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +class MongoMissingCredentialsError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingCredentialsError'; + } +} +exports.MongoMissingCredentialsError = MongoMissingCredentialsError; +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +class MongoMissingDependencyError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, options = {}) { + super(message, options); + } + get name() { + return 'MongoMissingDependencyError'; + } +} +exports.MongoMissingDependencyError = MongoMissingDependencyError; +/** + * An error signifying a general system issue + * @public + * @category Error + */ +class MongoSystemError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, reason) { + if (reason && reason.error) { + super(MongoError.buildErrorMessage(reason.error.message || reason.error), { + cause: reason.error + }); + } + else { + super(message); + } + if (reason) { + this.reason = reason; + } + this.code = reason.error?.code; + } + get name() { + return 'MongoSystemError'; + } +} +exports.MongoSystemError = MongoSystemError; +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +class MongoServerSelectionError extends MongoSystemError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, reason) { + super(message, reason); + } + get name() { + return 'MongoServerSelectionError'; + } +} +exports.MongoServerSelectionError = MongoServerSelectionError; +function makeWriteConcernResultObject(input) { + const output = Object.assign({}, input); + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + return output; +} +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +class MongoWriteConcernError extends MongoServerError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message, result) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + super(message); + this.errInfo = message.errInfo; + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + get name() { + return 'MongoWriteConcernError'; + } +} +exports.MongoWriteConcernError = MongoWriteConcernError; +// https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst#retryable-error +const RETRYABLE_READ_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit +]); +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES; +function needsRetryableWriteLabel(error, maxWireVersion) { + // pre-4.4 server, then the driver adds an error label for every valid case + // execute operation will only inspect the label, code/message logic is handled here + if (error instanceof MongoNetworkError) { + return true; + } + if (error instanceof MongoError) { + if ((maxWireVersion >= 9 || isRetryableWriteError(error)) && + !error.hasErrorLabel(exports.MongoErrorLabel.HandshakeError)) { + // If we already have the error label no need to add it again. 4.4+ servers add the label. + // In the case where we have a handshake error, need to fall down to the logic checking + // the codes. + return false; + } + } + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has(error.result?.code ?? error.code ?? 0); + } + if (error instanceof MongoError && typeof error.code === 'number') { + return RETRYABLE_WRITE_ERROR_CODES.has(error.code); + } + const isNotWritablePrimaryError = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + return false; +} +exports.needsRetryableWriteLabel = needsRetryableWriteLabel; +function isRetryableWriteError(error) { + return (error.hasErrorLabel(exports.MongoErrorLabel.RetryableWriteError) || + error.hasErrorLabel(exports.MongoErrorLabel.PoolRequstedRetry)); +} +exports.isRetryableWriteError = isRetryableWriteError; +/** Determines whether an error is something the driver should attempt to retry */ +function isRetryableReadError(error) { + const hasRetryableErrorCode = typeof error.code === 'number' ? RETRYABLE_READ_ERROR_CODES.has(error.code) : false; + if (hasRetryableErrorCode) { + return true; + } + if (error instanceof MongoNetworkError) { + return true; + } + const isNotWritablePrimaryError = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + return false; +} +exports.isRetryableReadError = isRetryableReadError; +const SDAM_RECOVERING_CODES = new Set([ + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); +const SDAM_NOT_PRIMARY_CODES = new Set([ + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.LegacyNotPrimary +]); +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress +]); +function isRecoveringError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + return (exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || + exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message)); +} +function isNotWritablePrimaryError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOT_PRIMARY_CODES.has(err.code); + } + if (isRecoveringError(err)) { + return false; + } + return exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); +} +function isNodeShuttingDownError(err) { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} +exports.isNodeShuttingDownError = isNodeShuttingDownError; +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +function isSDAMUnrecoverableError(error) { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + return isRecoveringError(error) || isNotWritablePrimaryError(error); +} +exports.isSDAMUnrecoverableError = isSDAMUnrecoverableError; +function isNetworkTimeoutError(err) { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} +exports.isNetworkTimeoutError = isNetworkTimeoutError; +function isResumableError(error, wireVersion) { + if (error == null || !(error instanceof MongoError)) { + return false; + } + if (error instanceof MongoNetworkError) { + return true; + } + if (wireVersion != null && wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error.code === exports.MONGODB_ERROR_CODES.CursorNotFound) { + return true; + } + return error.hasErrorLabel(exports.MongoErrorLabel.ResumableChangeStreamError); + } + if (typeof error.code === 'number') { + return exports.GET_MORE_RESUMABLE_CODES.has(error.code); + } + return false; +} +exports.isResumableError = isResumableError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/error.js.map b/nodejs/node_modules/mongodb/lib/error.js.map new file mode 100644 index 00000000..6a492a0b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":";;;AAOA,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAE3C;;;;GAIG;AACU,QAAA,yCAAyC,GAAG,IAAI,MAAM,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;AAEvF;;;;GAIG;AACU,QAAA,6CAA6C,GAAG,IAAI,MAAM,CACrE,yBAAyB,EACzB,GAAG,CACJ,CAAC;AAEF;;;;GAIG;AACU,QAAA,gCAAgC,GAAG,IAAI,MAAM,CAAC,oBAAoB,EAAE,GAAG,CAAC,CAAC;AAEtF,oCAAoC;AACvB,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,CAAC;IACf,cAAc,EAAE,EAAE;IAClB,kBAAkB,EAAE,EAAE;IACtB,kBAAkB,EAAE,GAAG;IACvB,iBAAiB,EAAE,GAAG;IACtB,eAAe,EAAE,IA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I,IAAI,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC;KACd;IAED,IAAI,KAAK,YAAY,iBAAiB,EAAE;QACtC,OAAO,IAAI,CAAC;KACb;IAED,IAAI,WAAW,IAAI,IAAI,IAAI,WAAW,IAAI,CAAC,EAAE;QAC3C,iJAAiJ;QACjJ,IAAI,KAAK,CAAC,IAAI,KAAK,2BAAmB,CAAC,cAAc,EAAE;YACrD,OAAO,IAAI,CAAC;SACb;QACD,OAAO,KAAK,CAAC,aAAa,CAAC,uBAAe,CAAC,0BAA0B,CAAC,CAAC;KACxE;IAED,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;QAClC,OAAO,gCAAwB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;KACjD;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAtBD,4CAsBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/explain.js b/nodejs/node_modules/mongodb/lib/explain.js new file mode 100644 index 00000000..4fb841e9 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/explain.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Explain = exports.ExplainVerbosity = void 0; +const error_1 = require("./error"); +/** @public */ +exports.ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +}); +/** @internal */ +class Explain { + constructor(verbosity) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? exports.ExplainVerbosity.allPlansExecution + : exports.ExplainVerbosity.queryPlanner; + } + else { + this.verbosity = verbosity; + } + } + static fromOptions(options) { + if (options?.explain == null) + return; + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); + } + throw new error_1.MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} +exports.Explain = Explain; +//# sourceMappingURL=explain.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/explain.js.map b/nodejs/node_modules/mongodb/lib/explain.js.map new file mode 100644 index 00000000..8b114f11 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/explain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"explain.js","sourceRoot":"","sources":["../src/explain.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAEpD,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,YAAY,EAAE,cAAc;IAC5B,oBAAoB,EAAE,sBAAsB;IAC5C,cAAc,EAAE,gBAAgB;IAChC,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC,CAAC;AAmBZ,gBAAgB;AAChB,MAAa,OAAO;IAGlB,YAAY,SAA+B;QACzC,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE;YAClC,IAAI,CAAC,SAAS,GAAG,SAAS;gBACxB,CAAC,CAAC,wBAAgB,CAAC,iBAAiB;gBACpC,CAAC,CAAC,wBAAgB,CAAC,YAAY,CAAC;SACnC;aAAM;YACL,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;SAC5B;IACH,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,OAAwB;QACzC,IAAI,OAAO,EAAE,OAAO,IAAI,IAAI;YAAE,OAAO;QAErC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAChC,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC/D,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;SAC7B;QAED,MAAM,IAAI,iCAAyB,CAAC,+CAA+C,CAAC,CAAC;IACvF,CAAC;CACF;AAvBD,0BAuBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/gridfs/download.js b/nodejs/node_modules/mongodb/lib/gridfs/download.js new file mode 100644 index 00000000..0a130e1d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/gridfs/download.js @@ -0,0 +1,275 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucketReadStream = void 0; +const stream_1 = require("stream"); +const error_1 = require("../error"); +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +class GridFSBucketReadStream extends stream_1.Readable { + /** + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + * @internal + */ + constructor(chunks, files, readPreference, filter, options) { + super({ emitClose: true }); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + _read() { + if (this.destroyed) + return; + waitForFile(this, () => doRead(this)); + } + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0) { + throwIfInitialized(this); + this.s.options.start = start; + return this; + } + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0) { + throwIfInitialized(this); + this.s.options.end = end; + return this; + } + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + */ + async abort() { + this.push(null); + this.destroy(); + await this.s.cursor?.close(); + } +} +/** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ +GridFSBucketReadStream.FILE = 'file'; +exports.GridFSBucketReadStream = GridFSBucketReadStream; +function throwIfInitialized(stream) { + if (stream.s.init) { + throw new error_1.MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} +function doRead(stream) { + if (stream.destroyed) + return; + if (!stream.s.cursor) + return; + if (!stream.s.file) + return; + const handleReadResult = ({ error, doc }) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.destroy(error); + return; + } + if (!doc) { + stream.push(null); + stream.s.cursor?.close().then(() => null, error => stream.destroy(error)); + return; + } + if (!stream.s.file) + return; + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.destroy(new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + if (doc.n < expectedN) { + return stream.destroy(new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.destroy(new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes`)); + } + return stream.destroy(new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`)); + } + stream.s.bytesRead += buf.byteLength; + if (buf.byteLength === 0) { + return stream.push(null); + } + let sliceStart = null; + let sliceEnd = null; + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; + } + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; + } + else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; + } + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); + } + stream.push(buf); + return; + }; + stream.s.cursor.next().then(doc => handleReadResult({ error: null, doc }), error => handleReadResult({ error, doc: null })); +} +function init(stream) { + const findOneOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + const handleReadResult = ({ error, doc }) => { + if (error) { + return stream.destroy(error); + } + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new error_1.MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.destroy(err); + } + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; + } + if (stream.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + stream.destroy(); + return; + } + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } + catch (error) { + return stream.destroy(error); + } + const filter = { files_id: doc._id }; + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.readPreference); + } + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc; + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); + } + catch (error) { + return stream.destroy(error); + } + stream.emit(GridFSBucketReadStream.FILE, doc); + return; + }; + stream.s.files.findOne(stream.s.filter, findOneOptions).then(doc => handleReadResult({ error: null, doc }), error => handleReadResult({ error, doc: null })); +} +function waitForFile(stream, callback) { + if (stream.s.file) { + return callback(); + } + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + stream.once('file', () => { + callback(); + }); +} +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`); + } + if (options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); + } + if (options.end != null && options.end < options.start) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`); + } + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + return options.start - stream.s.bytesRead; + } + throw new error_1.MongoInvalidArgumentError('Start option must be defined'); +} +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`); + } + if (options.start == null || options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } + throw new error_1.MongoInvalidArgumentError('End option must be defined'); +} +//# sourceMappingURL=download.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/gridfs/download.js.map b/nodejs/node_modules/mongodb/lib/gridfs/download.js.map new file mode 100644 index 00000000..480effe1 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/gridfs/download.js.map @@ -0,0 +1 @@ +{"version":3,"file":"download.js","sourceRoot":"","sources":["../../src/gridfs/download.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AA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OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE;YAC5B,MAAM,IAAI,iCAAyB,CACjC,eAAe,OAAO,CAAC,GAAG,mDAAmD,GAAG,CAAC,MAAM,GAAG,CAC3F,CAAC;SACH;QACD,IAAI,OAAO,CAAC,KAAK,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,GAAG,CAAC,EAAE;YAC9C,MAAM,IAAI,iCAAyB,CAAC,eAAe,OAAO,CAAC,GAAG,wBAAwB,CAAC,CAAC;SACzF;QAED,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEpF,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,CAAC;QAE7D,MAAM,CAAC,CAAC,CAAC,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QAE9D,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC;KAC7E;IACD,MAAM,IAAI,iCAAyB,CAAC,4BAA4B,CAAC,CAAC;AACpE,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/gridfs/index.js b/nodejs/node_modules/mongodb/lib/gridfs/index.js new file mode 100644 index 00000000..5b42c2a3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/gridfs/index.js @@ -0,0 +1,128 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucket = void 0; +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const write_concern_1 = require("../write_concern"); +const download_1 = require("./download"); +const upload_1 = require("./upload"); +const DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; +/** + * Constructor for a streaming GridFS interface + * @public + */ +class GridFSBucket extends mongo_types_1.TypedEventEmitter { + constructor(db, options) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: write_concern_1.WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, options); + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id, filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, { ...options, id }); + } + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id, options) { + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, options); + } + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + async delete(id) { + const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }); + // Delete orphaned chunks before returning FileNotFound + await this.s._chunksCollection.deleteMany({ files_id: id }); + if (deletedCount === 0) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + throw new error_1.MongoRuntimeError(`File not found for id ${id}`); + } + } + /** Convenience wrapper around find on the files collection */ + find(filter = {}, options = {}) { + return this.s._filesCollection.find(filter, options); + } + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename, options) { + let sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } + else { + skip = -options.revision - 1; + } + } + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { ...options, sort, skip }); + } + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + async rename(id, filename) { + const filter = { _id: id }; + const update = { $set: { filename } }; + const { matchedCount } = await this.s._filesCollection.updateOne(filter, update); + if (matchedCount === 0) { + throw new error_1.MongoRuntimeError(`File with id ${id} not found`); + } + } + /** Removes this bucket's files collection, followed by its chunks collection. */ + async drop() { + await this.s._filesCollection.drop(); + await this.s._chunksCollection.drop(); + } +} +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ +GridFSBucket.INDEX = 'index'; +exports.GridFSBucket = GridFSBucket; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/gridfs/index.js.map b/nodejs/node_modules/mongodb/lib/gridfs/index.js.map new file mode 100644 index 00000000..01d7288d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/gridfs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/gridfs/index.ts"],"names":[],"mappings":";;;AAIA,oCAA6C;AAC7C,gDAAgE;AAGhE,oDAA0E;AAE1E,yCAKoB;AACpB,qCAIkB;AAElB,MAAM,6BAA6B,GAG/B;IACF,UAAU,EAAE,IAAI;IAChB,cAAc,EAA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C7B,EAAE,QAAQ,EAAE,EACZ,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAC3B,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,MAAM,CAAC,EAAY,EAAE,QAAgB;QACzC,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;QAC3B,MAAM,MAAM,GAAG,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,EAAE,CAAC;QACtC,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjF,IAAI,YAAY,KAAK,CAAC,EAAE;YACtB,MAAM,IAAI,yBAAiB,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC;SAC7D;IACH,CAAC;IAED,iFAAiF;IACjF,KAAK,CAAC,IAAI;QACR,MAAM,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;QACrC,MAAM,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC;IACxC,CAAC;;AA/ID;;;;;;;GAOG;AACa,kBAAK,GAAG,OAAgB,CAAC;AAZ9B,oCAAY"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/gridfs/upload.js b/nodejs/node_modules/mongodb/lib/gridfs/upload.js new file mode 100644 index 00000000..ed6aaead --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/gridfs/upload.js @@ -0,0 +1,305 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GridFSBucketWriteStream = void 0; +const stream_1 = require("stream"); +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const write_concern_1 = require("./../write_concern"); +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +class GridFSBucketWriteStream extends stream_1.Writable { + /** + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + * @internal + */ + constructor(bucket, filename, options) { + super(); + /** + * The document containing information about the inserted file. + * This property is defined _after_ the finish event has been emitted. + * It will remain `null` if an error occurs. + * + * @example + * ```ts + * fs.createReadStream('file.txt') + * .pipe(bucket.openUploadStream('file.txt')) + * .on('finish', function () { + * console.log(this.gridFSFile) + * }) + * ``` + */ + this.gridFSFile = null; + options = options ?? {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + this.id = options.id ? options.id : new bson_1.ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + checkIndexes(this).then(() => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }, () => null); + } + } + /** + * @internal + * + * The stream is considered constructed when the indexes are done being created + */ + _construct(callback) { + if (this.bucket.s.checkedIndexes) { + return process.nextTick(callback); + } + this.bucket.once('index', callback); + } + /** + * @internal + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + */ + _write(chunk, encoding, callback) { + doWrite(this, chunk, encoding, callback); + } + /** @internal */ + _final(callback) { + if (this.state.streamEnd) { + return process.nextTick(callback); + } + this.state.streamEnd = true; + writeRemnant(this, callback); + } + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + async abort() { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new error_1.MongoAPIError('Cannot abort a stream that has already completed'); + } + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new error_1.MongoAPIError('Cannot call abort() on a stream twice'); + } + this.state.aborted = true; + await this.chunks.deleteMany({ files_id: this.id }); + } +} +exports.GridFSBucketWriteStream = GridFSBucketWriteStream; +function handleError(stream, error, callback) { + if (stream.state.errored) { + process.nextTick(callback); + return; + } + stream.state.errored = true; + process.nextTick(callback, error); +} +function createChunkDoc(filesId, n, data) { + return { + _id: new bson_1.ObjectId(), + files_id: filesId, + n, + data + }; +} +async function checkChunksIndex(stream) { + const index = { files_id: 1, n: 1 }; + let indexes; + try { + indexes = await stream.chunks.listIndexes().toArray(); + } + catch (error) { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } + else { + throw error; + } + } + const hasChunksIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + return true; + } + return false; + }); + if (!hasChunksIndex) { + await stream.chunks.createIndex(index, { + ...stream.writeConcern, + background: true, + unique: true + }); + } +} +function checkDone(stream, callback) { + if (stream.done) { + return process.nextTick(callback); + } + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const gridFSFile = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata); + if (isAborted(stream, callback)) { + return; + } + stream.files.insertOne(gridFSFile, { writeConcern: stream.writeConcern }).then(() => { + stream.gridFSFile = gridFSFile; + callback(); + }, error => handleError(stream, error, callback)); + return; + } + process.nextTick(callback); +} +async function checkIndexes(stream) { + const doc = await stream.files.findOne({}, { projection: { _id: 1 } }); + if (doc != null) { + // If at least one document exists assume the collection has the required index + return; + } + const index = { filename: 1, uploadDate: 1 }; + let indexes; + try { + indexes = await stream.files.listIndexes().toArray(); + } + catch (error) { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } + else { + throw error; + } + } + const hasFileIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + return true; + } + return false; + }); + if (!hasFileIndex) { + await stream.files.createIndex(index, { background: false }); + } + await checkChunksIndex(stream); +} +function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) { + const ret = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + if (contentType) { + ret.contentType = contentType; + } + if (aliases) { + ret.aliases = aliases; + } + if (metadata) { + ret.metadata = metadata; + } + return ret; +} +function doWrite(stream, chunk, encoding, callback) { + if (isAborted(stream, callback)) { + return; + } + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + stream.length += inputBuf.length; + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.pos += inputBuf.length; + process.nextTick(callback); + return; + } + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + let inputBufRemaining = inputBuf.length; + let spaceRemaining = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + if (isAborted(stream, callback)) { + return; + } + stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(() => { + --stream.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + checkDone(stream, callback); + } + }, error => handleError(stream, error, callback)); + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } +} +function writeRemnant(stream, callback) { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + ++stream.state.outstandingRequests; + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + // If the stream was aborted, do not write remnant + if (isAborted(stream, callback)) { + return; + } + stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(() => { + --stream.state.outstandingRequests; + checkDone(stream, callback); + }, error => handleError(stream, error, callback)); +} +function isAborted(stream, callback) { + if (stream.state.aborted) { + process.nextTick(callback, new error_1.MongoAPIError('Stream has been aborted')); + return true; + } + return false; +} +//# sourceMappingURL=upload.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/gridfs/upload.js.map b/nodejs/node_modules/mongodb/lib/gridfs/upload.js.map new file mode 100644 index 00000000..e1d42ea5 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/gridfs/upload.js.map @@ -0,0 +1 @@ +{"version":3,"file":"upload.js","sourceRoot":"","sources":["../../src/gridfs/upload.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAGlC,kCAAmC;AAEnC,oCAA0E;AAG1E,sDAAkD;AAgClD;;;;;GAKG;AACH,MAAa,uBAAwB,SAAQ,iBAAQ;IAqDnD;;;;;OAKG;IACH,YAAY,MAAoB,EAAE,QAAgB,EAAE,OAAwC;QAC1F,KAAK,EAAE,CAAC;QAvBV;;;;;;;;;;;;;WAaG;QACH,eAAU,GAAsB,IAAI,CAAC;QAWnC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QACxB,IAAI,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;QACnC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC9B,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAC9C,CAAC;AACJ,CAAC;AAED,SAAS,SAAS,CAAC,MAA+B,EAAE,QAAwB;IAC1E,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE;QACxB,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,qBAAa,CAAC,yBAAyB,CAAC,CAAC,CAAC;QACzE,OAAO,IAAI,CAAC;KACb;IACD,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/index.js b/nodejs/node_modules/mongodb/lib/index.js new file mode 100644 index 00000000..69cdca12 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/index.js @@ -0,0 +1,180 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoUnexpectedServerResponseError = exports.MongoTransactionError = exports.MongoTopologyClosedError = exports.MongoTailableCursorError = exports.MongoSystemError = exports.MongoServerSelectionError = exports.MongoServerError = exports.MongoServerClosedError = exports.MongoRuntimeError = exports.MongoParseError = exports.MongoNotConnectedError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoKerberosError = exports.MongoInvalidArgumentError = exports.MongoGridFSStreamError = exports.MongoGridFSChunkError = exports.MongoExpiredSessionError = exports.MongoError = exports.MongoDriverError = exports.MongoDecompressionError = exports.MongoCursorInUseError = exports.MongoCursorExhaustedError = exports.MongoCompatibilityError = exports.MongoChangeStreamError = exports.MongoBatchReExecutionError = exports.MongoAzureError = exports.MongoAWSError = exports.MongoAPIError = exports.ChangeStreamCursor = exports.ClientEncryption = exports.MongoBulkWriteError = exports.UUID = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = exports.BSON = void 0; +exports.ConnectionPoolReadyEvent = exports.ConnectionPoolMonitoringEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolClearedEvent = exports.ConnectionCreatedEvent = exports.ConnectionClosedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckedInEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = exports.CommandFailedEvent = exports.WriteConcern = exports.ReadPreference = exports.ReadConcern = exports.TopologyType = exports.ServerType = exports.ReadPreferenceMode = exports.ReadConcernLevel = exports.ProfilingLevel = exports.ReturnDocument = exports.ServerApiVersion = exports.ExplainVerbosity = exports.MongoErrorLabel = exports.CURSOR_FLAGS = exports.Compressor = exports.AuthMechanism = exports.GSSAPICanonicalizationValue = exports.AutoEncryptionLoggerLevel = exports.BatchType = exports.UnorderedBulkOperation = exports.OrderedBulkOperation = exports.MongoClient = exports.ListIndexesCursor = exports.ListCollectionsCursor = exports.GridFSBucketWriteStream = exports.GridFSBucketReadStream = exports.GridFSBucket = exports.FindCursor = exports.Db = exports.Collection = exports.ClientSession = exports.ChangeStream = exports.CancellationToken = exports.AggregationCursor = exports.Admin = exports.AbstractCursor = exports.MongoWriteConcernError = void 0; +exports.MongoClientAuthProviders = exports.MongoCryptKMSRequestNetworkTimeoutError = exports.MongoCryptInvalidArgumentError = exports.MongoCryptError = exports.MongoCryptCreateEncryptedCollectionError = exports.MongoCryptCreateDataKeyError = exports.MongoCryptAzureKMSRequestError = exports.SrvPollingEvent = exports.WaitingForSuitableServerEvent = exports.ServerSelectionSucceededEvent = exports.ServerSelectionStartedEvent = exports.ServerSelectionFailedEvent = exports.ServerSelectionEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ServerHeartbeatFailedEvent = exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ConnectionReadyEvent = void 0; +const admin_1 = require("./admin"); +Object.defineProperty(exports, "Admin", { enumerable: true, get: function () { return admin_1.Admin; } }); +const ordered_1 = require("./bulk/ordered"); +Object.defineProperty(exports, "OrderedBulkOperation", { enumerable: true, get: function () { return ordered_1.OrderedBulkOperation; } }); +const unordered_1 = require("./bulk/unordered"); +Object.defineProperty(exports, "UnorderedBulkOperation", { enumerable: true, get: function () { return unordered_1.UnorderedBulkOperation; } }); +const change_stream_1 = require("./change_stream"); +Object.defineProperty(exports, "ChangeStream", { enumerable: true, get: function () { return change_stream_1.ChangeStream; } }); +const collection_1 = require("./collection"); +Object.defineProperty(exports, "Collection", { enumerable: true, get: function () { return collection_1.Collection; } }); +const abstract_cursor_1 = require("./cursor/abstract_cursor"); +Object.defineProperty(exports, "AbstractCursor", { enumerable: true, get: function () { return abstract_cursor_1.AbstractCursor; } }); +const aggregation_cursor_1 = require("./cursor/aggregation_cursor"); +Object.defineProperty(exports, "AggregationCursor", { enumerable: true, get: function () { return aggregation_cursor_1.AggregationCursor; } }); +const find_cursor_1 = require("./cursor/find_cursor"); +Object.defineProperty(exports, "FindCursor", { enumerable: true, get: function () { return find_cursor_1.FindCursor; } }); +const list_collections_cursor_1 = require("./cursor/list_collections_cursor"); +Object.defineProperty(exports, "ListCollectionsCursor", { enumerable: true, get: function () { return list_collections_cursor_1.ListCollectionsCursor; } }); +const list_indexes_cursor_1 = require("./cursor/list_indexes_cursor"); +Object.defineProperty(exports, "ListIndexesCursor", { enumerable: true, get: function () { return list_indexes_cursor_1.ListIndexesCursor; } }); +const db_1 = require("./db"); +Object.defineProperty(exports, "Db", { enumerable: true, get: function () { return db_1.Db; } }); +const gridfs_1 = require("./gridfs"); +Object.defineProperty(exports, "GridFSBucket", { enumerable: true, get: function () { return gridfs_1.GridFSBucket; } }); +const download_1 = require("./gridfs/download"); +Object.defineProperty(exports, "GridFSBucketReadStream", { enumerable: true, get: function () { return download_1.GridFSBucketReadStream; } }); +const upload_1 = require("./gridfs/upload"); +Object.defineProperty(exports, "GridFSBucketWriteStream", { enumerable: true, get: function () { return upload_1.GridFSBucketWriteStream; } }); +const mongo_client_1 = require("./mongo_client"); +Object.defineProperty(exports, "MongoClient", { enumerable: true, get: function () { return mongo_client_1.MongoClient; } }); +const mongo_types_1 = require("./mongo_types"); +Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return mongo_types_1.CancellationToken; } }); +const sessions_1 = require("./sessions"); +Object.defineProperty(exports, "ClientSession", { enumerable: true, get: function () { return sessions_1.ClientSession; } }); +/** @public */ +var bson_1 = require("./bson"); +Object.defineProperty(exports, "BSON", { enumerable: true, get: function () { return bson_1.BSON; } }); +var bson_2 = require("./bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_2.Binary; } }); +Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function () { return bson_2.BSONRegExp; } }); +Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function () { return bson_2.BSONSymbol; } }); +Object.defineProperty(exports, "BSONType", { enumerable: true, get: function () { return bson_2.BSONType; } }); +Object.defineProperty(exports, "Code", { enumerable: true, get: function () { return bson_2.Code; } }); +Object.defineProperty(exports, "DBRef", { enumerable: true, get: function () { return bson_2.DBRef; } }); +Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function () { return bson_2.Decimal128; } }); +Object.defineProperty(exports, "Double", { enumerable: true, get: function () { return bson_2.Double; } }); +Object.defineProperty(exports, "Int32", { enumerable: true, get: function () { return bson_2.Int32; } }); +Object.defineProperty(exports, "Long", { enumerable: true, get: function () { return bson_2.Long; } }); +Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function () { return bson_2.MaxKey; } }); +Object.defineProperty(exports, "MinKey", { enumerable: true, get: function () { return bson_2.MinKey; } }); +Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function () { return bson_2.ObjectId; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_2.Timestamp; } }); +Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return bson_2.UUID; } }); +var common_1 = require("./bulk/common"); +Object.defineProperty(exports, "MongoBulkWriteError", { enumerable: true, get: function () { return common_1.MongoBulkWriteError; } }); +var client_encryption_1 = require("./client-side-encryption/client_encryption"); +Object.defineProperty(exports, "ClientEncryption", { enumerable: true, get: function () { return client_encryption_1.ClientEncryption; } }); +var change_stream_cursor_1 = require("./cursor/change_stream_cursor"); +Object.defineProperty(exports, "ChangeStreamCursor", { enumerable: true, get: function () { return change_stream_cursor_1.ChangeStreamCursor; } }); +var error_1 = require("./error"); +Object.defineProperty(exports, "MongoAPIError", { enumerable: true, get: function () { return error_1.MongoAPIError; } }); +Object.defineProperty(exports, "MongoAWSError", { enumerable: true, get: function () { return error_1.MongoAWSError; } }); +Object.defineProperty(exports, "MongoAzureError", { enumerable: true, get: function () { return error_1.MongoAzureError; } }); +Object.defineProperty(exports, "MongoBatchReExecutionError", { enumerable: true, get: function () { return error_1.MongoBatchReExecutionError; } }); +Object.defineProperty(exports, "MongoChangeStreamError", { enumerable: true, get: function () { return error_1.MongoChangeStreamError; } }); +Object.defineProperty(exports, "MongoCompatibilityError", { enumerable: true, get: function () { return error_1.MongoCompatibilityError; } }); +Object.defineProperty(exports, "MongoCursorExhaustedError", { enumerable: true, get: function () { return error_1.MongoCursorExhaustedError; } }); +Object.defineProperty(exports, "MongoCursorInUseError", { enumerable: true, get: function () { return error_1.MongoCursorInUseError; } }); +Object.defineProperty(exports, "MongoDecompressionError", { enumerable: true, get: function () { return error_1.MongoDecompressionError; } }); +Object.defineProperty(exports, "MongoDriverError", { enumerable: true, get: function () { return error_1.MongoDriverError; } }); +Object.defineProperty(exports, "MongoError", { enumerable: true, get: function () { return error_1.MongoError; } }); +Object.defineProperty(exports, "MongoExpiredSessionError", { enumerable: true, get: function () { return error_1.MongoExpiredSessionError; } }); +Object.defineProperty(exports, "MongoGridFSChunkError", { enumerable: true, get: function () { return error_1.MongoGridFSChunkError; } }); +Object.defineProperty(exports, "MongoGridFSStreamError", { enumerable: true, get: function () { return error_1.MongoGridFSStreamError; } }); +Object.defineProperty(exports, "MongoInvalidArgumentError", { enumerable: true, get: function () { return error_1.MongoInvalidArgumentError; } }); +Object.defineProperty(exports, "MongoKerberosError", { enumerable: true, get: function () { return error_1.MongoKerberosError; } }); +Object.defineProperty(exports, "MongoMissingCredentialsError", { enumerable: true, get: function () { return error_1.MongoMissingCredentialsError; } }); +Object.defineProperty(exports, "MongoMissingDependencyError", { enumerable: true, get: function () { return error_1.MongoMissingDependencyError; } }); +Object.defineProperty(exports, "MongoNetworkError", { enumerable: true, get: function () { return error_1.MongoNetworkError; } }); +Object.defineProperty(exports, "MongoNetworkTimeoutError", { enumerable: true, get: function () { return error_1.MongoNetworkTimeoutError; } }); +Object.defineProperty(exports, "MongoNotConnectedError", { enumerable: true, get: function () { return error_1.MongoNotConnectedError; } }); +Object.defineProperty(exports, "MongoParseError", { enumerable: true, get: function () { return error_1.MongoParseError; } }); +Object.defineProperty(exports, "MongoRuntimeError", { enumerable: true, get: function () { return error_1.MongoRuntimeError; } }); +Object.defineProperty(exports, "MongoServerClosedError", { enumerable: true, get: function () { return error_1.MongoServerClosedError; } }); +Object.defineProperty(exports, "MongoServerError", { enumerable: true, get: function () { return error_1.MongoServerError; } }); +Object.defineProperty(exports, "MongoServerSelectionError", { enumerable: true, get: function () { return error_1.MongoServerSelectionError; } }); +Object.defineProperty(exports, "MongoSystemError", { enumerable: true, get: function () { return error_1.MongoSystemError; } }); +Object.defineProperty(exports, "MongoTailableCursorError", { enumerable: true, get: function () { return error_1.MongoTailableCursorError; } }); +Object.defineProperty(exports, "MongoTopologyClosedError", { enumerable: true, get: function () { return error_1.MongoTopologyClosedError; } }); +Object.defineProperty(exports, "MongoTransactionError", { enumerable: true, get: function () { return error_1.MongoTransactionError; } }); +Object.defineProperty(exports, "MongoUnexpectedServerResponseError", { enumerable: true, get: function () { return error_1.MongoUnexpectedServerResponseError; } }); +Object.defineProperty(exports, "MongoWriteConcernError", { enumerable: true, get: function () { return error_1.MongoWriteConcernError; } }); +// enums +var common_2 = require("./bulk/common"); +Object.defineProperty(exports, "BatchType", { enumerable: true, get: function () { return common_2.BatchType; } }); +var auto_encrypter_1 = require("./client-side-encryption/auto_encrypter"); +Object.defineProperty(exports, "AutoEncryptionLoggerLevel", { enumerable: true, get: function () { return auto_encrypter_1.AutoEncryptionLoggerLevel; } }); +var gssapi_1 = require("./cmap/auth/gssapi"); +Object.defineProperty(exports, "GSSAPICanonicalizationValue", { enumerable: true, get: function () { return gssapi_1.GSSAPICanonicalizationValue; } }); +var providers_1 = require("./cmap/auth/providers"); +Object.defineProperty(exports, "AuthMechanism", { enumerable: true, get: function () { return providers_1.AuthMechanism; } }); +var compression_1 = require("./cmap/wire_protocol/compression"); +Object.defineProperty(exports, "Compressor", { enumerable: true, get: function () { return compression_1.Compressor; } }); +var abstract_cursor_2 = require("./cursor/abstract_cursor"); +Object.defineProperty(exports, "CURSOR_FLAGS", { enumerable: true, get: function () { return abstract_cursor_2.CURSOR_FLAGS; } }); +var error_2 = require("./error"); +Object.defineProperty(exports, "MongoErrorLabel", { enumerable: true, get: function () { return error_2.MongoErrorLabel; } }); +var explain_1 = require("./explain"); +Object.defineProperty(exports, "ExplainVerbosity", { enumerable: true, get: function () { return explain_1.ExplainVerbosity; } }); +var mongo_client_2 = require("./mongo_client"); +Object.defineProperty(exports, "ServerApiVersion", { enumerable: true, get: function () { return mongo_client_2.ServerApiVersion; } }); +var find_and_modify_1 = require("./operations/find_and_modify"); +Object.defineProperty(exports, "ReturnDocument", { enumerable: true, get: function () { return find_and_modify_1.ReturnDocument; } }); +var set_profiling_level_1 = require("./operations/set_profiling_level"); +Object.defineProperty(exports, "ProfilingLevel", { enumerable: true, get: function () { return set_profiling_level_1.ProfilingLevel; } }); +var read_concern_1 = require("./read_concern"); +Object.defineProperty(exports, "ReadConcernLevel", { enumerable: true, get: function () { return read_concern_1.ReadConcernLevel; } }); +var read_preference_1 = require("./read_preference"); +Object.defineProperty(exports, "ReadPreferenceMode", { enumerable: true, get: function () { return read_preference_1.ReadPreferenceMode; } }); +var common_3 = require("./sdam/common"); +Object.defineProperty(exports, "ServerType", { enumerable: true, get: function () { return common_3.ServerType; } }); +Object.defineProperty(exports, "TopologyType", { enumerable: true, get: function () { return common_3.TopologyType; } }); +// Helper classes +var read_concern_2 = require("./read_concern"); +Object.defineProperty(exports, "ReadConcern", { enumerable: true, get: function () { return read_concern_2.ReadConcern; } }); +var read_preference_2 = require("./read_preference"); +Object.defineProperty(exports, "ReadPreference", { enumerable: true, get: function () { return read_preference_2.ReadPreference; } }); +var write_concern_1 = require("./write_concern"); +Object.defineProperty(exports, "WriteConcern", { enumerable: true, get: function () { return write_concern_1.WriteConcern; } }); +// events +var command_monitoring_events_1 = require("./cmap/command_monitoring_events"); +Object.defineProperty(exports, "CommandFailedEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandFailedEvent; } }); +Object.defineProperty(exports, "CommandStartedEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandStartedEvent; } }); +Object.defineProperty(exports, "CommandSucceededEvent", { enumerable: true, get: function () { return command_monitoring_events_1.CommandSucceededEvent; } }); +var connection_pool_events_1 = require("./cmap/connection_pool_events"); +Object.defineProperty(exports, "ConnectionCheckedInEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedInEvent; } }); +Object.defineProperty(exports, "ConnectionCheckedOutEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedOutEvent; } }); +Object.defineProperty(exports, "ConnectionCheckOutFailedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutFailedEvent; } }); +Object.defineProperty(exports, "ConnectionCheckOutStartedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutStartedEvent; } }); +Object.defineProperty(exports, "ConnectionClosedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionClosedEvent; } }); +Object.defineProperty(exports, "ConnectionCreatedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionCreatedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolClearedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClearedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolClosedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClosedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolCreatedEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolCreatedEvent; } }); +Object.defineProperty(exports, "ConnectionPoolMonitoringEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolMonitoringEvent; } }); +Object.defineProperty(exports, "ConnectionPoolReadyEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolReadyEvent; } }); +Object.defineProperty(exports, "ConnectionReadyEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionReadyEvent; } }); +var events_1 = require("./sdam/events"); +Object.defineProperty(exports, "ServerClosedEvent", { enumerable: true, get: function () { return events_1.ServerClosedEvent; } }); +Object.defineProperty(exports, "ServerDescriptionChangedEvent", { enumerable: true, get: function () { return events_1.ServerDescriptionChangedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatFailedEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatFailedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatStartedEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatStartedEvent; } }); +Object.defineProperty(exports, "ServerHeartbeatSucceededEvent", { enumerable: true, get: function () { return events_1.ServerHeartbeatSucceededEvent; } }); +Object.defineProperty(exports, "ServerOpeningEvent", { enumerable: true, get: function () { return events_1.ServerOpeningEvent; } }); +Object.defineProperty(exports, "TopologyClosedEvent", { enumerable: true, get: function () { return events_1.TopologyClosedEvent; } }); +Object.defineProperty(exports, "TopologyDescriptionChangedEvent", { enumerable: true, get: function () { return events_1.TopologyDescriptionChangedEvent; } }); +Object.defineProperty(exports, "TopologyOpeningEvent", { enumerable: true, get: function () { return events_1.TopologyOpeningEvent; } }); +var server_selection_events_1 = require("./sdam/server_selection_events"); +Object.defineProperty(exports, "ServerSelectionEvent", { enumerable: true, get: function () { return server_selection_events_1.ServerSelectionEvent; } }); +Object.defineProperty(exports, "ServerSelectionFailedEvent", { enumerable: true, get: function () { return server_selection_events_1.ServerSelectionFailedEvent; } }); +Object.defineProperty(exports, "ServerSelectionStartedEvent", { enumerable: true, get: function () { return server_selection_events_1.ServerSelectionStartedEvent; } }); +Object.defineProperty(exports, "ServerSelectionSucceededEvent", { enumerable: true, get: function () { return server_selection_events_1.ServerSelectionSucceededEvent; } }); +Object.defineProperty(exports, "WaitingForSuitableServerEvent", { enumerable: true, get: function () { return server_selection_events_1.WaitingForSuitableServerEvent; } }); +var srv_polling_1 = require("./sdam/srv_polling"); +Object.defineProperty(exports, "SrvPollingEvent", { enumerable: true, get: function () { return srv_polling_1.SrvPollingEvent; } }); +var errors_1 = require("./client-side-encryption/errors"); +Object.defineProperty(exports, "MongoCryptAzureKMSRequestError", { enumerable: true, get: function () { return errors_1.MongoCryptAzureKMSRequestError; } }); +Object.defineProperty(exports, "MongoCryptCreateDataKeyError", { enumerable: true, get: function () { return errors_1.MongoCryptCreateDataKeyError; } }); +Object.defineProperty(exports, "MongoCryptCreateEncryptedCollectionError", { enumerable: true, get: function () { return errors_1.MongoCryptCreateEncryptedCollectionError; } }); +Object.defineProperty(exports, "MongoCryptError", { enumerable: true, get: function () { return errors_1.MongoCryptError; } }); +Object.defineProperty(exports, "MongoCryptInvalidArgumentError", { enumerable: true, get: function () { return errors_1.MongoCryptInvalidArgumentError; } }); +Object.defineProperty(exports, "MongoCryptKMSRequestNetworkTimeoutError", { enumerable: true, get: function () { return errors_1.MongoCryptKMSRequestNetworkTimeoutError; } }); +var mongo_client_auth_providers_1 = require("./mongo_client_auth_providers"); +Object.defineProperty(exports, "MongoClientAuthProviders", { enumerable: true, get: function () { return mongo_client_auth_providers_1.MongoClientAuthProviders; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/index.js.map b/nodejs/node_modules/mongodb/lib/index.js.map new file mode 100644 index 00000000..4af3e813 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,mCAAgC;AA8E9B,sFA9EO,aAAK,OA8EP;AA7EP,4CAAsD;AA2FpD,qGA3FO,8BAAoB,OA2FP;AA1FtB,gDAA0D;AA4FxD,uGA5FO,kCAAsB,OA4FP;AA3FxB,mDAA+C;AA8E7C,6FA9EO,4BAAY,OA8EP;AA7Ed,6CAA0C;AA+ExC,2FA/EO,uBAAU,OA+EP;AA9EZ,8DAA0D;AAuExD,+FAvEO,gCAAc,OAuEP;AAtEhB,oEAAgE;AAyE9D,kGAzEO,sCAAiB,OAyEP;AAxEnB,sDAAkD;AA8EhD,2FA9EO,wBAAU,OA8EP;AA7EZ,8EAAyE;AAiFvE,sGAjFO,+CAAqB,OAiFP;AAhFvB,sEAAiE;AAiF/D,kGAjFO,uCAAiB,OAiFP;AA/EnB,6BAA0B;AAyExB,mFAzEO,OAAE,OAyEP;AAxEJ,qCAAwC;AA0EtC,6FA1EO,qBAAY,OA0EP;AAzEd,gDAA2D;AA0EzD,uGA1EO,iCAAsB,OA0EP;AAzExB,4CAA0D;AA0ExD,wGA1EO,gCAAuB,OA0EP;AAzEzB,iDAA6C;AA4E3C,4FA5EO,0BAAW,OA4EP;AA3Eb,+CAAkD;AAgEhD,kGAhEO,+BAAiB,OAgEP;AA/DnB,yCAA2C;AAiEzC,8FAjEO,wBAAa,OAiEP;AA/Df,cAAc;AACd,+BAA8B;AAArB,4FAAA,IAAI,OAAA;AACb,+BAgBgB;AAfd,8FA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,mIAAA,yBAAyB,OAAA;AACzB,oIAAA,0BAA0B,OAAA;AAC1B,uIAAA,6BAA6B,OAAA;AAC7B,kIAAA,wBAAwB,OAAA;AACxB,8HAAA,oBAAoB,OAAA;AAEtB,wCAUuB;AATrB,2GAAA,iBAAiB,OAAA;AACjB,uHAAA,6BAA6B,OAAA;AAC7B,oHAAA,0BAA0B,OAAA;AAC1B,qHAAA,2BAA2B,OAAA;AAC3B,uHAAA,6BAA6B,OAAA;AAC7B,4GAAA,kBAAkB,OAAA;AAClB,6GAAA,mBAAmB,OAAA;AACnB,yHAAA,+BAA+B,OAAA;AAC/B,8GAAA,oBAAoB,OAAA;AAEtB,0EAMwC;AALtC,+HAAA,oBAAoB,OAAA;AACpB,qIAAA,0BAA0B,OAAA;AAC1B,sIAAA,2BAA2B,OAAA;AAC3B,wIAAA,6BAA6B,OAAA;AAC7B,wIAAA,6BAA6B,OAAA;AAE/B,kDAAqD;AAA5C,8GAAA,eAAe,OAAA;AAuExB,0DAOyC;AANvC,wHAAA,8BAA8B,OAAA;AAC9B,sHAAA,4BAA4B,OAAA;AAC5B,kIAAA,wCAAwC,OAAA;AACxC,yGAAA,eAAe,OAAA;AACf,wHAAA,8BAA8B,OAAA;AAC9B,iIAAA,uCAAuC,OAAA;AAsIzC,6EAAyE;AAAhE,uIAAA,wBAAwB,OAAA"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_client.js b/nodejs/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 00000000..208fa373 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,358 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoClient = exports.ServerApiVersion = void 0; +const fs_1 = require("fs"); +const util_1 = require("util"); +const bson_1 = require("./bson"); +const change_stream_1 = require("./change_stream"); +const mongo_credentials_1 = require("./cmap/auth/mongo_credentials"); +const providers_1 = require("./cmap/auth/providers"); +const connection_string_1 = require("./connection_string"); +const constants_1 = require("./constants"); +const db_1 = require("./db"); +const error_1 = require("./error"); +const mongo_client_auth_providers_1 = require("./mongo_client_auth_providers"); +const mongo_logger_1 = require("./mongo_logger"); +const mongo_types_1 = require("./mongo_types"); +const execute_operation_1 = require("./operations/execute_operation"); +const run_command_1 = require("./operations/run_command"); +const read_preference_1 = require("./read_preference"); +const server_selection_1 = require("./sdam/server_selection"); +const topology_1 = require("./sdam/topology"); +const sessions_1 = require("./sessions"); +const utils_1 = require("./utils"); +/** @public */ +exports.ServerApiVersion = Object.freeze({ + v1: '1' +}); +/** @internal */ +const kOptions = Symbol('options'); +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +class MongoClient extends mongo_types_1.TypedEventEmitter { + constructor(url, options) { + super(); + this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options); + const shouldSetLogger = Object.values(this[kOptions].mongoLoggerOptions.componentSeverities).some(value => value !== mongo_logger_1.SeverityLevel.OFF); + this.mongoLogger = shouldSetLogger + ? new mongo_logger_1.MongoLogger(this[kOptions].mongoLoggerOptions) + : undefined; + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + // The internal state + this.s = { + url, + bsonOptions: (0, bson_1.resolveBSONOptions)(this[kOptions]), + namespace: (0, utils_1.ns)('admin'), + hasBeenClosed: false, + sessionPool: new sessions_1.ServerSessionPool(this), + activeSessions: new Set(), + authProviders: new mongo_client_auth_providers_1.MongoClientAuthProviders(), + get options() { + return client[kOptions]; + }, + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get isMongoClient() { + return true; + } + }; + this.checkForNonGenuineHosts(); + } + /** @internal */ + checkForNonGenuineHosts() { + const documentDBHostnames = this[kOptions].hosts.filter((hostAddress) => (0, utils_1.isHostMatch)(utils_1.DOCUMENT_DB_CHECK, hostAddress.host)); + const srvHostIsDocumentDB = (0, utils_1.isHostMatch)(utils_1.DOCUMENT_DB_CHECK, this[kOptions].srvHost); + const cosmosDBHostnames = this[kOptions].hosts.filter((hostAddress) => (0, utils_1.isHostMatch)(utils_1.COSMOS_DB_CHECK, hostAddress.host)); + const srvHostIsCosmosDB = (0, utils_1.isHostMatch)(utils_1.COSMOS_DB_CHECK, this[kOptions].srvHost); + if (documentDBHostnames.length !== 0 || srvHostIsDocumentDB) { + this.mongoLogger?.info('client', utils_1.DOCUMENT_DB_MSG); + } + else if (cosmosDBHostnames.length !== 0 || srvHostIsCosmosDB) { + this.mongoLogger?.info('client', utils_1.COSMOS_DB_MSG); + } + } + /** @see MongoOptions */ + get options() { + return Object.freeze({ ...this[kOptions] }); + } + get serverApi() { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands() { + return this[kOptions].monitorCommands; + } + set monitorCommands(value) { + this[kOptions].monitorCommands = value; + } + /** @internal */ + get autoEncrypter() { + return this[kOptions].autoEncrypter; + } + get readConcern() { + return this.s.readConcern; + } + get writeConcern() { + return this.s.writeConcern; + } + get readPreference() { + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + async connect() { + if (this.connectionLock) { + return this.connectionLock; + } + try { + this.connectionLock = this._connect(); + await this.connectionLock; + } + finally { + // release + this.connectionLock = undefined; + } + return this; + } + /** + * Create a topology to open the connection, must be locked to avoid topology leaks in concurrency scenario. + * Locking is enforced by the connect method. + * + * @internal + */ + async _connect() { + if (this.topology && this.topology.isConnected()) { + return this; + } + const options = this[kOptions]; + if (options.tls) { + if (typeof options.tlsCAFile === 'string') { + options.ca ??= await fs_1.promises.readFile(options.tlsCAFile); + } + if (typeof options.tlsCRLFile === 'string') { + options.crl ??= await fs_1.promises.readFile(options.tlsCRLFile); + } + if (typeof options.tlsCertificateKeyFile === 'string') { + if (!options.key || !options.cert) { + const contents = await fs_1.promises.readFile(options.tlsCertificateKeyFile); + options.key ??= contents; + options.cert ??= contents; + } + } + } + if (typeof options.srvHost === 'string') { + const hosts = await (0, connection_string_1.resolveSRVRecord)(options); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + } + // It is important to perform validation of hosts AFTER SRV resolution, to check the real hostname, + // but BEFORE we even attempt connecting with a potentially not allowed hostname + if (options.credentials?.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) { + const allowedHosts = options.credentials?.mechanismProperties?.ALLOWED_HOSTS || mongo_credentials_1.DEFAULT_ALLOWED_HOSTS; + const isServiceAuth = !!options.credentials?.mechanismProperties?.PROVIDER_NAME; + if (!isServiceAuth) { + for (const host of options.hosts) { + if (!(0, utils_1.hostMatchesWildcards)(host.toHostPort().host, allowedHosts)) { + throw new error_1.MongoInvalidArgumentError(`Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(',')}'`); + } + } + } + } + this.topology = new topology_1.Topology(this, options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + this.topology.once(topology_1.Topology.OPEN, () => this.emit('open', this)); + for (const event of constants_1.MONGO_CLIENT_EVENTS) { + this.topology.on(event, (...args) => this.emit(event, ...args)); + } + const topologyConnect = async () => { + try { + await (0, util_1.promisify)(callback => this.topology?.connect(options, callback))(); + } + catch (error) { + this.topology?.close(); + throw error; + } + }; + if (this.autoEncrypter) { + await this.autoEncrypter?.init(); + await topologyConnect(); + await options.encrypter.connectInternalClient(); + } + else { + await topologyConnect(); + } + return this; + } + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + async close(force = false) { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + await Promise.all(activeSessionEnds); + if (this.topology == null) { + return; + } + // If we would attempt to select a server and get nothing back we short circuit + // to avoid the server selection timeout. + const selector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred); + const topologyDescription = this.topology.description; + const serverDescriptions = Array.from(topologyDescription.servers.values()); + const servers = selector(topologyDescription, serverDescriptions); + if (servers.length !== 0) { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length !== 0) { + await (0, execute_operation_1.executeOperation)(this, new run_command_1.RunAdminCommandOperation({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true })).catch(() => null); // outcome does not matter; + } + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + topology.close(); + const { encrypter } = this[kOptions]; + if (encrypter) { + await encrypter.close(this, force); + } + } + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName, options) { + options = options ?? {}; + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; + } + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + // Return the db object + const db = new db_1.Db(this, dbName, finalOptions); + // Return the database + return db; + } + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @see https://www.mongodb.com/docs/manual/reference/connection-string/ + */ + static async connect(url, options) { + const client = new this(url, options); + return client.connect(); + } + /** + * Creates a new ClientSession. When using the returned session in an operation + * a corresponding ServerSession will be created. + * + * @remarks + * A ClientSession instance may only be passed to operations being performed on the same + * MongoClient it was started from. + */ + startSession(options) { + const session = new sessions_1.ClientSession(this, this.s.sessionPool, { explicit: true, ...options }, this[kOptions]); + this.s.activeSessions.add(session); + session.once('ended', () => { + this.s.activeSessions.delete(session); + }); + return session; + } + async withSession(optionsOrExecutor, executor) { + const options = { + // Always define an owner + owner: Symbol(), + // If it's an object inherit the options + ...(typeof optionsOrExecutor === 'object' ? optionsOrExecutor : {}) + }; + const withSessionCallback = typeof optionsOrExecutor === 'function' ? optionsOrExecutor : executor; + if (withSessionCallback == null) { + throw new error_1.MongoInvalidArgumentError('Missing required callback parameter'); + } + const session = this.startSession(options); + try { + return await withSessionCallback(session); + } + finally { + try { + await session.endSession(); + } + catch { + // We are not concerned with errors from endSession() + } + } + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to provide the schema that may be defined for all the data within the current cluster + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } +} +exports.MongoClient = MongoClient; +//# sourceMappingURL=mongo_client.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_client.js.map b/nodejs/node_modules/mongodb/lib/mongo_client.js.map new file mode 100644 index 00000000..e6a8be18 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_client.js","sourceRoot":"","sources":["../src/mongo_client.ts"],"names":[],"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yBAAyB;YACzB,KAAK,EAAE,MAAM,EAAE;YACf,wCAAwC;YACxC,GAAG,CAAC,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,CAAC;SACpE,CAAC;QAEF,MAAM,mBAAmB,GACvB,OAAO,iBAAiB,KAAK,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,QAAQ,CAAC;QAEzE,IAAI,mBAAmB,IAAI,IAAI,EAAE;YAC/B,MAAM,IAAI,iCAAyB,CAAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QAE3C,IAAI;YACF,OAAO,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;SAC3C;gBAAS;YACR,IAAI;gBACF,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;aAC5B;YAAC,MAAM;gBACN,qDAAqD;aACtD;SACF;IACH,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAGH,WAAuB,EAAE,EAAE,UAA+B,EAAE;QAC5D,6CAA6C;QAC7C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC5B,OAAO,GAAG,QAAQ,CAAC;YACnB,QAAQ,GAAG,EAAE,CAAC;SACf;QAED,OAAO,IAAI,4BAAY,CAAmB,IAAI,EAAE,QAAQ,EAAE,IAAA,sBAAc,EAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3F,CAAC;CACF;AAxZD,kCAwZC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_client_auth_providers.js b/nodejs/node_modules/mongodb/lib/mongo_client_auth_providers.js new file mode 100644 index 00000000..56b5a4f3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_client_auth_providers.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoClientAuthProviders = void 0; +const gssapi_1 = require("./cmap/auth/gssapi"); +const mongocr_1 = require("./cmap/auth/mongocr"); +const mongodb_aws_1 = require("./cmap/auth/mongodb_aws"); +const mongodb_oidc_1 = require("./cmap/auth/mongodb_oidc"); +const plain_1 = require("./cmap/auth/plain"); +const providers_1 = require("./cmap/auth/providers"); +const scram_1 = require("./cmap/auth/scram"); +const x509_1 = require("./cmap/auth/x509"); +const error_1 = require("./error"); +/** @internal */ +const AUTH_PROVIDERS = new Map([ + [providers_1.AuthMechanism.MONGODB_AWS, () => new mongodb_aws_1.MongoDBAWS()], + [providers_1.AuthMechanism.MONGODB_CR, () => new mongocr_1.MongoCR()], + [providers_1.AuthMechanism.MONGODB_GSSAPI, () => new gssapi_1.GSSAPI()], + [providers_1.AuthMechanism.MONGODB_OIDC, () => new mongodb_oidc_1.MongoDBOIDC()], + [providers_1.AuthMechanism.MONGODB_PLAIN, () => new plain_1.Plain()], + [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, () => new scram_1.ScramSHA1()], + [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, () => new scram_1.ScramSHA256()], + [providers_1.AuthMechanism.MONGODB_X509, () => new x509_1.X509()] +]); +/** + * Create a set of providers per client + * to avoid sharing the provider's cache between different clients. + * @internal + */ +class MongoClientAuthProviders { + constructor() { + this.existingProviders = new Map(); + } + /** + * Get or create an authentication provider based on the provided mechanism. + * We don't want to create all providers at once, as some providers may not be used. + * @param name - The name of the provider to get or create. + * @returns The provider. + * @throws MongoInvalidArgumentError if the mechanism is not supported. + * @internal + */ + getOrCreateProvider(name) { + const authProvider = this.existingProviders.get(name); + if (authProvider) { + return authProvider; + } + const provider = AUTH_PROVIDERS.get(name)?.(); + if (!provider) { + throw new error_1.MongoInvalidArgumentError(`authMechanism ${name} not supported`); + } + this.existingProviders.set(name, provider); + return provider; + } +} +exports.MongoClientAuthProviders = MongoClientAuthProviders; +//# sourceMappingURL=mongo_client_auth_providers.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_client_auth_providers.js.map b/nodejs/node_modules/mongodb/lib/mongo_client_auth_providers.js.map new file mode 100644 index 00000000..556865f0 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_client_auth_providers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_client_auth_providers.js","sourceRoot":"","sources":["../src/mongo_client_auth_providers.ts"],"names":[],"mappings":";;;AACA,+CAA4C;AAC5C,iDAA8C;AAC9C,yDAAqD;AACrD,2DAAuD;AACvD,6CAA0C;AAC1C,qDAAsD;AACtD,6CAA2D;AAC3D,2CAAwC;AACxC,mCAAoD;AAEpD,gBAAgB;AAChB,MAAM,cAAc,GAAG,IAAI,GAAG,CAA6C;IACzE,CAAC,yBAAa,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI,wBAAU,EAAE,CAAC;IACnD,CAAC,yBAAa,CAAC,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI,iBAAO,EAAE,CAAC;IAC/C,CAAC,yBAAa,CAAC,cAAc,EAAE,GAAG,EAAE,CAAC,IAAI,eAAM,EAAE,CAAC;IAClD,CAAC,yBAAa,CAAC,YAAY,EAAE,GAAG,EAAE,CAAC,IAAI,0BAAW,EAAE,CAAC;IACrD,CAAC,yBAAa,CAAC,aAAa,EAAE,GAAG,EAAE,CAAC,IAAI,aAAK,EAAE,CAAC;IAChD,CAAC,yBAAa,CAAC,kBAAkB,EAAE,GAAG,EAAE,CAAC,IAAI,iBAAS,EAAE,CAAC;IACzD,CAAC,yBAAa,CAAC,oBAAoB,EAAE,GAAG,EAAE,CAAC,IAAI,mBAAW,EAAE,CAAC;IAC7D,CAAC,yBAAa,CAAC,YAAY,EAAE,GAAG,EAAE,CAAC,IAAI,WAAI,EAAE,CAAC;CAC/C,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAa,wBAAwB;IAArC;QACU,sBAAiB,GAA8C,IAAI,GAAG,EAAE,CAAC;IAwBnF,CAAC;IAtBC;;;;;;;OAOG;IACH,mBAAmB,CAAC,IAA4B;QAC9C,MAAM,YAAY,GAAG,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtD,IAAI,YAAY,EAAE;YAChB,OAAO,YAAY,CAAC;SACrB;QAED,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;QAC9C,IAAI,CAAC,QAAQ,EAAE;YACb,MAAM,IAAI,iCAAyB,CAAC,iBAAiB,IAAI,gBAAgB,CAAC,CAAC;SAC5E;QAED,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC3C,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF;AAzBD,4DAyBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_logger.js b/nodejs/node_modules/mongodb/lib/mongo_logger.js new file mode 100644 index 00000000..84969f47 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_logger.js @@ -0,0 +1,548 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoLogger = exports.defaultLogTransform = exports.stringifyWithMaxLen = exports.createStdioLogger = exports.parseSeverityFromString = exports.MongoLoggableComponent = exports.SEVERITY_LEVEL_MAP = exports.DEFAULT_MAX_DOCUMENT_LENGTH = exports.SeverityLevel = void 0; +const util_1 = require("util"); +const bson_1 = require("./bson"); +const constants_1 = require("./constants"); +const utils_1 = require("./utils"); +/** @internal */ +exports.SeverityLevel = Object.freeze({ + EMERGENCY: 'emergency', + ALERT: 'alert', + CRITICAL: 'critical', + ERROR: 'error', + WARNING: 'warn', + NOTICE: 'notice', + INFORMATIONAL: 'info', + DEBUG: 'debug', + TRACE: 'trace', + OFF: 'off' +}); +/** @internal */ +exports.DEFAULT_MAX_DOCUMENT_LENGTH = 1000; +/** @internal */ +class SeverityLevelMap extends Map { + constructor(entries) { + const newEntries = []; + for (const [level, value] of entries) { + newEntries.push([value, level]); + } + newEntries.push(...entries); + super(newEntries); + } + getNumericSeverityLevel(severity) { + return this.get(severity); + } + getSeverityLevelName(level) { + return this.get(level); + } +} +/** @internal */ +exports.SEVERITY_LEVEL_MAP = new SeverityLevelMap([ + [exports.SeverityLevel.OFF, -Infinity], + [exports.SeverityLevel.EMERGENCY, 0], + [exports.SeverityLevel.ALERT, 1], + [exports.SeverityLevel.CRITICAL, 2], + [exports.SeverityLevel.ERROR, 3], + [exports.SeverityLevel.WARNING, 4], + [exports.SeverityLevel.NOTICE, 5], + [exports.SeverityLevel.INFORMATIONAL, 6], + [exports.SeverityLevel.DEBUG, 7], + [exports.SeverityLevel.TRACE, 8] +]); +/** @internal */ +exports.MongoLoggableComponent = Object.freeze({ + COMMAND: 'command', + TOPOLOGY: 'topology', + SERVER_SELECTION: 'serverSelection', + CONNECTION: 'connection', + CLIENT: 'client' +}); +/** + * Parses a string as one of SeverityLevel + * @internal + * + * @param s - the value to be parsed + * @returns one of SeverityLevel if value can be parsed as such, otherwise null + */ +function parseSeverityFromString(s) { + const validSeverities = Object.values(exports.SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity; + } + return null; +} +exports.parseSeverityFromString = parseSeverityFromString; +/** @internal */ +function createStdioLogger(stream) { + return { + write: (0, util_1.promisify)((log, cb) => { + const logLine = (0, util_1.inspect)(log, { compact: true, breakLength: Infinity }); + stream.write(`${logLine}\n`, 'utf-8', cb); + return; + }) + }; +} +exports.createStdioLogger = createStdioLogger; +/** + * resolves the MONGODB_LOG_PATH and mongodbLogPath options from the environment and the + * mongo client options respectively. The mongodbLogPath can be either 'stdout', 'stderr', a NodeJS + * Writable or an object which has a `write` method with the signature: + * ```ts + * write(log: Log): void + * ``` + * + * @returns the MongoDBLogWritable object to write logs to + */ +function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) { + if (typeof mongodbLogPath === 'string' && /^stderr$/i.test(mongodbLogPath)) { + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; + } + if (typeof mongodbLogPath === 'string' && /^stdout$/i.test(mongodbLogPath)) { + return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; + } + if (typeof mongodbLogPath === 'object' && typeof mongodbLogPath?.write === 'function') { + return { mongodbLogPath: mongodbLogPath, mongodbLogPathIsStdErr: false }; + } + if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) { + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; + } + if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) { + return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; + } + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; +} +function resolveSeverityConfiguration(clientOption, environmentOption, defaultSeverity) { + return (parseSeverityFromString(clientOption) ?? + parseSeverityFromString(environmentOption) ?? + defaultSeverity); +} +function compareSeverity(s0, s1) { + const s0Num = exports.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0); + const s1Num = exports.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1); + return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0; +} +/** @internal */ +function stringifyWithMaxLen(value, maxDocumentLength, options = {}) { + let strToTruncate = ''; + if (typeof value === 'string') { + strToTruncate = value; + } + else if (typeof value === 'function') { + strToTruncate = value.name; + } + else { + try { + strToTruncate = bson_1.EJSON.stringify(value, options); + } + catch (e) { + strToTruncate = `Extended JSON serialization failed with: ${e.message}`; + } + } + // handle truncation that occurs in the middle of multi-byte codepoints + if (maxDocumentLength !== 0 && + strToTruncate.length > maxDocumentLength && + strToTruncate.charCodeAt(maxDocumentLength - 1) !== + strToTruncate.codePointAt(maxDocumentLength - 1)) { + maxDocumentLength--; + if (maxDocumentLength === 0) { + return ''; + } + } + return maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength + ? `${strToTruncate.slice(0, maxDocumentLength)}...` + : strToTruncate; +} +exports.stringifyWithMaxLen = stringifyWithMaxLen; +function isLogConvertible(obj) { + const objAsLogConvertible = obj; + // eslint-disable-next-line no-restricted-syntax + return objAsLogConvertible.toLog !== undefined && typeof objAsLogConvertible.toLog === 'function'; +} +function attachServerSelectionFields(log, serverSelectionEvent, maxDocumentLength = exports.DEFAULT_MAX_DOCUMENT_LENGTH) { + const { selector, operation, topologyDescription, message } = serverSelectionEvent; + log.selector = stringifyWithMaxLen(selector, maxDocumentLength); + log.operation = operation; + log.topologyDescription = stringifyWithMaxLen(topologyDescription, maxDocumentLength); + log.message = message; + return log; +} +function attachCommandFields(log, commandEvent) { + log.commandName = commandEvent.commandName; + log.requestId = commandEvent.requestId; + log.driverConnectionId = commandEvent.connectionId; + const { host, port } = utils_1.HostAddress.fromString(commandEvent.address).toHostPort(); + log.serverHost = host; + log.serverPort = port; + if (commandEvent?.serviceId) { + log.serviceId = commandEvent.serviceId.toHexString(); + } + log.databaseName = commandEvent.databaseName; + log.serverConnectionId = commandEvent.serverConnectionId; + return log; +} +function attachConnectionFields(log, event) { + const { host, port } = utils_1.HostAddress.fromString(event.address).toHostPort(); + log.serverHost = host; + log.serverPort = port; + return log; +} +function attachSDAMFields(log, sdamEvent) { + log.topologyId = sdamEvent.topologyId; + return log; +} +function attachServerHeartbeatFields(log, serverHeartbeatEvent) { + const { awaited, connectionId } = serverHeartbeatEvent; + log.awaited = awaited; + log.driverConnectionId = serverHeartbeatEvent.connectionId; + const { host, port } = utils_1.HostAddress.fromString(connectionId).toHostPort(); + log.serverHost = host; + log.serverPort = port; + return log; +} +/** @internal */ +function defaultLogTransform(logObject, maxDocumentLength = exports.DEFAULT_MAX_DOCUMENT_LENGTH) { + let log = Object.create(null); + switch (logObject.name) { + case constants_1.SERVER_SELECTION_STARTED: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + return log; + case constants_1.SERVER_SELECTION_FAILED: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + log.failure = logObject.failure?.message; + return log; + case constants_1.SERVER_SELECTION_SUCCEEDED: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + log.serverHost = logObject.serverHost; + log.serverPort = logObject.serverPort; + return log; + case constants_1.WAITING_FOR_SUITABLE_SERVER: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + log.remainingTimeMS = logObject.remainingTimeMS; + return log; + case constants_1.COMMAND_STARTED: + log = attachCommandFields(log, logObject); + log.message = 'Command started'; + log.command = stringifyWithMaxLen(logObject.command, maxDocumentLength, { relaxed: true }); + log.databaseName = logObject.databaseName; + return log; + case constants_1.COMMAND_SUCCEEDED: + log = attachCommandFields(log, logObject); + log.message = 'Command succeeded'; + log.durationMS = logObject.duration; + log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); + return log; + case constants_1.COMMAND_FAILED: + log = attachCommandFields(log, logObject); + log.message = 'Command failed'; + log.durationMS = logObject.duration; + log.failure = logObject.failure?.message ?? '(redacted)'; + return log; + case constants_1.CONNECTION_POOL_CREATED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool created'; + if (logObject.options) { + const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = logObject.options; + log = { + ...log, + maxIdleTimeMS, + minPoolSize, + maxPoolSize, + maxConnecting, + waitQueueTimeoutMS + }; + } + return log; + case constants_1.CONNECTION_POOL_READY: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool ready'; + return log; + case constants_1.CONNECTION_POOL_CLEARED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool cleared'; + if (logObject.serviceId?._bsontype === 'ObjectId') { + log.serviceId = logObject.serviceId?.toHexString(); + } + return log; + case constants_1.CONNECTION_POOL_CLOSED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool closed'; + return log; + case constants_1.CONNECTION_CREATED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection created'; + log.driverConnectionId = logObject.connectionId; + return log; + case constants_1.CONNECTION_READY: + log = attachConnectionFields(log, logObject); + log.message = 'Connection ready'; + log.driverConnectionId = logObject.connectionId; + return log; + case constants_1.CONNECTION_CLOSED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection closed'; + log.driverConnectionId = logObject.connectionId; + switch (logObject.reason) { + case 'stale': + log.reason = 'Connection became stale because the pool was cleared'; + break; + case 'idle': + log.reason = + 'Connection has been available but unused for longer than the configured max idle time'; + break; + case 'error': + log.reason = 'An error occurred while using the connection'; + if (logObject.error) { + log.error = logObject.error; + } + break; + case 'poolClosed': + log.reason = 'Connection pool was closed'; + break; + default: + log.reason = `Unknown close reason: ${logObject.reason}`; + } + return log; + case constants_1.CONNECTION_CHECK_OUT_STARTED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checkout started'; + return log; + case constants_1.CONNECTION_CHECK_OUT_FAILED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checkout failed'; + switch (logObject.reason) { + case 'poolClosed': + log.reason = 'Connection pool was closed'; + break; + case 'timeout': + log.reason = 'Wait queue timeout elapsed without a connection becoming available'; + break; + case 'connectionError': + log.reason = 'An error occurred while trying to establish a new connection'; + if (logObject.error) { + log.error = logObject.error; + } + break; + default: + log.reason = `Unknown close reason: ${logObject.reason}`; + } + return log; + case constants_1.CONNECTION_CHECKED_OUT: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checked out'; + log.driverConnectionId = logObject.connectionId; + return log; + case constants_1.CONNECTION_CHECKED_IN: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checked in'; + log.driverConnectionId = logObject.connectionId; + return log; + case constants_1.SERVER_OPENING: + log = attachSDAMFields(log, logObject); + log = attachConnectionFields(log, logObject); + log.message = 'Starting server monitoring'; + return log; + case constants_1.SERVER_CLOSED: + log = attachSDAMFields(log, logObject); + log = attachConnectionFields(log, logObject); + log.message = 'Stopped server monitoring'; + return log; + case constants_1.SERVER_HEARTBEAT_STARTED: + log = attachSDAMFields(log, logObject); + log = attachServerHeartbeatFields(log, logObject); + log.message = 'Server heartbeat started'; + return log; + case constants_1.SERVER_HEARTBEAT_SUCCEEDED: + log = attachSDAMFields(log, logObject); + log = attachServerHeartbeatFields(log, logObject); + log.message = 'Server heartbeat succeeded'; + log.durationMS = logObject.duration; + log.serverConnectionId = logObject.serverConnectionId; + log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); + return log; + case constants_1.SERVER_HEARTBEAT_FAILED: + log = attachSDAMFields(log, logObject); + log = attachServerHeartbeatFields(log, logObject); + log.message = 'Server heartbeat failed'; + log.durationMS = logObject.duration; + log.failure = logObject.failure?.message; + return log; + case constants_1.TOPOLOGY_OPENING: + log = attachSDAMFields(log, logObject); + log.message = 'Starting topology monitoring'; + return log; + case constants_1.TOPOLOGY_CLOSED: + log = attachSDAMFields(log, logObject); + log.message = 'Stopped topology monitoring'; + return log; + case constants_1.TOPOLOGY_DESCRIPTION_CHANGED: + log = attachSDAMFields(log, logObject); + log.message = 'Topology description changed'; + log.previousDescription = log.reply = stringifyWithMaxLen(logObject.previousDescription, maxDocumentLength); + log.newDescription = log.reply = stringifyWithMaxLen(logObject.newDescription, maxDocumentLength); + return log; + default: + for (const [key, value] of Object.entries(logObject)) { + if (value != null) + log[key] = value; + } + } + return log; +} +exports.defaultLogTransform = defaultLogTransform; +/** @internal */ +class MongoLogger { + constructor(options) { + this.pendingLog = null; + /** + * This method should be used when logging errors that do not have a public driver API for + * reporting errors. + */ + this.error = this.log.bind(this, 'error'); + /** + * This method should be used to log situations where undesirable application behaviour might + * occur. For example, failing to end sessions on `MongoClient.close`. + */ + this.warn = this.log.bind(this, 'warn'); + /** + * This method should be used to report high-level information about normal driver behaviour. + * For example, the creation of a `MongoClient`. + */ + this.info = this.log.bind(this, 'info'); + /** + * This method should be used to report information that would be helpful when debugging an + * application. For example, a command starting, succeeding or failing. + */ + this.debug = this.log.bind(this, 'debug'); + /** + * This method should be used to report fine-grained details related to logic flow. For example, + * entering and exiting a function body. + */ + this.trace = this.log.bind(this, 'trace'); + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + this.logDestinationIsStdErr = options.logDestinationIsStdErr; + this.severities = this.createLoggingSeverities(); + } + createLoggingSeverities() { + const severities = Object(); + for (const component of Object.values(exports.MongoLoggableComponent)) { + severities[component] = {}; + for (const severityLevel of Object.values(exports.SeverityLevel)) { + severities[component][severityLevel] = + compareSeverity(severityLevel, this.componentSeverities[component]) <= 0; + } + } + return severities; + } + turnOffSeverities() { + for (const component of Object.values(exports.MongoLoggableComponent)) { + this.componentSeverities[component] = exports.SeverityLevel.OFF; + for (const severityLevel of Object.values(exports.SeverityLevel)) { + this.severities[component][severityLevel] = false; + } + } + } + logWriteFailureHandler(error) { + if (this.logDestinationIsStdErr) { + this.turnOffSeverities(); + this.clearPendingLog(); + return; + } + this.logDestination = createStdioLogger(process.stderr); + this.logDestinationIsStdErr = true; + this.clearPendingLog(); + this.error(exports.MongoLoggableComponent.CLIENT, { + toLog: function () { + return { + message: 'User input for mongodbLogPath is now invalid. Logging is halted.', + error: error.message + }; + } + }); + this.turnOffSeverities(); + this.clearPendingLog(); + } + clearPendingLog() { + this.pendingLog = null; + } + willLog(component, severity) { + if (severity === exports.SeverityLevel.OFF) + return false; + return this.severities[component][severity]; + } + log(severity, component, message) { + if (!this.willLog(component, severity)) + return; + let logMessage = { t: new Date(), c: component, s: severity }; + if (typeof message === 'string') { + logMessage.message = message; + } + else if (typeof message === 'object') { + if (isLogConvertible(message)) { + logMessage = { ...logMessage, ...message.toLog() }; + } + else { + logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) }; + } + } + if ((0, utils_1.isPromiseLike)(this.pendingLog)) { + this.pendingLog = this.pendingLog + .then(() => this.logDestination.write(logMessage)) + .then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); + return; + } + try { + const logResult = this.logDestination.write(logMessage); + if ((0, utils_1.isPromiseLike)(logResult)) { + this.pendingLog = logResult.then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); + } + } + catch (error) { + this.logWriteFailureHandler(error); + } + } + /** + * Merges options set through environment variables and the MongoClient, preferring environment + * variables when both are set, and substituting defaults for values not set. Options set in + * constructor take precedence over both environment variables and MongoClient options. + * + * @remarks + * When parsing component severity levels, invalid values are treated as unset and replaced with + * the default severity. + * + * @param envOptions - options set for the logger from the environment + * @param clientOptions - options set for the logger in the MongoClient options + * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger + */ + static resolveOptions(envOptions, clientOptions) { + // client options take precedence over env options + const resolvedLogPath = resolveLogPath(envOptions, clientOptions); + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolvedLogPath.mongodbLogPath, + mongodbLogPathIsStdErr: resolvedLogPath.mongodbLogPathIsStdErr + }; + const defaultSeverity = resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.default, combinedOptions.MONGODB_LOG_ALL, exports.SeverityLevel.OFF); + return { + componentSeverities: { + command: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.command, combinedOptions.MONGODB_LOG_COMMAND, defaultSeverity), + topology: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.topology, combinedOptions.MONGODB_LOG_TOPOLOGY, defaultSeverity), + serverSelection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.serverSelection, combinedOptions.MONGODB_LOG_SERVER_SELECTION, defaultSeverity), + connection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.connection, combinedOptions.MONGODB_LOG_CONNECTION, defaultSeverity), + client: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.client, combinedOptions.MONGODB_LOG_CLIENT, defaultSeverity), + default: defaultSeverity + }, + maxDocumentLength: combinedOptions.mongodbLogMaxDocumentLength ?? + (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? + 1000, + logDestination: combinedOptions.mongodbLogPath, + logDestinationIsStdErr: combinedOptions.mongodbLogPathIsStdErr + }; + } +} +exports.MongoLogger = MongoLogger; +//# sourceMappingURL=mongo_logger.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_logger.js.map b/nodejs/node_modules/mongodb/lib/mongo_logger.js.map new file mode 100644 index 00000000..9e1c2ae5 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_logger.js","sourceRoot":"","sources":["../src/mongo_logger.ts"],"names":[],"mappings":";;;AAAA,+BAA0C;AAE1C,iCAAgF;AAehF,2CA2BqB;AAerB,mCAA2E;AAE3E,gBAAgB;AACH,QAAA,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,SAAS,EAAE,WAAW;IACtB,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,OAAO;IACd,OAAO,EAAE,MAAM;IACf,MAAM,EAAE,QAAQ;IAChB,aAAa,EAAE,MAAM;IACrB,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,GAAG,EAAE,KAAK;CACF,CAAC,CAAC;AAEZ,gBAAgB;AACH,QAAA,2BAA2B,GAAG,IAAI,CAAC;AAIhD,gBAAgB;AAChB,MAAM,gBAAiB,SAAQ,GAAmD;IAChF,YAAY,OAA2D;QACrE,MAAM,UAAU,GAAuD,EAAE,CAAC;QAC1E,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE;YACpC,UAAU,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;SACjC;QAED,UAAU,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC;QAC5B,KAAK,CAAC,UAAU,CAAC,CAAC;IACpB,CAAC;IAED,uBAAuB,CAAC,QAAuB;QAC7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;YACL,mBAAmB,EAAE;gBACnB,OAAO,EAAE,4BAA4B,CACnC,eAAe,CAAC,6BAA6B,EAAE,OAAO,EACtD,eAAe,CAAC,mBAAmB,EACnC,eAAe,CAChB;gBACD,QAAQ,EAAE,4BAA4B,CACpC,eAAe,CAAC,6BAA6B,EAAE,QAAQ,EACvD,eAAe,CAAC,oBAAoB,EACpC,eAAe,CAChB;gBACD,eAAe,EAAE,4BAA4B,CAC3C,eAAe,CAAC,6BAA6B,EAAE,eAAe,EAC9D,eAAe,CAAC,4BAA4B,EAC5C,eAAe,CAChB;gBACD,UAAU,EAAE,4BAA4B,CACtC,eAAe,CAAC,6BAA6B,EAAE,UAAU,EACzD,eAAe,CAAC,sBAAsB,EACtC,eAAe,CAChB;gBACD,MAAM,EAAE,4BAA4B,CAClC,eAAe,CAAC,6BAA6B,EAAE,MAAM,EACrD,eAAe,CAAC,kBAAkB,EAClC,eAAe,CAChB;gBACD,OAAO,EAAE,eAAe;aACzB;YACD,iBAAiB,EACf,eAAe,CAAC,2BAA2B;gBAC3C,IAAA,4BAAoB,EAAC,eAAe,CAAC,+BAA+B,CAAC;gBACrE,IAAI;YACN,cAAc,EAAE,eAAe,CAAC,cAAc;YAC9C,sBAAsB,EAAE,eAAe,CAAC,sBAAsB;SAC/D,CAAC;IACJ,CAAC;CACF;AAvMD,kCAuMC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_types.js b/nodejs/node_modules/mongodb/lib/mongo_types.js new file mode 100644 index 00000000..bc4fefd6 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_types.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancellationToken = exports.TypedEventEmitter = void 0; +const events_1 = require("events"); +const mongo_logger_1 = require("./mongo_logger"); +/** + * Typescript type safe event emitter + * @public + */ +class TypedEventEmitter extends events_1.EventEmitter { + /** @internal */ + emitAndLog(event, ...args) { + this.emit(event, ...args); + if (this.component) + this.mongoLogger?.debug(this.component, args[0]); + } + /** @internal */ + emitAndLogHeartbeat(event, topologyId, serverConnectionId, ...args) { + this.emit(event, ...args); + if (this.component) { + const loggableHeartbeatEvent = { + topologyId: topologyId, + serverConnectionId: serverConnectionId ?? null, + ...args[0] + }; + this.mongoLogger?.debug(this.component, loggableHeartbeatEvent); + } + } + /** @internal */ + emitAndLogCommand(monitorCommands, event, databaseName, connectionEstablished, ...args) { + if (monitorCommands) { + this.emit(event, ...args); + } + if (connectionEstablished) { + const loggableCommandEvent = { + databaseName: databaseName, + ...args[0] + }; + this.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.COMMAND, loggableCommandEvent); + } + } +} +exports.TypedEventEmitter = TypedEventEmitter; +/** @public */ +class CancellationToken extends TypedEventEmitter { +} +exports.CancellationToken = CancellationToken; +//# sourceMappingURL=mongo_types.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/mongo_types.js.map b/nodejs/node_modules/mongodb/lib/mongo_types.js.map new file mode 100644 index 00000000..ac976cc3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/mongo_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_types.js","sourceRoot":"","sources":["../src/mongo_types.ts"],"names":[],"mappings":";;;AACA,mCAAsC;AActC,iDAQwB;AAkYxB;;;GAGG;AAEH,MAAa,iBAAoD,SAAQ,qBAAY;IAKnF,gBAAgB;IAChB,UAAU,CACR,KAAwB,EACxB,GAAG,IAAkC;QAErC,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;QAC1B,IAAI,IAAI,CAAC,SAAS;YAAE,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IACvE,CAAC;IACD,gBAAgB;IAChB,mBAAmB,CACjB,KAAwB,EACxB,UAAkB,EAClB,kBAAyC,EACzC,GAAG,IAAkC;QAErC,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;QAC1B,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,MAAM,sBAAsB,GAGc;gBACxC,UAAU,EAAE,UAAU;gBACtB,kBAAkB,EAAE,kBAAkB,IAAI,IAAI;gBAC9C,GAAG,IAAI,CAAC,CAAC,CAAC;aACX,CAAC;YACF,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,sBAAsB,CAAC,CAAC;SACjE;IACH,CAAC;IACD,gBAAgB;IAChB,iBAAiB,CACf,eAAwB,EACxB,KAAwB,EACxB,YAAoB,EACpB,qBAA8B,EAC9B,GAAG,IAAkC;QAErC,IAAI,eAAe,EAAE;YACnB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;SAC3B;QACD,IAAI,qBAAqB,EAAE;YACzB,MAAM,oBAAoB,GAGU;gBAClC,YAAY,EAAE,YAAY;gBAC1B,GAAG,IAAI,CAAC,CAAC,CAAC;aACX,CAAC;YACF,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,qCAAsB,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;SAC/E;IACH,CAAC;CACF;AAvDD,8CAuDC;AAED,cAAc;AACd,MAAa,iBAAkB,SAAQ,iBAAqC;CAAG;AAA/E,8CAA+E"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/aggregate.js b/nodejs/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 00000000..a7cca3ca --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,95 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +exports.DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; +/** @internal */ +class AggregateOperation extends command_1.CommandOperation { + constructor(ns, pipeline, options) { + super(undefined, { ...options, dbName: ns.db }); + this.options = { ...options }; + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || exports.DB_AGGREGATE_COLLECTION; + this.pipeline = pipeline; + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options?.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } + else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + if (this.hasWriteStage) { + this.trySecondaryWrite = true; + } + else { + delete this.options.writeConcern; + } + if (this.explain && this.writeConcern) { + throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); + } + if (options?.cursor != null && typeof options.cursor !== 'object') { + throw new error_1.MongoInvalidArgumentError('Cursor options must be an object'); + } + } + get commandName() { + return 'aggregate'; + } + get canRetryRead() { + return !this.hasWriteStage; + } + addToPipeline(stage) { + this.pipeline.push(stage); + } + async execute(server, session) { + const options = this.options; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; + } + if (this.hasWriteStage && this.writeConcern) { + write_concern_1.WriteConcern.apply(command, this.writeConcern); + } + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + if (options.hint) { + command.hint = options.hint; + } + if (options.let) { + command.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + return super.executeCommand(server, session, command); + } +} +exports.AggregateOperation = AggregateOperation; +(0, operation_1.defineAspects)(AggregateOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=aggregate.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/aggregate.js.map b/nodejs/node_modules/mongodb/lib/operations/aggregate.js.map new file mode 100644 index 00000000..b5dad607 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/aggregate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregate.js","sourceRoot":"","sources":["../../src/operations/aggregate.ts"],"names":[],"mappings":";;;AACA,oCAAqD;AAIrD,oCAAiE;AACjE,oDAAgD;AAChD,uCAAkG;AAClG,2CAA+D;AAE/D,gBAAgB;AACH,QAAA,uBAAuB,GAAG,CAAU,CAAC;AAClD,MAAM,0CAA0C,GAAG,CAAU,CAAC;AA0B9D,gBAAgB;AAChB,MAAa,kBAAiC,SAAQ,0BAAmB;IAMvE,YAAY,EAAoB,EAAE,QAAoB,EAAE,OAA0B;QAChF,KAAK,CAAC,SAAS,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAEhD,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAE9B,gGAAgG;QAChG,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC,UAAU,IAAI,+BAAuB,CAAC;QAEvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,qEAAqE;QACrE,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,OAAO,OAAO,EAAE,GAAG,KAAK,QAAQ,EAAE;YACpC,IAAI,CAAC,QAAQ,GAAG,I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C,kBAAkB,EAAE;IAChC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/bulk_write.js b/nodejs/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 00000000..92f1e938 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BulkWriteOperation = void 0; +const operation_1 = require("./operation"); +/** @internal */ +class BulkWriteOperation extends operation_1.AbstractOperation { + constructor(collection, operations, options) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + get commandName() { + return 'bulkWrite'; + } + async execute(server, session) { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + // Create the bulk operation + const bulk = options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + // for each op go through and add to the bulk + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + // Execute the bulk + const result = await bulk.execute({ ...options, session }); + return result; + } +} +exports.BulkWriteOperation = BulkWriteOperation; +(0, operation_1.defineAspects)(BulkWriteOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=bulk_write.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/bulk_write.js.map b/nodejs/node_modules/mongodb/lib/operations/bulk_write.js.map new file mode 100644 index 00000000..1019ea9b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/bulk_write.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bulk_write.js","sourceRoot":"","sources":["../../src/operations/bulk_write.ts"],"names":[],"mappings":";;;AASA,2CAAuE;AAEvE,gBAAgB;AAChB,MAAa,kBAAmB,SAAQ,6BAAkC;IAKxE,YACE,UAAsB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/mongodb/lib/operations/collections.js new file mode 100644 index 00000000..bd627b9d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CollectionsOperation = void 0; +const collection_1 = require("../collection"); +const operation_1 = require("./operation"); +/** @internal */ +class CollectionsOperation extends operation_1.AbstractOperation { + constructor(db, options) { + super(options); + this.options = options; + this.db = db; + } + get commandName() { + return 'listCollections'; + } + async execute(server, session) { + // Let's get the collection names + const documents = await this.db + .listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }) + .toArray(); + const collections = []; + for (const { name } of documents) { + if (!name.includes('$')) { + // Filter collections removing any illegal ones + collections.push(new collection_1.Collection(this.db, name, this.db.s.options)); + } + } + // Return the collection objects + return collections; + } +} +exports.CollectionsOperation = CollectionsOperation; +//# sourceMappingURL=collections.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/collections.js.map b/nodejs/node_modules/mongodb/lib/operations/collections.js.map new file mode 100644 index 00000000..d2739c68 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collections.js","sourceRoot":"","sources":["../../src/operations/collections.ts"],"names":[],"mappings":";;;AAAA,8CAA2C;AAI3C,2CAAuE;AAMvE,gBAAgB;AAChB,MAAa,oBAAqB,SAAQ,6BAA+B;IAIvE,YAAY,EAAM,EAAE,OAA2B;QAC7C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,iBAA0B,CAAC;IACpC,CAAC;IAEQ,KAAK,CAAC,OAAO,CACpB,MAAc,EACd,OAAkC;QAElC,iCAAiC;QACjC,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,EAAE;aAC5B,eAAe,CACd,EAAE,EACF,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAClF;aACA,OAAO,EAAE,CAAC;QACb,MAAM,WAAW,GAAiB,EAAE,CAAC;QACrC,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,SAAS,EAAE;YAChC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;gBACvB,+CAA+C;gBAC/C,WAAW,CAAC,IAAI,CAAC,IAAI,uBAAU,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;aACpE;SACF;QACD,gCAAgC;QAChC,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AAnCD,oDAmCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/command.js b/nodejs/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 00000000..ea4141bd --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CommandOperation = void 0; +const error_1 = require("../error"); +const explain_1 = require("../explain"); +const read_concern_1 = require("../read_concern"); +const server_selection_1 = require("../sdam/server_selection"); +const utils_1 = require("../utils"); +const write_concern_1 = require("../write_concern"); +const operation_1 = require("./operation"); +/** @internal */ +class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + super(options); + this.options = options ?? {}; + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = options?.dbName || options?.authdb; + if (dbNameOverride) { + this.ns = new utils_1.MongoDBNamespace(dbNameOverride, '$cmd'); + } + else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new utils_1.MongoDBNamespace('admin', '$cmd'); + } + this.readConcern = read_concern_1.ReadConcern.fromOptions(options); + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); + } + else if (options?.explain != null) { + throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + get canRetryWrite() { + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + async executeCommand(server, session, cmd) { + // TODO: consider making this a non-enumerable property + this.server = server; + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const inTransaction = this.session && this.session.inTransaction(); + if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + if (this.trySecondaryWrite && serverWireVersion < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION) { + options.omitReadPreference = true; + } + if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + write_concern_1.WriteConcern.apply(cmd, this.writeConcern); + } + if (options.collation && + typeof options.collation === 'object' && + !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { + Object.assign(cmd, { collation: options.collation }); + } + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { + cmd = (0, utils_1.decorateWithExplain)(cmd, this.explain); + } + return server.command(this.ns, cmd, options); + } +} +exports.CommandOperation = CommandOperation; +//# sourceMappingURL=command.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/command.js.map b/nodejs/node_modules/mongodb/lib/operations/command.js.map new file mode 100644 index 00000000..c53999e4 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command.js","sourceRoot":"","sources":["../../src/operations/command.ts"],"names":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AAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,IAAI,IAAI,CAAC,SAAS,CAAC,kBAAM,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACtD,GAAG,GAAG,IAAA,2BAAmB,EAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;SAC9C;QAED,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;CACF;AAvFD,4CAuFC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/common_functions.js b/nodejs/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 00000000..cd0adc07 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.maybeAddIdToDocuments = exports.indexInformation = void 0; +async function indexInformation(db, name, options) { + if (options == null) { + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + // Get the list of indexes of the specified collection + const indexes = await db.collection(name).listIndexes(options).toArray(); + if (full) + return indexes; + const info = {}; + for (const index of indexes) { + info[index.name] = Object.entries(index.key); + } + return info; +} +exports.indexInformation = indexInformation; +function maybeAddIdToDocuments(coll, docOrDocs, options) { + const forceServerObjectId = typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options?.forceServerObjectId; + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docOrDocs; + } + const transform = (doc) => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + return doc; + }; + return Array.isArray(docOrDocs) ? docOrDocs.map(transform) : transform(docOrDocs); +} +exports.maybeAddIdToDocuments = maybeAddIdToDocuments; +//# sourceMappingURL=common_functions.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/common_functions.js.map b/nodejs/node_modules/mongodb/lib/operations/common_functions.js.map new file mode 100644 index 00000000..92a48123 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/common_functions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common_functions.js","sourceRoot":"","sources":["../../src/operations/common_functions.ts"],"names":[],"mappings":";;;AAwBO,KAAK,UAAU,gBAAgB,CACpC,EAAM,EACN,IAAY,EACZ,OAAiC;IAEjC,IAAI,OAAO,IAAI,IAAI,EAAE;QACnB,OAAO,GAAG,EAAE,CAAC;KACd;IACD,mCAAmC;IACnC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;IACzD,sDAAsD;IACtD,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;IACzE,IAAI,IAAI;QAAE,OAAO,OAAO,CAAC;IAEzB,MAAM,IAAI,GAA6C,EAAE,CAAC;IAC1D,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE;QAC3B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;KAC9C;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAnBD,4CAmBC;AAYD,SAAgB,qBAAqB,CACnC,IAAgB,EAChB,SAAgC,EAChC,OAA0C;IAE1C,MAAM,mBAAmB,GACvB,OAAO,OAAO,CAAC,mBAAmB,KAAK,SAAS;QAC9C,CAAC,CAAC,OAAO,CAAC,mBAAmB;QAC7B,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,EAAE,mBAAmB,CAAC;IAE7C,yDAAyD;IACzD,IAAI,mBAAmB,KAAK,IAAI,EAAE;QAChC,OAAO,SAAS,CAAC;KAClB;IAED,MAAM,SAAS,GAAG,CAAC,GAAa,EAAY,EAAE;QAC5C,IAAI,GAAG,CAAC,GAAG,IAAI,IAAI,EAAE;YACnB,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;SACvC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;IACF,OAAO,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AACpF,CAAC;AAvBD,sDAuBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/count.js b/nodejs/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 00000000..067fe6e6 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/count.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CountOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class CountOperation extends command_1.CommandOperation { + constructor(namespace, filter, options) { + super({ s: { namespace: namespace } }, options); + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + get commandName() { + return 'count'; + } + async execute(server, session) { + const options = this.options; + const cmd = { + count: this.collectionName, + query: this.query + }; + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + if (options.hint != null) { + cmd.hint = options.hint; + } + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + const result = await super.executeCommand(server, session, cmd); + return result ? result.n : 0; + } +} +exports.CountOperation = CountOperation; +(0, operation_1.defineAspects)(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=count.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/count.js.map b/nodejs/node_modules/mongodb/lib/operations/count.js.map new file mode 100644 index 00000000..3b3ec219 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count.js","sourceRoot":"","sources":["../../src/operations/count.ts"],"names":[],"mappings":";;;AAKA,uCAA2E;AAC3E,2CAAoD;AAcpD,gBAAgB;AAChB,MAAa,cAAe,SAAQ,0BAAwB;IAK1D,YAAY,SAA2B,EAAE,MAAgB,EAAE,OAAqB;QAC9E,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,EAA2B,EAAE,OAAO,CAAC,CAAC;QAEzE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC,UAAU,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC;IACtB,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,OAAgB,CAAC;IAC1B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC7B,MAAM,GAAG,GAAa;YACpB,KAAK,EAAE,IAAI,CAAC,cAAc;YAC1B,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;QAEF,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;YACrC,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;SAC3B;QAED,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACpC,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SACzB;QAED,IAAI,OAAO,CAAC,IAAI,IAAI,IAAI,EAAE;YACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;SACzB;QAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;QAChE,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC;CACF;AA3CD,wCA2CC;AAED,IAAA,yBAAa,EAAC,cAAc,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/count_documents.js b/nodejs/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 00000000..a70c80c5 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/count_documents.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CountDocumentsOperation = void 0; +const aggregate_1 = require("./aggregate"); +/** @internal */ +class CountDocumentsOperation extends aggregate_1.AggregateOperation { + constructor(collection, query, options) { + const pipeline = []; + pipeline.push({ $match: query }); + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + super(collection.s.namespace, pipeline, options); + } + async execute(server, session) { + const result = await super.execute(server, session); + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result; + if (response.cursor == null || response.cursor.firstBatch == null) { + return 0; + } + const docs = response.cursor.firstBatch; + return docs.length ? docs[0].n : 0; + } +} +exports.CountDocumentsOperation = CountDocumentsOperation; +//# sourceMappingURL=count_documents.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/count_documents.js.map b/nodejs/node_modules/mongodb/lib/operations/count_documents.js.map new file mode 100644 index 00000000..4cf9f0f2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/count_documents.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count_documents.js","sourceRoot":"","sources":["../../src/operations/count_documents.ts"],"names":[],"mappings":";;;AAIA,2CAAwE;AAUxE,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,8BAA0B;IACrE,YAAY,UAAsB,EAAE,KAAe,EAAE,OAA8B;QACjF,MAAM,QAAQ,GAAG,EAAE,CAAC;QACpB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QAEjC,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACpC,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;SACxC;QAED,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;YACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;SAC1C;QAED,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAEtD,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAEpD,uEAAuE;QACvE,MAAM,QAAQ,GAAG,MAA6B,CAAC;QAC/C,IAAI,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,IAAI,IAAI,EAAE;YACjE,OAAO,CAAC,CAAC;SACV;QAED,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;QACxC,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,CAAC;CACF;AA9BD,0DA8BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/create_collection.js b/nodejs/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 00000000..318bec2d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/create_collection.js @@ -0,0 +1,102 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateCollectionOperation = void 0; +const constants_1 = require("../cmap/wire_protocol/constants"); +const collection_1 = require("../collection"); +const error_1 = require("../error"); +const command_1 = require("./command"); +const indexes_1 = require("./indexes"); +const operation_1 = require("./operation"); +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'useBigInt64', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'enableUtf8Validation' +]); +/* @internal */ +const INVALID_QE_VERSION = 'Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption.'; +/** @internal */ +class CreateCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options = {}) { + super(db, options); + this.options = options; + this.db = db; + this.name = name; + } + get commandName() { + return 'create'; + } + async execute(server, session) { + const db = this.db; + const name = this.name; + const options = this.options; + const encryptedFields = options.encryptedFields ?? + db.client.options.autoEncryption?.encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + if (encryptedFields) { + // Creating a QE collection required min server of 7.0.0 + // TODO(NODE-5353): Get wire version information from connection. + if (!server.loadBalanced && + server.description.maxWireVersion < constants_1.MIN_SUPPORTED_QE_WIRE_VERSION) { + throw new error_1.MongoCompatibilityError(`${INVALID_QE_VERSION} The minimum server version required is ${constants_1.MIN_SUPPORTED_QE_SERVER_VERSION}`); + } + // Create auxilliary collections for queryable encryption support. + const escCollection = encryptedFields.escCollection ?? `enxcol_.${name}.esc`; + const ecocCollection = encryptedFields.ecocCollection ?? `enxcol_.${name}.ecoc`; + for (const collectionName of [escCollection, ecocCollection]) { + const createOp = new CreateCollectionOperation(db, collectionName, { + clusteredIndex: { + key: { _id: 1 }, + unique: true + } + }); + await createOp.executeWithoutEncryptedFieldsCheck(server, session); + } + if (!options.encryptedFields) { + this.options = { ...this.options, encryptedFields }; + } + } + const coll = await this.executeWithoutEncryptedFieldsCheck(server, session); + if (encryptedFields) { + // Create the required index for queryable encryption support. + const createIndexOp = new indexes_1.CreateIndexOperation(db, name, { __safeContent__: 1 }, {}); + await createIndexOp.execute(server, session); + } + return coll; + } + async executeWithoutEncryptedFieldsCheck(server, session) { + const db = this.db; + const name = this.name; + const options = this.options; + const cmd = { create: name }; + for (const n in options) { + if (options[n] != null && + typeof options[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n)) { + cmd[n] = options[n]; + } + } + // otherwise just execute the command + await super.executeCommand(server, session, cmd); + return new collection_1.Collection(db, name, options); + } +} +exports.CreateCollectionOperation = CreateCollectionOperation; +(0, operation_1.defineAspects)(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=create_collection.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/create_collection.js.map b/nodejs/node_modules/mongodb/lib/operations/create_collection.js.map new file mode 100644 index 00000000..cf649867 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/create_collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"create_collection.js","sourceRoot":"","sources":["../../src/operations/create_collection.ts"],"names":[],"mappings":";;;AACA,+DAGyC;AACzC,8CAA2C;AAE3C,oCAAmD;AAInD,uCAA2E;AAC3E,uCAAiD;AACjD,2CAAoD;AAEp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I,CAAC,OAAO,CAAC;QAE7B,MAAM,GAAG,GAAa,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACvC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE;YACvB,IACG,OAAe,CAAC,CAAC,CAAC,IAAI,IAAI;gBAC3B,OAAQ,OAAe,CAAC,CAAC,CAAC,KAAK,UAAU;gBACzC,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,EAC9B;gBACA,GAAG,CAAC,CAAC,CAAC,GAAI,OAAe,CAAC,CAAC,CAAC,CAAC;aAC9B;SACF;QACD,qCAAqC;QACrC,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;QACjD,OAAO,IAAI,uBAAU,CAAC,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC3C,CAAC;CACF;AAzFD,8DAyFC;AAED,IAAA,yBAAa,EAAC,yBAAyB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/delete.js b/nodejs/node_modules/mongodb/lib/operations/delete.js new file mode 100644 index 00000000..1b83ec8f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/delete.js @@ -0,0 +1,115 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeDeleteStatement = exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class DeleteOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get commandName() { + return 'delete'; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; + } + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + async execute(server, session) { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + if (options.let) { + command.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`); + } + } + return super.executeCommand(server, session, command); + } +} +exports.DeleteOperation = DeleteOperation; +class DeleteOneOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + async execute(server, session) { + const res = (await super.execute(server, session)); + if (this.explain) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + deletedCount: res.n + }; + } +} +exports.DeleteOneOperation = DeleteOneOperation; +class DeleteManyOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + async execute(server, session) { + const res = (await super.execute(server, session)); + if (this.explain) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + deletedCount: res.n + }; + } +} +exports.DeleteManyOperation = DeleteManyOperation; +function makeDeleteStatement(filter, options) { + const op = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + if (options.collation) { + op.collation = options.collation; + } + if (options.hint) { + op.hint = options.hint; + } + return op; +} +exports.makeDeleteStatement = makeDeleteStatement; +(0, operation_1.defineAspects)(DeleteOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DeleteOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(DeleteManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=delete.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/delete.js.map b/nodejs/node_modules/mongodb/lib/operations/delete.js.map new file mode 100644 index 00000000..46f5be63 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/delete.js.map @@ -0,0 +1 @@ +{"version":3,"file":"delete.js","sourceRoot":"","sources":["../../src/operations/delete.ts"],"names":[],"mappings":";;;AAEA,oCAAqE;AAMrE,uCAAkG;AAClG,2CAA+D;AAkC/D,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA8B;IAIjE,YAAY,EAAoB,EAAE,UAA6B,EAAE,OAAsB;QACrF,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,QAAiB,CAAC;IAC3B,CAAC;IAED,IAAa,aAAa;QACxB,IAAI,KAAK,CAAC,aAAa,KAAK,KAAK,EAAE;YACjC,OAAO,KAAK,CAAC;SACd;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/E,CAAC;IAEQ,KAAK,CAAC,OAAO,CACpB,MAAc,EACd,OAAkC;QAElC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI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SACpB,CAAC;IACJ,CAAC;CACF;AAnBD,kDAmBC;AAED,SAAgB,mBAAmB,CACjC,MAAgB,EAChB,OAA2C;IAE3C,MAAM,EAAE,GAAoB;QAC1B,CAAC,EAAE,MAAM;QACT,KAAK,EAAE,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC7D,CAAC;IAEF,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,EAAE,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAClC;IAED,IAAI,OAAO,CAAC,IAAI,EAAE;QAChB,EAAE,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;KACxB;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAlBD,kDAkBC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC3E,IAAA,yBAAa,EAAC,kBAAkB,EAAE;IAChC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC;AACH,IAAA,yBAAa,EAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/distinct.js b/nodejs/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 00000000..0bfa9ccb --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DistinctOperation = void 0; +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +class DistinctOperation extends command_1.CommandOperation { + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + this.options = options ?? {}; + this.collection = collection; + this.key = key; + this.query = query; + } + get commandName() { + return 'distinct'; + } + async execute(server, session) { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + // Distinct command + const cmd = { + distinct: coll.collectionName, + key: key, + query: query + }; + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (typeof options.comment !== 'undefined') { + cmd.comment = options.comment; + } + // Do we have a readConcern specified + (0, utils_1.decorateWithReadConcern)(cmd, coll, options); + // Have we specified collation + (0, utils_1.decorateWithCollation)(cmd, coll, options); + const result = await super.executeCommand(server, session, cmd); + return this.explain ? result : result.values; + } +} +exports.DistinctOperation = DistinctOperation; +(0, operation_1.defineAspects)(DistinctOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=distinct.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/distinct.js.map b/nodejs/node_modules/mongodb/lib/operations/distinct.js.map new file mode 100644 index 00000000..c8e49ba7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/distinct.js.map @@ -0,0 +1 @@ +{"version":3,"file":"distinct.js","sourceRoot":"","sources":["../../src/operations/distinct.ts"],"names":[],"mappings":";;;AAIA,oCAA0E;AAC1E,uCAA2E;AAC3E,2CAAoD;AAKpD;;;GAGG;AACH,MAAa,iBAAkB,SAAQ,0BAAuB;IAQ5D;;;;;;;OAOG;IACH,YAAY,UAAsB,EAAE,GAAW,EAAE,KAAe,EAAE,OAAyB;QACz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I,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC;IAC/C,CAAC;CACF;AA/DD,8CA+DC;AAED,IAAA,yBAAa,EAAC,iBAAiB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,WAAW,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/drop.js b/nodejs/node_modules/mongodb/lib/operations/drop.js new file mode 100644 index 00000000..99386c39 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,76 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DropDatabaseOperation = exports.DropCollectionOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class DropCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options = {}) { + super(db, options); + this.db = db; + this.options = options; + this.name = name; + } + get commandName() { + return 'drop'; + } + async execute(server, session) { + const db = this.db; + const options = this.options; + const name = this.name; + const encryptedFieldsMap = db.client.options.autoEncryption?.encryptedFieldsMap; + let encryptedFields = options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + if (!encryptedFields && encryptedFieldsMap) { + // If the MongoClient was configured with an encryptedFieldsMap, + // and no encryptedFields config was available in it or explicitly + // passed as an argument, the spec tells us to look one up using + // listCollections(). + const listCollectionsResult = await db + .listCollections({ name }, { nameOnly: false }) + .toArray(); + encryptedFields = listCollectionsResult?.[0]?.options?.encryptedFields; + } + if (encryptedFields) { + const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`; + const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`; + for (const collectionName of [escCollection, ecocCollection]) { + // Drop auxilliary collections, ignoring potential NamespaceNotFound errors. + const dropOp = new DropCollectionOperation(db, collectionName); + try { + await dropOp.executeWithoutEncryptedFieldsCheck(server, session); + } + catch (err) { + if (!(err instanceof error_1.MongoServerError) || + err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + throw err; + } + } + } + } + return this.executeWithoutEncryptedFieldsCheck(server, session); + } + async executeWithoutEncryptedFieldsCheck(server, session) { + await super.executeCommand(server, session, { drop: this.name }); + return true; + } +} +exports.DropCollectionOperation = DropCollectionOperation; +/** @internal */ +class DropDatabaseOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + get commandName() { + return 'dropDatabase'; + } + async execute(server, session) { + await super.executeCommand(server, session, { dropDatabase: 1 }); + return true; + } +} +exports.DropDatabaseOperation = DropDatabaseOperation; +(0, operation_1.defineAspects)(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=drop.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/drop.js.map b/nodejs/node_modules/mongodb/lib/operations/drop.js.map new file mode 100644 index 00000000..d74d1f9d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/drop.js.map @@ -0,0 +1 @@ +{"version":3,"file":"drop.js","sourceRoot":"","sources":["../../src/operations/drop.ts"],"names":[],"mappings":";;;AAEA,oCAAiE;AAGjE,uCAA2E;AAC3E,2CAAoD;AAQpD,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,0BAAyB;IAKpE,YAAY,EAAM,EAAE,IAAY,EAAE,UAAiC,EAAE;QACnE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,MAAe,CAAC;IACzB,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EA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2BAAmB,CAAC,iBAAiB,EAClD;wBACA,MAAM,GAAG,CAAC;qBACX;iBACF;aACF;SACF;QAED,OAAO,IAAI,CAAC,kCAAkC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;IAEO,KAAK,CAAC,kCAAkC,CAC9C,MAAc,EACd,OAAkC;QAElC,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlED,0DAkEC;AAKD,gBAAgB;AAChB,MAAa,qBAAsB,SAAQ,0BAAyB;IAGlE,YAAY,EAAM,EAAE,OAA4B;QAC9C,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IACD,IAAa,WAAW;QACtB,OAAO,cAAuB,CAAC;IACjC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAfD,sDAeC;AAED,IAAA,yBAAa,EAAC,uBAAuB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AACjE,IAAA,yBAAa,EAAC,qBAAqB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/estimated_document_count.js b/nodejs/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 00000000..125733bf --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/estimated_document_count.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EstimatedDocumentCountOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class EstimatedDocumentCountOperation extends command_1.CommandOperation { + constructor(collection, options = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + get commandName() { + return 'count'; + } + async execute(server, session) { + const cmd = { count: this.collectionName }; + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + const response = await super.executeCommand(server, session, cmd); + return response?.n || 0; + } +} +exports.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation; +(0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=estimated_document_count.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/estimated_document_count.js.map b/nodejs/node_modules/mongodb/lib/operations/estimated_document_count.js.map new file mode 100644 index 00000000..9c12f2fb --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/estimated_document_count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"estimated_document_count.js","sourceRoot":"","sources":["../../src/operations/estimated_document_count.ts"],"names":[],"mappings":";;;AAIA,uCAA2E;AAC3E,2CAAoD;AAYpD,gBAAgB;AAChB,MAAa,+BAAgC,SAAQ,0BAAwB;IAI3E,YAAY,UAAsB,EAAE,UAAyC,EAAE;QAC7E,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;IAClD,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,OAAgB,CAAC;IAC1B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,GAAG,GAAa,EAAE,KAAK,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAErD,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACxC;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACtC,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACpC;QAED,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;QAElE,OAAO,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;CACF;AA/BD,0EA+BC;AAED,IAAA,yBAAa,EAAC,+BAA+B,EAAE;IAC7C,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/execute_operation.js b/nodejs/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 00000000..f7a552c7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,191 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.executeOperation = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const server_selection_1 = require("../sdam/server_selection"); +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +const MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; +/** + * Executes the given operation with provided arguments. + * @internal + * + * @remarks + * Allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided. + * + * The expectation is that this function: + * - Connects the MongoClient if it has not already been connected + * - Creates a session if none is provided and cleans up the session it creates + * - Selects a server based on readPreference or various factors + * - Retries an operation if it fails for certain errors, see {@link retryOperation} + * + * @typeParam T - The operation's type + * @typeParam TResult - The type of the operation's result, calculated from T + * + * @param client - The MongoClient to execute this operation with + * @param operation - The operation to execute + */ +async function executeOperation(client, operation) { + if (!(operation instanceof operation_1.AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new error_1.MongoRuntimeError('This method requires a valid operation instance'); + } + if (client.topology == null) { + // Auto connect on operation + if (client.s.hasBeenClosed) { + throw new error_1.MongoNotConnectedError('Client must be connected before running operations'); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + try { + await client.connect(); + } + finally { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + } + } + const { topology } = client; + if (topology == null) { + throw new error_1.MongoRuntimeError('client.connect did not create a topology but also did not throw'); + } + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session = operation.session; + let owner; + if (session == null) { + owner = Symbol(); + session = client.startSession({ owner, explicit: false }); + } + else if (session.hasEnded) { + throw new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted'); + } + else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw new error_1.MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later'); + } + else if (session.client !== client) { + throw new error_1.MongoInvalidArgumentError('ClientSession must be from the same MongoClient'); + } + const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) { + throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`); + } + if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) { + session.unpin(); + } + let selector; + if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) { + // GetMore and KillCursor operations must always select the same server, but run through + // server selection to potentially force monitor checks if the server is + // in an unknown state. + selector = (0, server_selection_1.sameServerSelector)(operation.server?.description); + } + else if (operation.trySecondaryWrite) { + // If operation should try to write to secondary use the custom server selector + // otherwise provide the read preference. + selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); + } + else { + selector = readPreference; + } + const server = await topology.selectServerAsync(selector, { + session, + operationName: operation.commandName + }); + if (session == null) { + // No session also means it is not retryable, early exit + return operation.execute(server, undefined); + } + if (!operation.hasAspect(operation_1.Aspect.RETRYABLE)) { + // non-retryable operation, early exit + try { + return await operation.execute(server, session); + } + finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } + } + const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead; + const willRetryWrite = topology.s.options.retryWrites && + !inTransaction && + (0, utils_1.supportsRetryableWrites)(server) && + operation.canRetryWrite; + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite); + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + try { + return await operation.execute(server, session); + } + catch (operationError) { + if (willRetry && operationError instanceof error_1.MongoError) { + return await retryOperation(operation, operationError, { + session, + topology, + selector, + previousServer: server.description + }); + } + throw operationError; + } + finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } +} +exports.executeOperation = executeOperation; +async function retryOperation(operation, originalError, { session, topology, selector, previousServer }) { + const isWriteOperation = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + const isReadOperation = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + throw new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }); + } + if (isWriteOperation && !(0, error_1.isRetryableWriteError)(originalError)) { + throw originalError; + } + if (isReadOperation && !(0, error_1.isRetryableReadError)(originalError)) { + throw originalError; + } + if (originalError instanceof error_1.MongoNetworkError && + session.isPinned && + !session.inTransaction() && + operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) { + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + session.unpin({ force: true, forceClear: true }); + } + // select a new server, and attempt to retry the operation + const server = await topology.selectServerAsync(selector, { + session, + operationName: operation.commandName, + previousServer + }); + if (isWriteOperation && !(0, utils_1.supportsRetryableWrites)(server)) { + throw new error_1.MongoUnexpectedServerResponseError('Selected server does not support retryable writes'); + } + try { + return await operation.execute(server, session); + } + catch (retryError) { + if (retryError instanceof error_1.MongoError && + retryError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) { + throw originalError; + } + throw retryError; + } +} +//# sourceMappingURL=execute_operation.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/execute_operation.js.map b/nodejs/node_modules/mongodb/lib/operations/execute_operation.js.map new file mode 100644 index 00000000..3a87b10c --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/execute_operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"execute_operation.js","sourceRoot":"","sources":["../../src/operations/execute_operation.ts"],"names":[],"mappings":";;;AACA,oCAekB;AAElB,wDAAoD;AAGpD,+DAIkC;AAGlC,oCAAmD;AACnD,2CAAwD;AAExD,MAAM,8BAA8B,GAAG,2BAAmB,CAAC,gBAAgB,CAAC;AAC5E,MAAM,iCAAiC,GACrC,oHAAoH,CAAC;AAgBvH;;;;;;;;;;;;;;;;;;;;GAoBG;AACI,KAAK,UAAU,gBAAgB,CAGpC,MAAmB,EAAE,SAAY;IACjC,IAAI,CAAC,CAAC,SA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,4CAA4C;QAC5C,OAAO,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;KAClD;IAED,0DAA0D;IAC1D,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,iBAAiB,CAAC,QAAQ,EAAE;QACxD,OAAO;QACP,aAAa,EAAE,SAAS,CAAC,WAAW;QACpC,cAAc;KACf,CAAC,CAAC;IAEH,IAAI,gBAAgB,IAAI,CAAC,IAAA,+BAAuB,EAAC,MAAM,CAAC,EAAE;QACxD,MAAM,IAAI,0CAAkC,CAC1C,mDAAmD,CACpD,CAAC;KACH;IAED,IAAI;QACF,OAAO,MAAM,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACjD;IAAC,OAAO,UAAU,EAAE;QACnB,IACE,UAAU,YAAY,kBAAU;YAChC,UAAU,CAAC,aAAa,CAAC,uBAAe,CAAC,iBAAiB,CAAC,EAC3D;YACA,MAAM,aAAa,CAAC;SACrB;QACD,MAAM,UAAU,CAAC;KAClB;AACH,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/find.js b/nodejs/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 00000000..6113bc93 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,152 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindOperation = void 0; +const error_1 = require("../error"); +const read_concern_1 = require("../read_concern"); +const sort_1 = require("../sort"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class FindOperation extends command_1.CommandOperation { + constructor(collection, ns, filter = {}, options = {}) { + super(collection, options); + this.options = { ...options }; + delete this.options.writeConcern; + this.ns = ns; + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new error_1.MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectId' ? { _id: filter } : filter; + } + get commandName() { + return 'find'; + } + async execute(server, session) { + this.server = server; + const options = this.options; + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = (0, utils_1.decorateWithExplain)(findCommand, this.explain); + } + return server.command(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }); + } +} +exports.FindOperation = FindOperation; +function makeFindCommand(ns, filter, options) { + const findCommand = { + find: ns.collection, + filter + }; + if (options.sort) { + findCommand.sort = (0, sort_1.formatSort)(options.sort); + } + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + findCommand.projection = projection; + } + if (options.hint) { + findCommand.hint = (0, utils_1.normalizeHintField)(options.hint); + } + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; + } + else { + findCommand.limit = options.limit; + } + } + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if (options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit)) { + findCommand.limit = -options.batchSize; + } + findCommand.singleBatch = true; + } + else { + findCommand.batchSize = options.batchSize; + } + } + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + findCommand.comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + if (options.max) { + findCommand.max = options.max; + } + if (options.min) { + findCommand.min = options.min; + } + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + if (typeof options.oplogReplay === 'boolean') { + findCommand.oplogReplay = options.oplogReplay; + } + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } + else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + if (options.collation) { + findCommand.collation = options.collation; + } + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + if (options.let) { + findCommand.let = options.let; + } + return findCommand; +} +(0, operation_1.defineAspects)(FindOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=find.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/find.js.map b/nodejs/node_modules/mongodb/lib/operations/find.js.map new file mode 100644 index 00000000..20a7efbc --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/find.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find.js","sourceRoot":"","sources":["../../src/operations/find.ts"],"names":[],"mappings":";;;AAEA,oCAAqD;AACrD,kDAA8C;AAG9C,kCAAgD;AAChD,oCAA0F;AAC1F,uCAAkG;AAClG,2CAA+D;AA0D/D,gBAAgB;AAChB,MAAa,aAAc,SAAQ,0BAA0B;IAW3D,YACE,UAAkC,EAClC,EAAoB,EACpB,SAAmB,EAAE,EACrB,UAAuB,EAAE;QAEzB,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,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b/lib/operations/find_and_modify.js b/nodejs/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 00000000..caa311ae --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,152 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FindOneAndUpdateOperation = exports.FindOneAndReplaceOperation = exports.FindOneAndDeleteOperation = exports.FindAndModifyOperation = exports.ReturnDocument = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const sort_1 = require("../sort"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @public */ +exports.ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +}); +function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) { + cmdBase.new = options.returnDocument === exports.ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} +/** @internal */ +class FindAndModifyOperation extends command_1.CommandOperation { + constructor(collection, query, options) { + super(collection, options); + this.options = options ?? {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + options.includeResultMetadata ??= false; + const sort = (0, sort_1.formatSort)(options.sort); + if (sort) { + this.cmdBase.sort = sort; + } + if (options.projection) { + this.cmdBase.fields = options.projection; + } + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; + } + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; + } + if (options.let) { + this.cmdBase.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this.cmdBase.comment = options.comment; + } + // force primary read preference + this.readPreference = read_preference_1.ReadPreference.primary; + this.collection = collection; + this.query = query; + } + get commandName() { + return 'findAndModify'; + } + async execute(server, session) { + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + // Create findAndModify command object + const cmd = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + // Have we specified collation + try { + (0, utils_1.decorateWithCollation)(cmd, coll, options); + } + catch (err) { + return err; + } + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = this.writeConcern?.w === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 8) { + throw new error_1.MongoCompatibilityError('The current topology does not support a hint on findAndModify commands'); + } + cmd.hint = options.hint; + } + // Execute the command + const result = await super.executeCommand(server, session, cmd); + return options.includeResultMetadata ? result : result.value ?? null; + } +} +exports.FindAndModifyOperation = FindAndModifyOperation; +/** @internal */ +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + super(collection, filter, options); + this.cmdBase.remove = true; + } +} +exports.FindOneAndDeleteOperation = FindOneAndDeleteOperation; +/** @internal */ +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (replacement == null || typeof replacement !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} +exports.FindOneAndReplaceOperation = FindOneAndReplaceOperation; +/** @internal */ +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object'); + } + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; + } + } +} +exports.FindOneAndUpdateOperation = FindOneAndUpdateOperation; +(0, operation_1.defineAspects)(FindAndModifyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE +]); +//# sourceMappingURL=find_and_modify.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/find_and_modify.js.map b/nodejs/node_modules/mongodb/lib/operations/find_and_modify.js.map new file mode 100644 index 00000000..150ec0b7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/find_and_modify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_and_modify.js","sourceRoot":"","sources":["../../src/operations/find_and_modify.ts"],"names":[],"mappings":";;;AAEA,oCAA8E;AAC9E,wDAAoD;AAGpD,kCAAiE;AACjE,oCAAqF;AAErF,uCAA2E;AAC3E,2CAAoD;AAEpD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACN,CAAC,CAAC;AA2FZ,SAAS,uCAAuC,CAC9C,OAA6B,EAC7B,OAA2D;IAE3D,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,cAAc,KAAK,sBAAc,CAAC,KAAK,CAAC;IAC9D,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC;IAEzC,IAAI,OAAO,CAAC,wBAAwB,KAAK,IAAI,EAAE;QAC7C,OAAO,CAAC,wBAAwB,GAAG,OAAO,CAAC,wBAAwB,CAAC;KACrE;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,gBAAgB;AAChB,MA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AAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,IAAI,MAAM,IAAI,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YAChD,MAAM,IAAI,iCAAyB,CAAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,IAAI,CAAC,IAAA,0BAAkB,EAAC,MAAM,CAAC,EAAE;YAC/B,MAAM,IAAI,iCAAyB,CAAC,2CAA2C,CAAC,CAAC;SAClF;QAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC;QAC7B,uCAAuC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAE/D,IAAI,OAAO,CAAC,YAAY,EAAE;YACxB,IAAI,CAAC,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;SAClD;IACH,CAAC;CACF;AA3BD,8DA2BC;AAED,IAAA,yBAAa,EAAC,sBAAsB,EAAE;IACpC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,WAAW;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/get_more.js b/nodejs/node_modules/mongodb/lib/operations/get_more.js new file mode 100644 index 00000000..fcdddc5b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/get_more.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GetMoreOperation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +/** @internal */ +class GetMoreOperation extends operation_1.AbstractOperation { + constructor(ns, cursorId, server, options) { + super(options); + this.options = options; + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + get commandName() { + return 'getMore'; + } + /** + * Although there is a server already associated with the get more operation, the signature + * for execute passes a server so we will just use that one. + */ + async execute(server, _session) { + if (server !== this.server) { + throw new error_1.MongoRuntimeError('Getmore must run on the same server operation began on'); + } + if (this.cursorId == null || this.cursorId.isZero()) { + throw new error_1.MongoRuntimeError('Unable to iterate cursor with no id'); + } + const collection = this.ns.collection; + if (collection == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + throw new error_1.MongoRuntimeError('A collection name must be determined before getMore'); + } + const getMoreCmd = { + getMore: this.cursorId, + collection + }; + if (typeof this.options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + if (typeof this.options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined && (0, utils_1.maxWireVersion)(server) >= 9) { + getMoreCmd.comment = this.options.comment; + } + const commandOptions = { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch', + ...this.options + }; + return server.command(this.ns, getMoreCmd, commandOptions); + } +} +exports.GetMoreOperation = GetMoreOperation; +(0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]); +//# sourceMappingURL=get_more.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/get_more.js.map b/nodejs/node_modules/mongodb/lib/operations/get_more.js.map new file mode 100644 index 00000000..e91e9347 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/get_more.js.map @@ -0,0 +1 @@ +{"version":3,"file":"get_more.js","sourceRoot":"","sources":["../../src/operations/get_more.ts"],"names":[],"mappings":";;;AACA,oCAA6C;AAG7C,oCAAiE;AACjE,2CAA8F;AA+B9F,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAAiB;IAIrD,YAAY,EAAoB,EAAE,QAAc,EAAE,MAAc,EAAE,OAAuB;QACvF,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,O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,EAAE;YACrE,UAAU,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SAC3C;QAED,MAAM,cAAc,GAAG;YACrB,mBAAmB,EAAE,IAAI;YACzB,mBAAmB,EAAE,WAAW;YAChC,GAAG,IAAI,CAAC,OAAO;SAChB,CAAC;QAEF,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;IAC7D,CAAC;CACF;AA/DD,4CA+DC;AAED,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/indexes.js b/nodejs/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 00000000..32d2d883 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,267 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IndexInformationOperation = exports.IndexExistsOperation = exports.ListIndexesOperation = exports.DropIndexOperation = exports.EnsureIndexOperation = exports.CreateIndexOperation = exports.CreateIndexesOperation = exports.IndexesOperation = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const common_functions_1 = require("./common_functions"); +const operation_1 = require("./operation"); +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + // 2d-sphere indexes + '2dsphereIndexVersion', + // 2d indexes + 'bits', + 'min', + 'max', + // geoHaystack Indexes + 'bucketSize', + // wildcard indexes + 'wildcardProjection' +]); +function isIndexDirection(x) { + return (typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack'); +} +function isSingleIndexTuple(t) { + return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); +} +function makeIndexSpec(indexSpec, options) { + const key = new Map(); + const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; + // Iterate through array and handle different types + for (const spec of indexSpecs) { + if (typeof spec === 'string') { + key.set(spec, 1); + } + else if (Array.isArray(spec)) { + key.set(spec[0], spec[1] ?? 1); + } + else if (spec instanceof Map) { + for (const [property, value] of spec) { + key.set(property, value); + } + } + else if ((0, utils_1.isObject)(spec)) { + for (const [property, value] of Object.entries(spec)) { + key.set(property, value); + } + } + } + return { ...options, key }; +} +/** @internal */ +class IndexesOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + get commandName() { + return 'listIndexes'; + } + async execute(_server, session) { + const coll = this.collection; + const options = this.options; + return (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { + full: true, + ...options, + readPreference: this.readPreference, + session + }); + } +} +exports.IndexesOperation = IndexesOperation; +/** @internal */ +class CreateIndexesOperation extends command_1.CommandOperation { + constructor(parent, collectionName, indexes, options) { + super(parent, options); + this.options = options ?? {}; + this.collectionName = collectionName; + this.indexes = indexes.map(userIndex => { + // Ensure the key is a Map to preserve index key ordering + const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); + const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join('_'); + const validIndexOptions = Object.fromEntries(Object.entries({ ...userIndex }).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName))); + return { + ...validIndexOptions, + name, + key + }; + }); + } + get commandName() { + return 'createIndexes'; + } + async execute(server, session) { + const options = this.options; + const indexes = this.indexes; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const cmd = { createIndexes: this.collectionName, indexes }; + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + throw new error_1.MongoCompatibilityError('Option `commitQuorum` for `createIndexes` not supported on servers < 4.4'); + } + cmd.commitQuorum = options.commitQuorum; + } + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + await super.executeCommand(server, session, cmd); + const indexNames = indexes.map(index => index.name || ''); + return indexNames; + } +} +exports.CreateIndexesOperation = CreateIndexesOperation; +/** @internal */ +class CreateIndexOperation extends CreateIndexesOperation { + constructor(parent, collectionName, indexSpec, options) { + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + async execute(server, session) { + const indexNames = await super.execute(server, session); + return indexNames[0]; + } +} +exports.CreateIndexOperation = CreateIndexOperation; +/** @internal */ +class EnsureIndexOperation extends CreateIndexOperation { + constructor(db, collectionName, indexSpec, options) { + super(db, collectionName, indexSpec, options); + this.readPreference = read_preference_1.ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + get commandName() { + return 'listIndexes'; + } + async execute(server, session) { + const indexName = this.indexes[0].name; + const indexes = await this.db + .collection(this.collectionName) + .listIndexes({ session }) + .toArray() + .catch(error => { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) + return []; + throw error; + }); + if (indexName && indexes.some(index => index.name === indexName)) + return indexName; + return super.execute(server, session); + } +} +exports.EnsureIndexOperation = EnsureIndexOperation; +/** @internal */ +class DropIndexOperation extends command_1.CommandOperation { + constructor(collection, indexName, options) { + super(collection, options); + this.options = options ?? {}; + this.collection = collection; + this.indexName = indexName; + } + get commandName() { + return 'dropIndexes'; + } + async execute(server, session) { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + return super.executeCommand(server, session, cmd); + } +} +exports.DropIndexOperation = DropIndexOperation; +/** @internal */ +class ListIndexesOperation extends command_1.CommandOperation { + constructor(collection, options) { + super(collection, options); + this.options = { ...options }; + delete this.options.writeConcern; + this.collectionNamespace = collection.s.namespace; + } + get commandName() { + return 'listIndexes'; + } + async execute(server, session) { + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + const command = { listIndexes: this.collectionNamespace.collection, cursor }; + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (serverWireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + return super.executeCommand(server, session, command); + } +} +exports.ListIndexesOperation = ListIndexesOperation; +/** @internal */ +class IndexExistsOperation extends operation_1.AbstractOperation { + constructor(collection, indexes, options) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + get commandName() { + return 'listIndexes'; + } + async execute(server, session) { + const coll = this.collection; + const indexes = this.indexes; + const info = await (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { + ...this.options, + readPreference: this.readPreference, + session + }); + // Let's check for the index names + if (!Array.isArray(indexes)) + return info[indexes] != null; + // All keys found return true + return indexes.every(indexName => info[indexName] != null); + } +} +exports.IndexExistsOperation = IndexExistsOperation; +/** @internal */ +class IndexInformationOperation extends operation_1.AbstractOperation { + constructor(db, name, options) { + super(options); + this.options = options ?? {}; + this.db = db; + this.name = name; + } + get commandName() { + return 'listIndexes'; + } + async execute(server, session) { + const db = this.db; + const name = this.name; + return (0, common_functions_1.indexInformation)(db, name, { + ...this.options, + readPreference: this.readPreference, + session + }); + } +} +exports.IndexInformationOperation = IndexInformationOperation; +(0, operation_1.defineAspects)(ListIndexesOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +(0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(CreateIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(EnsureIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=indexes.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/indexes.js.map b/nodejs/node_modules/mongodb/lib/operations/indexes.js.map new file mode 100644 index 00000000..73ff4469 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"indexes.js","sourceRoot":"","sources":["../../src/operations/indexes.ts"],"names":[],"mappings":";;;AAGA,oCAAoF;AAEpF,wDAAoD;AAGpD,oCAA2E;AAC3E,uCAKmB;AACnB,yDAAoF;AACpF,2CAAuE;AAEvE,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,YAAY;IACZ,QAAQ;IACR,MAAM;IACN,yBAAyB;IACzB,QAAQ;IACR,QAAQ;IACR,oBAAoB;IACpB,eAAe;IACf,WAAW;IACX,SAAS;IAET,eAAe;IACf,SAAS;IACT,kBAAkB;IAClB,mBAAmB;IACnB,kBAAkB;IAElB,oBAAoB;IACpB,sBAAsB;IAEtB,aAAa;IACb,MAAM;IACN,KAAK;IACL,KAAK;IAEL,sBAAsB;IACtB,YAAY;IAEZ,mBAAmB;IACnB,oBAAoB;CACrB,CAAC,CAAC;AAaH,SAAS,gBAAgB,CAAC,CAAU;IAClC,OAAO,CACL,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,UAAU,IAAI,CAAC,KAAK,MAAM,IAAI,CAAC,KAAK,aAAa,CAC/F,CAAC;AACJ,CAAC;AA8ED,SAAS,kBAAkB,CAAC,CAAU;IACpC,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACtE,CAAC;AAED,SAAS,aAAa,CACpB,SAA6B,EAC7B,OAA8B;IAE9B,MAAM,GAAG,GAAgC,IAAI,GAAG,EAAE,CAAC;IAEnD,MAAM,UAAU,GACd,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,kBAAkB,CAAC,SAAS,CAAC,CAAC,CAAC,CA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,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9D,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/insert.js b/nodejs/node_modules/mongodb/lib/operations/insert.js new file mode 100644 index 00000000..ddd53913 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/insert.js @@ -0,0 +1,101 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InsertManyOperation = exports.InsertOneOperation = exports.InsertOperation = void 0; +const error_1 = require("../error"); +const write_concern_1 = require("../write_concern"); +const bulk_write_1 = require("./bulk_write"); +const command_1 = require("./command"); +const common_functions_1 = require("./common_functions"); +const operation_1 = require("./operation"); +/** @internal */ +class InsertOperation extends command_1.CommandOperation { + constructor(ns, documents, options) { + super(undefined, options); + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns; + this.documents = documents; + } + get commandName() { + return 'insert'; + } + async execute(server, session) { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + return super.executeCommand(server, session, command); + } +} +exports.InsertOperation = InsertOperation; +class InsertOneOperation extends InsertOperation { + constructor(collection, doc, options) { + super(collection.s.namespace, (0, common_functions_1.maybeAddIdToDocuments)(collection, [doc], options), options); + } + async execute(server, session) { + const res = await super.execute(server, session); + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + throw new error_1.MongoServerError(res.writeErrors[0]); + } + return { + acknowledged: this.writeConcern?.w !== 0, + insertedId: this.documents[0]._id + }; + } +} +exports.InsertOneOperation = InsertOneOperation; +/** @internal */ +class InsertManyOperation extends operation_1.AbstractOperation { + constructor(collection, docs, options) { + super(options); + if (!Array.isArray(docs)) { + throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents'); + } + this.options = options; + this.collection = collection; + this.docs = docs; + } + get commandName() { + return 'insert'; + } + async execute(server, session) { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + const bulkWriteOperation = new bulk_write_1.BulkWriteOperation(coll, this.docs.map(document => ({ + insertOne: { document } + })), options); + try { + const res = await bulkWriteOperation.execute(server, session); + return { + acknowledged: writeConcern?.w !== 0, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }; + } + catch (err) { + if (err && err.message === 'Operation must be an object with an operation key') { + throw new error_1.MongoInvalidArgumentError('Collection.insertMany() cannot be called with an array that has null/undefined values'); + } + throw err; + } + } +} +exports.InsertManyOperation = InsertManyOperation; +(0, operation_1.defineAspects)(InsertOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(InsertOneOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(InsertManyOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=insert.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/insert.js.map b/nodejs/node_modules/mongodb/lib/operations/insert.js.map new file mode 100644 index 00000000..6dfa8ba9 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/insert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"insert.js","sourceRoot":"","sources":["../../src/operations/insert.ts"],"names":[],"mappings":";;;AAGA,oCAAuE;AAKvE,oDAAgD;AAChD,6CAAkD;AAClD,uCAA2E;AAC3E,yDAA2D;AAC3D,2CAAuE;AAEvE,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BA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OAAO,EAAE,GAAG,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAC9F,MAAM,YAAY,GAAG,4BAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACvD,MAAM,kBAAkB,GAAG,IAAI,+BAAkB,CAC/C,IAAI,EACJ,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;YACzB,SAAS,EAAE,EAAE,QAAQ,EAAE;SACxB,CAAC,CAAC,EACH,OAAO,CACR,CAAC;QAEF,IAAI;YACF,MAAM,GAAG,GAAG,MAAM,kBAAkB,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YAC9D,OAAO;gBACL,YAAY,EAAE,YAAY,EAAE,CAAC,KAAK,CAAC;gBACnC,aAAa,EAAE,GAAG,CAAC,aAAa;gBAChC,WAAW,EAAE,GAAG,CAAC,WAAW;aAC7B,CAAC;SACH;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,mDAAmD,EAAE;gBAC9E,MAAM,IAAI,iCAAyB,CACjC,uFAAuF,CACxF,CAAC;aACH;YACD,MAAM,GAAG,CAAC;SACX;IACH,CAAC;CACF;AApDD,kDAoDC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC3E,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AAC9E,IAAA,yBAAa,EAAC,mBAAmB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/is_capped.js b/nodejs/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 00000000..5ba90d0c --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IsCappedOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +/** @internal */ +class IsCappedOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + get commandName() { + return 'listCollections'; + } + async execute(server, session) { + const coll = this.collection; + const [collection] = await coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray(); + if (collection == null || collection.options == null) { + throw new error_1.MongoAPIError(`collection ${coll.namespace} not found`); + } + return !!collection.options?.capped; + } +} +exports.IsCappedOperation = IsCappedOperation; +//# sourceMappingURL=is_capped.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/is_capped.js.map b/nodejs/node_modules/mongodb/lib/operations/is_capped.js.map new file mode 100644 index 00000000..7e4efd7d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/is_capped.js.map @@ -0,0 +1 @@ +{"version":3,"file":"is_capped.js","sourceRoot":"","sources":["../../src/operations/is_capped.ts"],"names":[],"mappings":";;;AACA,oCAAyC;AAGzC,2CAAuE;AAEvE,gBAAgB;AAChB,MAAa,iBAAkB,SAAQ,6BAA0B;IAI/D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,iBAA0B,CAAC;IACpC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,CAAC,UAAU,CAAC,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,EAAE;aACjC,eAAe,CACd,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,EAC7B,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CACnF;aACA,OAAO,EAAE,CAAC;QACb,IAAI,UAAU,IAAI,IAAI,IAAI,UAAU,CAAC,OAAO,IAAI,IAAI,EAAE;YACpD,MAAM,IAAI,qBAAa,CAAC,cAAc,IAAI,CAAC,SAAS,YAAY,CAAC,CAAC;SACnE;QACD,OAAO,CAAC,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IACtC,CAAC;CACF;AA3BD,8CA2BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/kill_cursors.js b/nodejs/node_modules/mongodb/lib/operations/kill_cursors.js new file mode 100644 index 00000000..f3db44d1 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/kill_cursors.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.KillCursorsOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +class KillCursorsOperation extends operation_1.AbstractOperation { + constructor(cursorId, ns, server, options) { + super(options); + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + get commandName() { + return 'killCursors'; + } + async execute(server, session) { + if (server !== this.server) { + throw new error_1.MongoRuntimeError('Killcursor must run on the same server operation began on'); + } + const killCursors = this.ns.collection; + if (killCursors == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + throw new error_1.MongoRuntimeError('A collection name must be determined before killCursors'); + } + const killCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + try { + await server.command(this.ns, killCursorsCommand, { session }); + } + catch { + // The driver should never emit errors from killCursors, this is spec-ed behavior + } + } +} +exports.KillCursorsOperation = KillCursorsOperation; +(0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]); +//# sourceMappingURL=kill_cursors.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/kill_cursors.js.map b/nodejs/node_modules/mongodb/lib/operations/kill_cursors.js.map new file mode 100644 index 00000000..177b11a7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/kill_cursors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"kill_cursors.js","sourceRoot":"","sources":["../../src/operations/kill_cursors.ts"],"names":[],"mappings":";;;AACA,oCAA6C;AAI7C,2CAA8F;AAY9F,MAAa,oBAAqB,SAAQ,6BAAiB;IAGzD,YAAY,QAAc,EAAE,EAAoB,EAAE,MAAc,EAAE,OAAyB;QACzF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,aAAsB,CAAC;IAChC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,IAAI,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE;YAC1B,MAAM,IAAI,yBAAiB,CAAC,2DAA2D,CAAC,CAAC;SAC1F;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC;QACvC,IAAI,WAAW,IAAI,IAAI,EAAE;YACvB,gEAAgE;YAChE,wFAAwF;YACxF,MAAM,IAAI,yBAAiB,CAAC,yDAAyD,CAAC,CAAC;SACxF;QAED,MAAM,kBAAkB,GAAuB;YAC7C,WAAW;YACX,OAAO,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC;SACzB,CAAC;QACF,IAAI;YACF,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,kBAAkB,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;SAChE;QAAC,MAAM;YACN,iFAAiF;SAClF;IACH,CAAC;CACF;AApCD,oDAoCC;AAED,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/list_collections.js b/nodejs/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 00000000..398c4cd7 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/list_collections.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListCollectionsOperation = void 0; +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class ListCollectionsOperation extends command_1.CommandOperation { + constructor(db, filter, options) { + super(db, options); + this.options = { ...options }; + delete this.options.writeConcern; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + this.authorizedCollections = !!this.options.authorizedCollections; + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + get commandName() { + return 'listCollections'; + } + async execute(server, session) { + return super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server))); + } + /* This is here for the purpose of unit testing the final command that gets sent. */ + generateCommand(wireVersion) { + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly, + authorizedCollections: this.authorizedCollections + }; + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (wireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + return command; + } +} +exports.ListCollectionsOperation = ListCollectionsOperation; +(0, operation_1.defineAspects)(ListCollectionsOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=list_collections.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/list_collections.js.map b/nodejs/node_modules/mongodb/lib/operations/list_collections.js.map new file mode 100644 index 00000000..1addfb0d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/list_collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_collections.js","sourceRoot":"","sources":["../../src/operations/list_collections.ts"],"names":[],"mappings":";;;AAIA,oCAA0C;AAC1C,uCAA2E;AAC3E,2CAAoD;AAYpD,gBAAgB;AAChB,MAAa,wBAAyB,SAAQ,0BAA0B;IAetE,YAAY,EAAM,EAAE,MAAgB,EAAE,OAAgC;QACpE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;QACjC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;QACxC,IAAI,CAAC,qBAAqB,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,CAAC;QAElE,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACzC;IACH,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,iBAA0B,CAAC;IACpC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,OAAO,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,eAAe,CAAC,IAAA,sBAAc,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC7F,CAAC;IAED,oFAAoF;IACpF,eAAe,CAAC,WAAmB;QACjC,MAAM,OAAO,GAAa;YACxB,eAAe,EAAE,CAAC;YAClB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE;YAC3D,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;SAClD,CAAC;QAEF,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,WAAW,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YAC1D,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACxC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AAxDD,4DAwDC;AAcD,IAAA,yBAAa,EAAC,wBAAwB,EAAE;IACtC,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/list_databases.js b/nodejs/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 00000000..f0159bf8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/list_databases.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListDatabasesOperation = void 0; +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class ListDatabasesOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options ?? {}; + this.ns = new utils_1.MongoDBNamespace('admin', '$cmd'); + } + get commandName() { + return 'listDatabases'; + } + async execute(server, session) { + const cmd = { listDatabases: 1 }; + if (typeof this.options.nameOnly === 'boolean') { + cmd.nameOnly = this.options.nameOnly; + } + if (this.options.filter) { + cmd.filter = this.options.filter; + } + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if ((0, utils_1.maxWireVersion)(server) >= 9 && this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + return super.executeCommand(server, session, cmd); + } +} +exports.ListDatabasesOperation = ListDatabasesOperation; +(0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=list_databases.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/list_databases.js.map b/nodejs/node_modules/mongodb/lib/operations/list_databases.js.map new file mode 100644 index 00000000..cc5d042b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/list_databases.js.map @@ -0,0 +1 @@ +{"version":3,"file":"list_databases.js","sourceRoot":"","sources":["../../src/operations/list_databases.ts"],"names":[],"mappings":";;;AAKA,oCAA4D;AAC5D,uCAA2E;AAC3E,2CAAoD;AAoBpD,gBAAgB;AAChB,MAAa,sBAAuB,SAAQ,0BAAqC;IAG/E,YAAY,EAAM,EAAE,OAA8B;QAChD,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAClD,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,eAAwB,CAAC;IAClC,CAAC;IAEQ,KAAK,CAAC,OAAO,CACpB,MAAc,EACd,OAAkC;QAElC,MAAM,GAAG,GAAa,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC;QAE3C,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,KAAK,SAAS,EAAE;YAC9C,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;SACtC;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YACvB,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;SAClC;QAED,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE;YACzD,GAAG,CAAC,mBAAmB,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC;SAC5D;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,IAAA,sBAAc,EAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACrE,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACpC;QAED,OAAO,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,CAAmB,CAAC;IACtE,CAAC;CACF;AAvCD,wDAuCC;AAED,IAAA,yBAAa,EAAC,sBAAsB,EAAE,CAAC,kBAAM,CAAC,cAAc,EAAE,kBAAM,CAAC,SAAS,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/operation.js b/nodejs/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 00000000..1f165abe --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defineAspects = exports.AbstractOperation = exports.Aspect = void 0; +const bson_1 = require("../bson"); +const read_preference_1 = require("../read_preference"); +exports.Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING'), + MUST_SELECT_SAME_SERVER: Symbol('MUST_SELECT_SAME_SERVER') +}; +/** @internal */ +const kSession = Symbol('session'); +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + * @internal + */ +class AbstractOperation { + constructor(options = {}) { + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) + ? read_preference_1.ReadPreference.primary + : read_preference_1.ReadPreference.fromOptions(options) ?? read_preference_1.ReadPreference.primary; + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = (0, bson_1.resolveBSONOptions)(options); + this[kSession] = options.session != null ? options.session : undefined; + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + this.trySecondaryWrite = false; + } + hasAspect(aspect) { + const ctor = this.constructor; + if (ctor.aspects == null) { + return false; + } + return ctor.aspects.has(aspect); + } + get session() { + return this[kSession]; + } + clearSession() { + this[kSession] = undefined; + } + get canRetryRead() { + return true; + } + get canRetryWrite() { + return true; + } +} +exports.AbstractOperation = AbstractOperation; +function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + return aspects; +} +exports.defineAspects = defineAspects; +//# sourceMappingURL=operation.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/operation.js.map b/nodejs/node_modules/mongodb/lib/operations/operation.js.map new file mode 100644 index 00000000..e61af171 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"operation.js","sourceRoot":"","sources":["../../src/operations/operation.ts"],"names":[],"mappings":";;;AAAA,kCAAuF;AACvF,wDAA6E;AAKhE,QAAA,MAAM,GAAG;IACpB,cAAc,EAAE,MAAM,CAAC,gBAAgB,CAAC;IACxC,eAAe,EAAE,MAAM,CAAC,iBAAiB,CAAC;IAC1C,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC;IAC9B,WAAW,EAAE,MAAM,CAAC,aAAa,CAAC;IAClC,cAAc,EAA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;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,aAAa;QACf,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA3DD,8CA2DC;AAED,SAAgB,aAAa,CAC3B,SAA+B,EAC/B,OAAwC;IAExC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,YAAY,GAAG,CAAC,EAAE;QACxD,OAAO,GAAG,CAAC,OAAO,CAAC,CAAC;KACrB;IAED,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC3B,MAAM,CAAC,cAAc,CAAC,SAAS,EAAE,SAAS,EAAE;QAC1C,KAAK,EAAE,OAAO;QACd,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAfD,sCAeC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/options_operation.js b/nodejs/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 00000000..6cc24922 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OptionsOperation = void 0; +const error_1 = require("../error"); +const operation_1 = require("./operation"); +/** @internal */ +class OptionsOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + get commandName() { + return 'listCollections'; + } + async execute(server, session) { + const coll = this.collection; + const [collection] = await coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray(); + if (collection == null || collection.options == null) { + throw new error_1.MongoAPIError(`collection ${coll.namespace} not found`); + } + return collection.options; + } +} +exports.OptionsOperation = OptionsOperation; +//# sourceMappingURL=options_operation.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/options_operation.js.map b/nodejs/node_modules/mongodb/lib/operations/options_operation.js.map new file mode 100644 index 00000000..dd8af646 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/options_operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"options_operation.js","sourceRoot":"","sources":["../../src/operations/options_operation.ts"],"names":[],"mappings":";;;AAEA,oCAAyC;AAGzC,2CAAuE;AAEvE,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAA2B;IAI/D,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IACD,IAAa,WAAW;QACtB,OAAO,iBAA0B,CAAC;IACpC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,CAAC,UAAU,CAAC,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,EAAE;aACjC,eAAe,CACd,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,EAC7B,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CACnF;aACA,OAAO,EAAE,CAAC;QACb,IAAI,UAAU,IAAI,IAAI,IAAI,UAAU,CAAC,OAAO,IAAI,IAAI,EAAE;YACpD,MAAM,IAAI,qBAAa,CAAC,cAAc,IAAI,CAAC,SAAS,YAAY,CAAC,CAAC;SACnE;QACD,OAAO,UAAU,CAAC,OAAO,CAAC;IAC5B,CAAC;CACF;AA1BD,4CA0BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/profiling_level.js b/nodejs/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 00000000..6bf7275b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/profiling_level.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProfilingLevelOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +/** @internal */ +class ProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + get commandName() { + return 'profile'; + } + async execute(server, session) { + const doc = await super.executeCommand(server, session, { profile: -1 }); + if (doc.ok === 1) { + const was = doc.was; + if (was === 0) + return 'off'; + if (was === 1) + return 'slow_only'; + if (was === 2) + return 'all'; + throw new error_1.MongoUnexpectedServerResponseError(`Illegal profiling level value ${was}`); + } + else { + throw new error_1.MongoUnexpectedServerResponseError('Error with profile command'); + } + } +} +exports.ProfilingLevelOperation = ProfilingLevelOperation; +//# sourceMappingURL=profiling_level.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/profiling_level.js.map b/nodejs/node_modules/mongodb/lib/operations/profiling_level.js.map new file mode 100644 index 00000000..1dd9fc50 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/profiling_level.js.map @@ -0,0 +1 @@ +{"version":3,"file":"profiling_level.js","sourceRoot":"","sources":["../../src/operations/profiling_level.ts"],"names":[],"mappings":";;;AACA,oCAA8D;AAG9D,uCAA2E;AAK3E,gBAAgB;AAChB,MAAa,uBAAwB,SAAQ,0BAAwB;IAGnE,YAAY,EAAM,EAAE,OAA8B;QAChD,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,SAAkB,CAAC;IAC5B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACzE,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE;YAChB,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;YACpB,IAAI,GAAG,KAAK,CAAC;gBAAE,OAAO,KAAK,CAAC;YAC5B,IAAI,GAAG,KAAK,CAAC;gBAAE,OAAO,WAAW,CAAC;YAClC,IAAI,GAAG,KAAK,CAAC;gBAAE,OAAO,KAAK,CAAC;YAC5B,MAAM,IAAI,0CAAkC,CAAC,iCAAiC,GAAG,EAAE,CAAC,CAAC;SACtF;aAAM;YACL,MAAM,IAAI,0CAAkC,CAAC,4BAA4B,CAAC,CAAC;SAC5E;IACH,CAAC;CACF;AAxBD,0DAwBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/remove_user.js b/nodejs/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 00000000..7c2dd024 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/remove_user.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoveUserOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class RemoveUserOperation extends command_1.CommandOperation { + constructor(db, username, options) { + super(db, options); + this.options = options; + this.username = username; + } + get commandName() { + return 'dropUser'; + } + async execute(server, session) { + await super.executeCommand(server, session, { dropUser: this.username }); + return true; + } +} +exports.RemoveUserOperation = RemoveUserOperation; +(0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=remove_user.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/remove_user.js.map b/nodejs/node_modules/mongodb/lib/operations/remove_user.js.map new file mode 100644 index 00000000..963ce6d3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/remove_user.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remove_user.js","sourceRoot":"","sources":["../../src/operations/remove_user.ts"],"names":[],"mappings":";;;AAGA,uCAA2E;AAC3E,2CAAoD;AAKpD,gBAAgB;AAChB,MAAa,mBAAoB,SAAQ,0BAAyB;IAIhE,YAAY,EAAM,EAAE,QAAgB,EAAE,OAA0B;QAC9D,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,UAAmB,CAAC;IAC7B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QACzE,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlBD,kDAkBC;AAED,IAAA,yBAAa,EAAC,mBAAmB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/rename.js b/nodejs/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 00000000..e31642a2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/rename.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RenameOperation = void 0; +const collection_1 = require("../collection"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class RenameOperation extends command_1.CommandOperation { + constructor(collection, newName, options) { + super(collection, options); + this.collection = collection; + this.newName = newName; + this.options = options; + this.ns = new utils_1.MongoDBNamespace('admin', '$cmd'); + } + get commandName() { + return 'renameCollection'; + } + async execute(server, session) { + // Build the command + const renameCollection = this.collection.namespace; + const toCollection = this.collection.s.namespace.withCollection(this.newName).toString(); + const dropTarget = typeof this.options.dropTarget === 'boolean' ? this.options.dropTarget : false; + const command = { + renameCollection: renameCollection, + to: toCollection, + dropTarget: dropTarget + }; + await super.executeCommand(server, session, command); + return new collection_1.Collection(this.collection.s.db, this.newName, this.collection.s.options); + } +} +exports.RenameOperation = RenameOperation; +(0, operation_1.defineAspects)(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=rename.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/rename.js.map b/nodejs/node_modules/mongodb/lib/operations/rename.js.map new file mode 100644 index 00000000..a5e6f430 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/rename.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rename.js","sourceRoot":"","sources":["../../src/operations/rename.ts"],"names":[],"mappings":";;;AACA,8CAA2C;AAG3C,oCAA4C;AAC5C,uCAA2E;AAC3E,2CAAoD;AAUpD,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA0B;IAC7D,YACS,UAAsB,EACtB,OAAe,EACN,OAAsB;QAEtC,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAJpB,eAAU,GAAV,UAAU,CAAY;QACtB,YAAO,GAAP,OAAO,CAAQ;QACN,YAAO,GAAP,OAAO,CAAe;QAGtC,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAClD,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,kBAA2B,CAAC;IACrC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,oBAAoB;QACpB,MAAM,gBAAgB,GAAG,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;QACnD,MAAM,YAAY,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;QACzF,MAAM,UAAU,GACd,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC;QAEjF,MAAM,OAAO,GAAG;YACd,gBAAgB,EAAE,gBAAgB;YAClC,EAAE,EAAE,YAAY;YAChB,UAAU,EAAE,UAAU;SACvB,CAAC;QAEF,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QACrD,OAAO,IAAI,uBAAU,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACvF,CAAC;CACF;AA9BD,0CA8BC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/run_command.js b/nodejs/node_modules/mongodb/lib/operations/run_command.js new file mode 100644 index 00000000..8aaedcc3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/run_command.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RunAdminCommandOperation = exports.RunCommandOperation = void 0; +const utils_1 = require("../utils"); +const operation_1 = require("./operation"); +/** @internal */ +class RunCommandOperation extends operation_1.AbstractOperation { + constructor(parent, command, options) { + super(options); + this.command = command; + this.options = options; + this.ns = parent.s.namespace.withCollection('$cmd'); + } + get commandName() { + return 'runCommand'; + } + async execute(server, session) { + this.server = server; + return server.command(this.ns, this.command, { + ...this.options, + readPreference: this.readPreference, + session + }); + } +} +exports.RunCommandOperation = RunCommandOperation; +class RunAdminCommandOperation extends operation_1.AbstractOperation { + constructor(command, options) { + super(options); + this.command = command; + this.options = options; + this.ns = new utils_1.MongoDBNamespace('admin', '$cmd'); + } + get commandName() { + return 'runCommand'; + } + async execute(server, session) { + this.server = server; + return server.command(this.ns, this.command, { + ...this.options, + readPreference: this.readPreference, + session + }); + } +} +exports.RunAdminCommandOperation = RunAdminCommandOperation; +//# sourceMappingURL=run_command.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/run_command.js.map b/nodejs/node_modules/mongodb/lib/operations/run_command.js.map new file mode 100644 index 00000000..1eeaa926 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/run_command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"run_command.js","sourceRoot":"","sources":["../../src/operations/run_command.ts"],"names":[],"mappings":";;;AAMA,oCAA4C;AAC5C,2CAAgD;AAUhD,gBAAgB;AAChB,MAAa,mBAAkC,SAAQ,6BAAoB;IACzE,YAAY,MAAU,EAAS,OAAiB,EAAkB,OAA0B;QAC1F,KAAK,CAAC,OAAO,CAAC,CAAC;QADc,YAAO,GAAP,OAAO,CAAU;QAAkB,YAAO,GAAP,OAAO,CAAmB;QAE1F,IAAI,CAAC,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;IACtD,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,YAAqB,CAAC;IAC/B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE;YAC3C,GAAG,IAAI,CAAC,OAAO;YACf,cAAc,EAAE,IAAI,CAAC,cAAc;YACnC,OAAO;SACR,CAAmB,CAAC;IACvB,CAAC;CACF;AAlBD,kDAkBC;AAED,MAAa,wBAAuC,SAAQ,6BAAoB;IAC9E,YACS,OAAiB,EACR,OAGf;QAED,KAAK,CAAC,OAAO,CAAC,CAAC;QANR,YAAO,GAAP,OAAO,CAAU;QACR,YAAO,GAAP,OAAO,CAGtB;QAGD,IAAI,CAAC,EAAE,GAAG,IAAI,wBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAClD,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,YAAqB,CAAC;IAC/B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE;YAC3C,GAAG,IAAI,CAAC,OAAO;YACf,cAAc,EAAE,IAAI,CAAC,cAAc;YACnC,OAAO;SACR,CAAmB,CAAC;IACvB,CAAC;CACF;AAxBD,4DAwBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/search_indexes/create.js b/nodejs/node_modules/mongodb/lib/operations/search_indexes/create.js new file mode 100644 index 00000000..9707f226 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/search_indexes/create.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateSearchIndexesOperation = void 0; +const operation_1 = require("../operation"); +/** @internal */ +class CreateSearchIndexesOperation extends operation_1.AbstractOperation { + constructor(collection, descriptions) { + super(); + this.collection = collection; + this.descriptions = descriptions; + } + get commandName() { + return 'createSearchIndexes'; + } + async execute(server, session) { + const namespace = this.collection.fullNamespace; + const command = { + createSearchIndexes: namespace.collection, + indexes: this.descriptions + }; + const res = await server.command(namespace, command, { session }); + const indexesCreated = res?.indexesCreated ?? []; + return indexesCreated.map(({ name }) => name); + } +} +exports.CreateSearchIndexesOperation = CreateSearchIndexesOperation; +//# sourceMappingURL=create.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/search_indexes/create.js.map b/nodejs/node_modules/mongodb/lib/operations/search_indexes/create.js.map new file mode 100644 index 00000000..24a0363b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/search_indexes/create.js.map @@ -0,0 +1 @@ +{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../src/operations/search_indexes/create.ts"],"names":[],"mappings":";;;AAKA,4CAAiD;AAajD,gBAAgB;AAChB,MAAa,4BAA6B,SAAQ,6BAA2B;IAC3E,YACmB,UAAsB,EACtB,YAAmD;QAEpE,KAAK,EAAE,CAAC;QAHS,eAAU,GAAV,UAAU,CAAY;QACtB,iBAAY,GAAZ,YAAY,CAAuC;IAGtE,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,qBAA8B,CAAC;IACxC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAChD,MAAM,OAAO,GAAG;YACd,mBAAmB,EAAE,SAAS,CAAC,UAAU;YACzC,OAAO,EAAE,IAAI,CAAC,YAAY;SAC3B,CAAC;QAEF,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;QAElE,MAAM,cAAc,GAA4B,GAAG,EAAE,cAAc,IAAI,EAAE,CAAC;QAC1E,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;CACF;AAxBD,oEAwBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/search_indexes/drop.js b/nodejs/node_modules/mongodb/lib/operations/search_indexes/drop.js new file mode 100644 index 00000000..494d65c2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/search_indexes/drop.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DropSearchIndexOperation = void 0; +const error_1 = require("../../error"); +const operation_1 = require("../operation"); +/** @internal */ +class DropSearchIndexOperation extends operation_1.AbstractOperation { + constructor(collection, name) { + super(); + this.collection = collection; + this.name = name; + } + get commandName() { + return 'dropSearchIndex'; + } + async execute(server, session) { + const namespace = this.collection.fullNamespace; + const command = { + dropSearchIndex: namespace.collection + }; + if (typeof this.name === 'string') { + command.name = this.name; + } + try { + await server.command(namespace, command, { session }); + } + catch (error) { + const isNamespaceNotFoundError = error instanceof error_1.MongoServerError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound; + if (!isNamespaceNotFoundError) { + throw error; + } + } + } +} +exports.DropSearchIndexOperation = DropSearchIndexOperation; +//# sourceMappingURL=drop.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/search_indexes/drop.js.map b/nodejs/node_modules/mongodb/lib/operations/search_indexes/drop.js.map new file mode 100644 index 00000000..376bb8df --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/search_indexes/drop.js.map @@ -0,0 +1 @@ +{"version":3,"file":"drop.js","sourceRoot":"","sources":["../../../src/operations/search_indexes/drop.ts"],"names":[],"mappings":";;;AAGA,uCAAoE;AAGpE,4CAAiD;AAEjD,gBAAgB;AAChB,MAAa,wBAAyB,SAAQ,6BAAuB;IACnE,YAA6B,UAAsB,EAAmB,IAAY;QAChF,KAAK,EAAE,CAAC;QADmB,eAAU,GAAV,UAAU,CAAY;QAAmB,SAAI,GAAJ,IAAI,CAAQ;IAElF,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,iBAA0B,CAAC;IACpC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAEhD,MAAM,OAAO,GAAa;YACxB,eAAe,EAAE,SAAS,CAAC,UAAU;SACtC,CAAC;QAEF,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;YACjC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;SAC1B;QAED,IAAI;YACF,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;SACvD;QAAC,OAAO,KAAK,EAAE;YACd,MAAM,wBAAwB,GAC5B,KAAK,YAAY,wBAAgB,IAAI,KAAK,CAAC,IAAI,KAAK,2BAAmB,CAAC,iBAAiB,CAAC;YAC5F,IAAI,CAAC,wBAAwB,EAAE;gBAC7B,MAAM,KAAK,CAAC;aACb;SACF;IACH,CAAC;CACF;AA9BD,4DA8BC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/search_indexes/update.js b/nodejs/node_modules/mongodb/lib/operations/search_indexes/update.js new file mode 100644 index 00000000..673c100b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/search_indexes/update.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UpdateSearchIndexOperation = void 0; +const operation_1 = require("../operation"); +/** @internal */ +class UpdateSearchIndexOperation extends operation_1.AbstractOperation { + constructor(collection, name, definition) { + super(); + this.collection = collection; + this.name = name; + this.definition = definition; + } + get commandName() { + return 'updateSearchIndex'; + } + async execute(server, session) { + const namespace = this.collection.fullNamespace; + const command = { + updateSearchIndex: namespace.collection, + name: this.name, + definition: this.definition + }; + await server.command(namespace, command, { session }); + return; + } +} +exports.UpdateSearchIndexOperation = UpdateSearchIndexOperation; +//# sourceMappingURL=update.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/search_indexes/update.js.map b/nodejs/node_modules/mongodb/lib/operations/search_indexes/update.js.map new file mode 100644 index 00000000..865d2b76 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/search_indexes/update.js.map @@ -0,0 +1 @@ +{"version":3,"file":"update.js","sourceRoot":"","sources":["../../../src/operations/search_indexes/update.ts"],"names":[],"mappings":";;;AAKA,4CAAiD;AAEjD,gBAAgB;AAChB,MAAa,0BAA2B,SAAQ,6BAAuB;IACrE,YACmB,UAAsB,EACtB,IAAY,EACZ,UAAoB;QAErC,KAAK,EAAE,CAAC;QAJS,eAAU,GAAV,UAAU,CAAY;QACtB,SAAI,GAAJ,IAAI,CAAQ;QACZ,eAAU,GAAV,UAAU,CAAU;IAGvC,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,mBAA4B,CAAC;IACtC,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAChD,MAAM,OAAO,GAAG;YACd,iBAAiB,EAAE,SAAS,CAAC,UAAU;YACvC,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC;QAEF,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;QACtD,OAAO;IACT,CAAC;CACF;AAxBD,gEAwBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/set_profiling_level.js b/nodejs/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 00000000..becae11b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/set_profiling_level.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SetProfilingLevelOperation = exports.ProfilingLevel = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const levelValues = new Set(['off', 'slow_only', 'all']); +/** @public */ +exports.ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +}); +/** @internal */ +class SetProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, level, options) { + super(db, options); + this.options = options; + switch (level) { + case exports.ProfilingLevel.off: + this.profile = 0; + break; + case exports.ProfilingLevel.slowOnly: + this.profile = 1; + break; + case exports.ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; + } + this.level = level; + } + get commandName() { + return 'profile'; + } + async execute(server, session) { + const level = this.level; + if (!levelValues.has(level)) { + throw new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${(0, utils_1.enumToString)(exports.ProfilingLevel)}"`); + } + // TODO(NODE-3483): Determine error to put here + await super.executeCommand(server, session, { profile: this.profile }); + return level; + } +} +exports.SetProfilingLevelOperation = SetProfilingLevelOperation; +//# sourceMappingURL=set_profiling_level.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/set_profiling_level.js.map b/nodejs/node_modules/mongodb/lib/operations/set_profiling_level.js.map new file mode 100644 index 00000000..e149b97f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/set_profiling_level.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set_profiling_level.js","sourceRoot":"","sources":["../../src/operations/set_profiling_level.ts"],"names":[],"mappings":";;;AACA,oCAAqD;AAGrD,oCAAwC;AACxC,uCAA2E;AAE3E,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AAEzD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,GAAG,EAAE,KAAK;IACV,QAAQ,EAAE,WAAW;IACrB,GAAG,EAAE,KAAK;CACF,CAAC,CAAC;AAQZ,gBAAgB;AAChB,MAAa,0BAA2B,SAAQ,0BAAgC;IAK9E,YAAY,EAAM,EAAE,KAAqB,EAAE,OAAiC;QAC1E,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,QAAQ,KAAK,EAAE;YACb,KAAK,sBAAc,CAAC,GAAG;gBACrB,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR,KAAK,sBAAc,CAAC,QAAQ;gBAC1B,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR,KAAK,sBAAc,CAAC,GAAG;gBACrB,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR;gBACE,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;SACT;QAED,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,SAAkB,CAAC;IAC5B,CAAC;IAEQ,KAAK,CAAC,OAAO,CACpB,MAAc,EACd,OAAkC;QAElC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QAEzB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,iCAAyB,CACjC,mCAAmC,IAAA,oBAAY,EAAC,sBAAc,CAAC,GAAG,CACnE,CAAC;SACH;QAED,+CAA+C;QAC/C,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QACvE,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AA9CD,gEA8CC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/stats.js b/nodejs/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 00000000..412e6100 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/stats.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DbStatsOperation = void 0; +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** @internal */ +class DbStatsOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + get commandName() { + return 'dbStats'; + } + async execute(server, session) { + const command = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + return super.executeCommand(server, session, command); + } +} +exports.DbStatsOperation = DbStatsOperation; +(0, operation_1.defineAspects)(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]); +//# sourceMappingURL=stats.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/stats.js.map b/nodejs/node_modules/mongodb/lib/operations/stats.js.map new file mode 100644 index 00000000..a794d830 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/stats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stats.js","sourceRoot":"","sources":["../../src/operations/stats.ts"],"names":[],"mappings":";;;AAIA,uCAA2E;AAC3E,2CAAoD;AAQpD,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,0BAA0B;IAG9D,YAAY,EAAM,EAAE,OAAuB;QACzC,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,SAAkB,CAAC;IAC5B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,OAAO,GAAa,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;QAC5C,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,IAAI,EAAE;YAC9B,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;SACpC;QAED,OAAO,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;CACF;AApBD,4CAoBC;AAED,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/update.js b/nodejs/node_modules/mongodb/lib/operations/update.js new file mode 100644 index 00000000..da527f2d --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/update.js @@ -0,0 +1,179 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeUpdateStatement = exports.ReplaceOneOperation = exports.UpdateManyOperation = exports.UpdateOneOperation = exports.UpdateOperation = void 0; +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const command_1 = require("./command"); +const operation_1 = require("./operation"); +/** + * @internal + * UpdateOperation is used in bulk write, while UpdateOneOperation and UpdateManyOperation are only used in the collections API + */ +class UpdateOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get commandName() { + return 'update'; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; + } + return this.statements.every(op => op.multi == null || op.multi === false); + } + async execute(server, session) { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (options.let) { + command.let = options.let; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`); + } + } + return super.executeCommand(server, session, command); + } +} +exports.UpdateOperation = UpdateOperation; +/** @internal */ +class UpdateOneOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + async execute(server, session) { + const res = await super.execute(server, session); + if (this.explain != null) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; + } +} +exports.UpdateOneOperation = UpdateOneOperation; +/** @internal */ +class UpdateManyOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + async execute(server, session) { + const res = await super.execute(server, session); + if (this.explain != null) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; + } +} +exports.UpdateManyOperation = UpdateManyOperation; +/** @internal */ +class ReplaceOneOperation extends UpdateOperation { + constructor(collection, filter, replacement, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + async execute(server, session) { + const res = await super.execute(server, session); + if (this.explain != null) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; + } +} +exports.ReplaceOneOperation = ReplaceOneOperation; +function makeUpdateStatement(filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + const op = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + if (options.multi) { + op.multi = options.multi; + } + if (options.hint) { + op.hint = options.hint; + } + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + if (options.collation) { + op.collation = options.collation; + } + return op; +} +exports.makeUpdateStatement = makeUpdateStatement; +(0, operation_1.defineAspects)(UpdateOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION]); +(0, operation_1.defineAspects)(UpdateOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(UpdateManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(ReplaceOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=update.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/update.js.map b/nodejs/node_modules/mongodb/lib/operations/update.js.map new file mode 100644 index 00000000..72c8916a --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/update.js.map @@ -0,0 +1 @@ +{"version":3,"file":"update.js","sourceRoot":"","sources":["../../src/operations/update.ts"],"names":[],"mappings":";;;AAEA,oCAAgG;AAIhG,oCAAqE;AACrE,uCAAkG;AAClG,2CAA+D;AAqD/D;;;GAGG;AACH,MAAa,eAAgB,SAAQ,0BAA0B;IAI7D,YACE,EAAoB,EACpB,UAA6B,EAC7B,OAA8C;QAE9C,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE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B,CAAC,CAAC;AACH,IAAA,yBAAa,EAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC;AACH,IAAA,yBAAa,EAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/validate_collection.js b/nodejs/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 00000000..bed27da2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/validate_collection.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValidateCollectionOperation = void 0; +const error_1 = require("../error"); +const command_1 = require("./command"); +/** @internal */ +class ValidateCollectionOperation extends command_1.CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + const command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + get commandName() { + return 'validate'; + } + async execute(server, session) { + const collectionName = this.collectionName; + const doc = await super.executeCommand(server, session, this.command); + if (doc.result != null && typeof doc.result !== 'string') + throw new error_1.MongoUnexpectedServerResponseError('Error with validation data'); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`); + if (doc.valid != null && !doc.valid) + throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`); + return doc; + } +} +exports.ValidateCollectionOperation = ValidateCollectionOperation; +//# sourceMappingURL=validate_collection.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/operations/validate_collection.js.map b/nodejs/node_modules/mongodb/lib/operations/validate_collection.js.map new file mode 100644 index 00000000..0e549a96 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/operations/validate_collection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validate_collection.js","sourceRoot":"","sources":["../../src/operations/validate_collection.ts"],"names":[],"mappings":";;;AAEA,oCAA8D;AAG9D,uCAA2E;AAQ3E,gBAAgB;AAChB,MAAa,2BAA4B,SAAQ,0BAA0B;IAKzE,YAAY,KAAY,EAAE,cAAsB,EAAE,OAAkC;QAClF,sCAAsC;QACtC,MAAM,OAAO,GAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;QACvD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE;gBACnF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAI,OAAoB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;aACnD;SACF;QAED,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;IAED,IAAa,WAAW;QACtB,OAAO,UAAmB,CAAC;IAC7B,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,MAAc,EAAE,OAAkC;QACvE,MAAM,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;QAE3C,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,IAAI,GAAG,CAAC,MAAM,IAAI,IAAI,IAAI,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ;YACtD,MAAM,IAAI,0CAAkC,CAAC,4BAA4B,CAAC,CAAC;QAC7E,IAAI,GAAG,CAAC,MAAM,IAAI,IAAI,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC,IAAI,IAAI;YACrE,MAAM,IAAI,0CAAkC,CAAC,sBAAsB,cAAc,EAAE,CAAC,CAAC;QACvF,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK;YACjC,MAAM,IAAI,0CAAkC,CAAC,sBAAsB,cAAc,EAAE,CAAC,CAAC;QAEvF,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAtCD,kEAsCC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/read_concern.js b/nodejs/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 00000000..aed3e227 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadConcern = exports.ReadConcernLevel = void 0; +/** @public */ +exports.ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +}); +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level) { + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = exports.ReadConcernLevel[level] ?? level; + } + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options) { + if (options == null) { + return; + } + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } + else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } + else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + if (options.level) { + return new ReadConcern(options.level); + } + return; + } + static get MAJORITY() { + return exports.ReadConcernLevel.majority; + } + static get AVAILABLE() { + return exports.ReadConcernLevel.available; + } + static get LINEARIZABLE() { + return exports.ReadConcernLevel.linearizable; + } + static get SNAPSHOT() { + return exports.ReadConcernLevel.snapshot; + } + toJSON() { + return { level: this.level }; + } +} +exports.ReadConcern = ReadConcern; +//# sourceMappingURL=read_concern.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/read_concern.js.map b/nodejs/node_modules/mongodb/lib/read_concern.js.map new file mode 100644 index 00000000..5df31985 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/read_concern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"read_concern.js","sourceRoot":"","sources":["../src/read_concern.ts"],"names":[],"mappings":";;;AAEA,cAAc;AACD,QAAA,gBAAgB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5C,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,UAAU;IACpB,YAAY,EAAE,cAAc;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;CACZ,CAAC,CAAC;AAQZ;;;;;;GAMG;AACH,MAAa,WAAW;IAGtB,2DAA2D;IAC3D,YAAY,KAAuB;QACjC;;;;;WAKG;QACH,IAAI,CAAC,KAAK,GAAG,wBAAgB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC;IAChD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,OAGlB;QACC,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,OAAO;SACR;QAED,IAAI,OAAO,CAAC,WAAW,EAAE;YACvB,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;YAChC,IAAI,WAAW,YAAY,WAAW,EAAE;gBACtC,OAAO,WAAW,CAAC;aACpB;iBAAM,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;gBAC1C,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC,CAAC;aACrC;iBAAM,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE;gBACtD,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;aAC3C;SACF;QAED,IAAI,OAAO,CAAC,KAAK,EAAE;YACjB,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;SACvC;QACD,OAAO;IACT,CAAC;IAED,MAAM,KAAK,QAAQ;QACjB,OAAO,wBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,MAAM,KAAK,SAAS;QAClB,OAAO,wBAAgB,CAAC,SAAS,CAAC;IACpC,CAAC;IAED,MAAM,KAAK,YAAY;QACrB,OAAO,wBAAgB,CAAC,YAAY,CAAC;IACvC,CAAC;IAED,MAAM,KAAK,QAAQ;QACjB,OAAO,wBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,MAAM;QACJ,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;CACF;AA/DD,kCA+DC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/read_preference.js b/nodejs/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 00000000..d8823991 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,195 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadPreference = exports.ReadPreferenceMode = void 0; +const error_1 = require("./error"); +/** @public */ +exports.ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +}); +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://www.mongodb.com/docs/manual/core/read-preference/ + */ +class ReadPreference { + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } + else if (tags && !Array.isArray(tags)) { + throw new error_1.MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + this.mode = mode; + this.tags = tags; + this.hedge = options?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = options ?? {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new error_1.MongoInvalidArgumentError('maxStalenessSeconds must be a positive integer'); + } + this.maxStalenessSeconds = options.maxStalenessSeconds; + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + if (this.maxStalenessSeconds) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + if (this.hedge) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with hedge'); + } + } + } + // Support the deprecated `preference` property introduced in the porcelain layer + get preference() { + return this.mode; + } + static fromString(mode) { + return new ReadPreference(mode); + } + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options) { + if (!options) + return; + const readPreference = options.readPreference ?? options.session?.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + if (readPreference == null) { + return; + } + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags, { + maxStalenessSeconds: options.maxStalenessSeconds, + hedge: options.hedge + }); + } + else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, readPreference.tags ?? readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } + } + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; + } + return readPreference; + } + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options) { + if (options.readPreference == null) + return options; + const r = options.readPreference; + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } + else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } + else if (!(r instanceof ReadPreference)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r}`); + } + return options; + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode) { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + return VALID_MODES.has(mode); + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + /** + * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire + * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query + */ + secondaryOk() { + const NEEDS_SECONDARYOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + return NEEDS_SECONDARYOK.has(this.mode); + } + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference) { + return readPreference.mode === this.mode; + } + /** Return JSON representation */ + toJSON() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) + readPreference.tags = this.tags; + if (this.maxStalenessSeconds) + readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) + readPreference.hedge = this.hedge; + return readPreference; + } +} +ReadPreference.PRIMARY = exports.ReadPreferenceMode.primary; +ReadPreference.PRIMARY_PREFERRED = exports.ReadPreferenceMode.primaryPreferred; +ReadPreference.SECONDARY = exports.ReadPreferenceMode.secondary; +ReadPreference.SECONDARY_PREFERRED = exports.ReadPreferenceMode.secondaryPreferred; +ReadPreference.NEAREST = exports.ReadPreferenceMode.nearest; +ReadPreference.primary = new ReadPreference(exports.ReadPreferenceMode.primary); +ReadPreference.primaryPreferred = new ReadPreference(exports.ReadPreferenceMode.primaryPreferred); +ReadPreference.secondary = new ReadPreference(exports.ReadPreferenceMode.secondary); +ReadPreference.secondaryPreferred = new ReadPreference(exports.ReadPreferenceMode.secondaryPreferred); +ReadPreference.nearest = new ReadPreference(exports.ReadPreferenceMode.nearest); +exports.ReadPreference = ReadPreference; +//# sourceMappingURL=read_preference.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/read_preference.js.map b/nodejs/node_modules/mongodb/lib/read_preference.js.map new file mode 100644 index 00000000..70ba71ac --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/read_preference.js.map @@ -0,0 +1 @@ +{"version":3,"file":"read_preference.js","sourceRoot":"","sources":["../src/read_preference.ts"],"names":[],"mappings":";;;AACA,mCAAoD;AAOpD,cAAc;AACD,QAAA,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9C,OAAO,E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AAC,mBAAmB,CAAC;QAC5F,IAAI,IAAI,CAAC,KAAK;YAAE,cAAc,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QAClD,OAAO,cAAc,CAAC;IACxB,CAAC;;AAjMa,sBAAO,GAAG,0BAAkB,CAAC,OAAO,CAAC;AACrC,gCAAiB,GAAG,0BAAkB,CAAC,gBAAgB,CAAC;AACxD,wBAAS,GAAG,0BAAkB,CAAC,SAAS,CAAC;AACzC,kCAAmB,GAAG,0BAAkB,CAAC,kBAAkB,CAAC;AAC5D,sBAAO,GAAG,0BAAkB,CAAC,OAAO,CAAC;AAErC,sBAAO,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,OAAO,CAAC,CAAC;AACzD,+BAAgB,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,gBAAgB,CAAC,CAAC;AAC3E,wBAAS,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,SAAS,CAAC,CAAC;AAC7D,iCAAkB,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,kBAAkB,CAAC,CAAC;AAC/E,sBAAO,GAAG,IAAI,cAAc,CAAC,0BAAkB,CAAC,OAAO,CAAC,CAAC;AAjB5D,wCAAc"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/common.js b/nodejs/node_modules/mongodb/lib/sdam/common.js new file mode 100644 index 00000000..60b96aa3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/common.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports._advanceClusterTime = exports.drainTimerQueue = exports.ServerType = exports.TopologyType = exports.STATE_CONNECTED = exports.STATE_CONNECTING = exports.STATE_CLOSED = exports.STATE_CLOSING = void 0; +const timers_1 = require("timers"); +// shared state names +exports.STATE_CLOSING = 'closing'; +exports.STATE_CLOSED = 'closed'; +exports.STATE_CONNECTING = 'connecting'; +exports.STATE_CONNECTED = 'connected'; +/** + * An enumeration of topology types we know about + * @public + */ +exports.TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +}); +/** + * An enumeration of server types we know about + * @public + */ +exports.ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +}); +/** @internal */ +function drainTimerQueue(queue) { + queue.forEach(timers_1.clearTimeout); + queue.clear(); +} +exports.drainTimerQueue = drainTimerQueue; +/** Shared function to determine clusterTime for a given topology or session */ +function _advanceClusterTime(entity, $clusterTime) { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } + else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; + } + } +} +exports._advanceClusterTime = _advanceClusterTime; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/common.js.map b/nodejs/node_modules/mongodb/lib/sdam/common.js.map new file mode 100644 index 00000000..95a76c42 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/sdam/common.ts"],"names":[],"mappings":";;;AAAA,mCAAsC;AAMtC,qBAAqB;AACR,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,gBAAgB,GAAG,YAAY,CAAC;AAChC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C;;;GAGG;AACU,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,QAAQ;IAChB,mBAAmB,EAAE,qBAAqB;IAC1C,qBAAqB,EAAE,uBAAuB;IAC9C,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKZ;;;GAGG;AACU,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,QAAQ;IAChB,eAAe,EAAE,iBAAiB;IAClC,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAQZ,gBAAgB;AAChB,SAAgB,eAAe,CAAC,KAAiB;IAC/C,KAAK,CAAC,OAAO,CAAC,qBAAY,CAAC,CAAC;IAC5B,KAAK,CAAC,KAAK,EAAE,CAAC;AAChB,CAAC;AAHD,0CAGC;AAWD,+EAA+E;AAC/E,SAAgB,mBAAmB,CACjC,MAAgC,EAChC,YAAyB;IAEzB,IAAI,MAAM,CAAC,WAAW,IAAI,IAAI,EAAE;QAC9B,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;KACnC;SAAM;QACL,IAAI,YAAY,CAAC,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE;YACxE,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;SACnC;KACF;AACH,CAAC;AAXD,kDAWC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/events.js b/nodejs/node_modules/mongodb/lib/sdam/events.js new file mode 100644 index 00000000..69dfe9f3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/events.js @@ -0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerHeartbeatFailedEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.TopologyClosedEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.ServerClosedEvent = exports.ServerOpeningEvent = exports.ServerDescriptionChangedEvent = void 0; +const constants_1 = require("../constants"); +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +class ServerDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, address, previousDescription, newDescription) { + this.name = constants_1.SERVER_DESCRIPTION_CHANGED; + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent; +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +class ServerOpeningEvent { + /** @internal */ + constructor(topologyId, address) { + /** @internal */ + this.name = constants_1.SERVER_OPENING; + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerOpeningEvent = ServerOpeningEvent; +/** + * Emitted when server is closed. + * @public + * @category Event + */ +class ServerClosedEvent { + /** @internal */ + constructor(topologyId, address) { + /** @internal */ + this.name = constants_1.SERVER_CLOSED; + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerClosedEvent = ServerClosedEvent; +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +class TopologyDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, previousDescription, newDescription) { + /** @internal */ + this.name = constants_1.TOPOLOGY_DESCRIPTION_CHANGED; + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent; +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +class TopologyOpeningEvent { + /** @internal */ + constructor(topologyId) { + /** @internal */ + this.name = constants_1.TOPOLOGY_OPENING; + this.topologyId = topologyId; + } +} +exports.TopologyOpeningEvent = TopologyOpeningEvent; +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +class TopologyClosedEvent { + /** @internal */ + constructor(topologyId) { + /** @internal */ + this.name = constants_1.TOPOLOGY_CLOSED; + this.topologyId = topologyId; + } +} +exports.TopologyClosedEvent = TopologyClosedEvent; +/** + * Emitted when the server monitor’s hello command is started - immediately before + * the hello command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +class ServerHeartbeatStartedEvent { + /** @internal */ + constructor(connectionId, awaited) { + /** @internal */ + this.name = constants_1.SERVER_HEARTBEAT_STARTED; + this.connectionId = connectionId; + this.awaited = awaited; + } +} +exports.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent; +/** + * Emitted when the server monitor’s hello succeeds. + * @public + * @category Event + */ +class ServerHeartbeatSucceededEvent { + /** @internal */ + constructor(connectionId, duration, reply, awaited) { + /** @internal */ + this.name = constants_1.SERVER_HEARTBEAT_SUCCEEDED; + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply ?? {}; + this.awaited = awaited; + } +} +exports.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent; +/** + * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +class ServerHeartbeatFailedEvent { + /** @internal */ + constructor(connectionId, duration, failure, awaited) { + /** @internal */ + this.name = constants_1.SERVER_HEARTBEAT_FAILED; + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + this.awaited = awaited; + } +} +exports.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent; +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/events.js.map b/nodejs/node_modules/mongodb/lib/sdam/events.js.map new file mode 100644 index 00000000..0ddeb049 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/sdam/events.ts"],"names":[],"mappings":";;;AACA,4CAUsB;AAItB;;;;GAIG;AACH,MAAa,6BAA6B;IAWxC,gBAAgB;IAChB,YACE,UAAkB,EAClB,OAAe,EACf,mBAAsC,EACtC,cAAi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nodejs/node_modules/mongodb/lib/sdam/monitor.js new file mode 100644 index 00000000..2b05556c --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/monitor.js @@ -0,0 +1,458 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MonitorInterval = exports.RTTPinger = exports.Monitor = exports.ServerMonitoringMode = void 0; +const timers_1 = require("timers"); +const bson_1 = require("../bson"); +const connect_1 = require("../cmap/connect"); +const client_metadata_1 = require("../cmap/handshake/client_metadata"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_logger_1 = require("../mongo_logger"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const events_1 = require("./events"); +const server_1 = require("./server"); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED], + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING] +}); +const INVALID_REQUEST_CHECK_STATES = new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor) { + return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING; +} +/** @public */ +exports.ServerMonitoringMode = Object.freeze({ + auto: 'auto', + poll: 'poll', + stream: 'stream' +}); +/** @internal */ +class Monitor extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + super(); + /** @internal */ + this.component = mongo_logger_1.MongoLoggableComponent.TOPOLOGY; + this[kServer] = server; + this.connection = null; + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: common_1.STATE_CLOSED + }; + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: options.connectTimeoutMS ?? 10000, + heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500, + serverMonitoringMode: options.serverMonitoringMode + }); + this.isRunningInFaasEnv = (0, client_metadata_1.getFAASEnv)() != null; + this.mongoLogger = this[kServer].topology.client?.mongoLogger; + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = { + id: '', + generation: server.pool.generation, + cancellationToken, + hostAddress: server.description.hostAddress, + ...options, + // force BSON serialization options + raw: false, + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + }; + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; + } + this.connectOptions = Object.freeze(connectOptions); + } + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: minHeartbeatFrequencyMS, + immediate: true + }); + } + requestCheck() { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + this[kMonitorId]?.wake(); + } + reset() { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // restart monitor + stateTransition(this, STATE_IDLE); + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: minHeartbeatFrequencyMS + }); + } + close() { + if (isInCloseState(this)) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // close monitor + this.emit('close'); + stateTransition(this, common_1.STATE_CLOSED); + } +} +exports.Monitor = Monitor; +function resetMonitorState(monitor) { + monitor[kMonitorId]?.stop(); + monitor[kMonitorId] = undefined; + monitor.rttPinger?.close(); + monitor.rttPinger = undefined; + monitor[kCancellationToken].emit('cancel'); + monitor.connection?.destroy(); + monitor.connection = null; +} +function useStreamingProtocol(monitor, topologyVersion) { + // If we have no topology version we always poll no matter + // what the user provided, since the server does not support + // the streaming protocol. + if (topologyVersion == null) + return false; + const serverMonitoringMode = monitor.options.serverMonitoringMode; + if (serverMonitoringMode === exports.ServerMonitoringMode.poll) + return false; + if (serverMonitoringMode === exports.ServerMonitoringMode.stream) + return true; + // If we are in auto mode, we need to figure out if we're in a FaaS + // environment or not and choose the appropriate mode. + if (monitor.isRunningInFaasEnv) + return false; + return true; +} +function checkServer(monitor, callback) { + let start; + let awaited; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = useStreamingProtocol(monitor, topologyVersion); + monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor[kServer].topology.s.id, undefined, new events_1.ServerHeartbeatStartedEvent(monitor.address, isAwaitable)); + function onHeartbeatFailed(err) { + monitor.connection?.destroy(); + monitor.connection = null; + monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_FAILED, monitor[kServer].topology.s.id, undefined, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err, awaited)); + const error = !(err instanceof error_1.MongoError) + ? new error_1.MongoError(error_1.MongoError.buildErrorMessage(err), { cause: err }) + : err; + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + if (error instanceof error_1.MongoNetworkTimeoutError) { + error.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); + } + monitor.emit('resetServer', error); + callback(err); + } + function onHeartbeatSucceeded(hello) { + if (!('isWritablePrimary' in hello)) { + // Provide hello-style response document. + hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND]; + } + const duration = isAwaitable && monitor.rttPinger + ? monitor.rttPinger.roundTripTime + : (0, utils_1.calculateDurationInMs)(start); + monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor[kServer].topology.s.id, hello.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, hello, isAwaitable)); + if (isAwaitable) { + // If we are using the streaming protocol then we immediately issue another 'started' + // event, otherwise the "check" is complete and return to the main monitor loop + monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor[kServer].topology.s.id, undefined, new events_1.ServerHeartbeatStartedEvent(monitor.address, true)); + // We have not actually sent an outgoing handshake, but when we get the next response we + // want the duration to reflect the time since we last heard from the server + start = (0, utils_1.now)(); + } + else { + monitor.rttPinger?.close(); + monitor.rttPinger = undefined; + callback(undefined, hello); + } + } + const { connection } = monitor; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const cmd = { + [serverApi?.version || helloOk ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: 1, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + if (isAwaitable && monitor.rttPinger == null) { + monitor.rttPinger = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions)); + } + // Record new start time before sending handshake + start = (0, utils_1.now)(); + if (isAwaitable) { + awaited = true; + return connection.exhaustCommand((0, utils_1.ns)('admin.$cmd'), cmd, options, (error, hello) => { + if (error) + return onHeartbeatFailed(error); + return onHeartbeatSucceeded(hello); + }); + } + awaited = false; + connection + .command((0, utils_1.ns)('admin.$cmd'), cmd, options) + .then(onHeartbeatSucceeded, onHeartbeatFailed); + return; + } + // connecting does an implicit `hello` + (async () => { + const socket = await (0, connect_1.makeSocket)(monitor.connectOptions); + const connection = (0, connect_1.makeConnection)(monitor.connectOptions, socket); + // The start time is after socket creation but before the handshake + start = (0, utils_1.now)(); + try { + await (0, connect_1.performInitialHandshake)(connection, monitor.connectOptions); + return connection; + } + catch (error) { + connection.destroy(); + throw error; + } + })().then(connection => { + if (isInCloseState(monitor)) { + connection.destroy(); + return; + } + monitor.connection = connection; + monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor[kServer].topology.s.id, connection.hello?.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), connection.hello, useStreamingProtocol(monitor, connection.hello?.topologyVersion))); + callback(undefined, connection.hello); + }, error => { + monitor.connection = null; + awaited = false; + onHeartbeatFailed(error); + }); +} +function monitorServer(monitor) { + return (callback) => { + if (monitor.s.state === STATE_MONITORING) { + process.nextTick(callback); + return; + } + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + callback(); + } + checkServer(monitor, (err, hello) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === common_1.ServerType.Unknown) { + return done(); + } + } + // if the check indicates streaming is supported, immediately reschedule monitoring + if (useStreamingProtocol(monitor, hello?.topologyVersion)) { + (0, timers_1.setTimeout)(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId]?.wake(); + } + }, 0); + } + done(); + }); + }; +} +function makeTopologyVersion(tv) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + // TODO(NODE-2674): Preserve int64 sent from MongoDB + counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter) + }; +} +/** @internal */ +class RTTPinger { + constructor(cancellationToken, options) { + this.connection = undefined; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + get roundTripTime() { + return this[kRoundTripTime]; + } + close() { + this.closed = true; + (0, timers_1.clearTimeout)(this[kMonitorId]); + this.connection?.destroy(); + this.connection = undefined; + } +} +exports.RTTPinger = RTTPinger; +function measureRoundTripTime(rttPinger, options) { + const start = (0, utils_1.now)(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + if (rttPinger.closed) { + return; + } + function measureAndReschedule(conn) { + if (rttPinger.closed) { + conn?.destroy(); + return; + } + if (rttPinger.connection == null) { + rttPinger.connection = conn; + } + rttPinger[kRoundTripTime] = (0, utils_1.calculateDurationInMs)(start); + rttPinger[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS); + } + const connection = rttPinger.connection; + if (connection == null) { + (0, connect_1.connect)(options).then(connection => { + measureAndReschedule(connection); + }, () => { + rttPinger.connection = undefined; + rttPinger[kRoundTripTime] = 0; + }); + return; + } + const commandName = connection.serverApi?.version || connection.helloOk ? 'hello' : constants_1.LEGACY_HELLO_COMMAND; + connection.command((0, utils_1.ns)('admin.$cmd'), { [commandName]: 1 }, undefined).then(() => measureAndReschedule(), () => { + rttPinger.connection?.destroy(); + rttPinger.connection = undefined; + rttPinger[kRoundTripTime] = 0; + return; + }); +} +/** + * @internal + */ +class MonitorInterval { + constructor(fn, options = {}) { + this.isExpeditedCallToFnScheduled = false; + this.stopped = false; + this.isExecutionInProgress = false; + this.hasExecutedOnce = false; + this._executeAndReschedule = () => { + if (this.stopped) + return; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + } + this.isExpeditedCallToFnScheduled = false; + this.isExecutionInProgress = true; + this.fn(() => { + this.lastExecutionEnded = (0, utils_1.now)(); + this.isExecutionInProgress = false; + this._reschedule(this.heartbeatFrequencyMS); + }); + }; + this.fn = fn; + this.lastExecutionEnded = -Infinity; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000; + this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; + if (options.immediate) { + this._executeAndReschedule(); + } + else { + this._reschedule(undefined); + } + } + wake() { + const currentTime = (0, utils_1.now)(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + // TODO(NODE-4674): Add error handling and logging to the monitor + if (timeSinceLastCall < 0) { + return this._executeAndReschedule(); + } + if (this.isExecutionInProgress) { + return; + } + // debounce multiple calls to wake within the `minInterval` + if (this.isExpeditedCallToFnScheduled) { + return; + } + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { + this.isExpeditedCallToFnScheduled = true; + this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); + return; + } + this._executeAndReschedule(); + } + stop() { + this.stopped = true; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + this.timerId = undefined; + } + this.lastExecutionEnded = -Infinity; + this.isExpeditedCallToFnScheduled = false; + } + toString() { + return JSON.stringify(this); + } + toJSON() { + const currentTime = (0, utils_1.now)(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + return { + timerId: this.timerId != null ? 'set' : 'cleared', + lastCallTime: this.lastExecutionEnded, + isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, + stopped: this.stopped, + heartbeatFrequencyMS: this.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, + currentTime, + timeSinceLastCall + }; + } + _reschedule(ms) { + if (this.stopped) + return; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + } + this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); + } +} +exports.MonitorInterval = MonitorInterval; +//# sourceMappingURL=monitor.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/monitor.js.map b/nodejs/node_modules/mongodb/lib/sdam/monitor.js.map new file mode 100644 index 00000000..28189ab3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/monitor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"monitor.js","sourceRoot":"","sources":["../../src/sdam/monitor.ts"],"names":[],"mappings":";;;AAAA,mCAAkD;AAElD,kCAA8C;AAC9C,6CAA+F;AAE/F,uEAA+D;AAC/D,4CAAoD;AACpD,oCAAiF;AACjF,kDAAyD;AACzD,gDAAsE;AAEtE,oCAA4E;AAC5E,qCAAmE;AACnE,qCAIkB;AAClB,qCAAkC;AAGlC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAE/C,MAAM,UAAU,GAAG,MAAM,CAAC;AAC1B,MAAM,gBAAgB,GAAG,YAAY,CAAC;AACtC,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,UAAU,EAAE,qBAAY,CAAC;IAC1D,CAAC,qBAAY,CAAC,EAAE,CAAC,qBAAY,EAAE,gBAAgB,CAAC;IAChD,CAAC,UAA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O,EAAE,IAAI,CAAC,OAAO;YACrB,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,WAAW;YACX,iBAAiB;SAClB,CAAC;IACJ,CAAC;IAEO,WAAW,CAAC,EAAW;QAC7B,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,IAAA,qBAAY,EAAC,IAAI,CAAC,OAAO,CAAC,CAAC;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,IAAA,mBAAU,EAAC,IAAI,CAAC,qBAAqB,EAAE,EAAE,IAAI,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACzF,CAAC;CAiBF;AA7GD,0CA6GC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server.js b/nodejs/node_modules/mongodb/lib/sdam/server.js new file mode 100644 index 00000000..dea12ff8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server.js @@ -0,0 +1,366 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Server = void 0; +const connection_1 = require("../cmap/connection"); +const connection_pool_1 = require("../cmap/connection_pool"); +const errors_1 = require("../cmap/errors"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const transactions_1 = require("../transactions"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const monitor_1 = require("./monitor"); +const server_description_1 = require("./server_description"); +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +class Server extends mongo_types_1.TypedEventEmitter { + /** + * Create a server + */ + constructor(topology, description, options) { + super(); + this.serverApi = options.serverApi; + const poolOptions = { hostAddress: description.hostAddress, ...options }; + this.topology = topology; + this.pool = new connection_pool_1.ConnectionPool(this, poolOptions); + this.s = { + description, + options, + state: common_1.STATE_CLOSED, + operationCount: 0 + }; + for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) { + this.pool.on(event, (e) => this.emit(event, e)); + } + this.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => { + this.clusterTime = clusterTime; + }); + if (this.loadBalanced) { + this.monitor = null; + // monitoring is disabled in load balancing mode + return; + } + // create the monitor + this.monitor = new monitor_1.Monitor(this, this.s.options); + for (const event of constants_1.HEARTBEAT_EVENTS) { + this.monitor.on(event, (e) => this.emit(event, e)); + } + this.monitor.on('resetServer', (error) => markServerUnknown(this, error)); + this.monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => { + this.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + })); + if (this.s.state === common_1.STATE_CONNECTING) { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + }); + } + get clusterTime() { + return this.topology.clusterTime; + } + set clusterTime(clusterTime) { + this.topology.clusterTime = clusterTime; + } + get description() { + return this.s.description; + } + get name() { + return this.s.description.address; + } + get autoEncrypter() { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return; + } + get loadBalanced() { + return this.topology.description.type === common_1.TopologyType.LoadBalanced; + } + /** + * Initiate server connect + */ + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + this.monitor?.connect(); + } + else { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + /** Destroy the server connection */ + destroy() { + if (this.s.state === common_1.STATE_CLOSED) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + if (!this.loadBalanced) { + this.monitor?.close(); + } + this.pool.close(); + stateTransition(this, common_1.STATE_CLOSED); + this.emit('closed'); + } + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck() { + if (!this.loadBalanced) { + this.monitor?.requestCheck(); + } + } + /** + * Execute a command + * @internal + */ + async command(ns, cmd, options) { + if (ns.db == null || typeof ns === 'string') { + throw new error_1.MongoInvalidArgumentError('Namespace must not be a string'); + } + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + throw new error_1.MongoServerClosedError(); + } + // Clone the options + const finalOptions = Object.assign({}, options, { + wireProtocolCommand: false, + directConnection: this.topology.s.options.directConnection + }); + // There are cases where we need to flag the read preference not to get sent in + // the command, such as pre-5.0 servers attempting to perform an aggregate write + // with a non-primary read preference. In this case the effective read preference + // (primary) is not the same as the provided and must be removed completely. + if (finalOptions.omitReadPreference) { + delete finalOptions.readPreference; + } + const session = finalOptions.session; + let conn = session?.pinnedConnection; + this.incrementOperationCount(); + if (conn == null) { + try { + conn = await this.pool.checkOut(); + if (this.loadBalanced && isPinnableCommand(cmd, session)) { + session?.pin(conn); + } + } + catch (checkoutError) { + this.decrementOperationCount(); + if (!(checkoutError instanceof errors_1.PoolClearedError)) + this.handleError(checkoutError); + throw checkoutError; + } + } + try { + try { + return await conn.command(ns, cmd, finalOptions); + } + catch (commandError) { + throw this.decorateCommandError(conn, cmd, finalOptions, commandError); + } + } + catch (operationError) { + if (operationError instanceof error_1.MongoError && + operationError.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) { + await this.pool.reauthenticate(conn); + try { + return await conn.command(ns, cmd, finalOptions); + } + catch (commandError) { + throw this.decorateCommandError(conn, cmd, finalOptions, commandError); + } + } + else { + throw operationError; + } + } + finally { + this.decrementOperationCount(); + if (session?.pinnedConnection !== conn) { + this.pool.checkIn(conn); + } + } + } + /** + * Handle SDAM error + * @internal + */ + handleError(error, connection) { + if (!(error instanceof error_1.MongoError)) { + return; + } + const isStaleError = error.connectionGeneration && error.connectionGeneration < this.pool.generation; + if (isStaleError) { + return; + } + const isNetworkNonTimeoutError = error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError); + const isNetworkTimeoutBeforeHandshakeError = (0, error_1.isNetworkErrorBeforeHandshake)(error); + const isAuthHandshakeError = error.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError); + if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + if (!this.loadBalanced) { + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + markServerUnknown(this, error); + } + else if (connection) { + this.pool.clear({ serviceId: connection.serviceId }); + } + } + else { + if ((0, error_1.isSDAMUnrecoverableError)(error)) { + if (shouldHandleStateChangeError(this, error)) { + const shouldClearPool = (0, utils_1.maxWireVersion)(this) <= 7 || (0, error_1.isNodeShuttingDownError)(error); + if (this.loadBalanced && connection && shouldClearPool) { + this.pool.clear({ serviceId: connection.serviceId }); + } + if (!this.loadBalanced) { + if (shouldClearPool) { + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + } + markServerUnknown(this, error); + process.nextTick(() => this.requestCheck()); + } + } + } + } + } + /** + * Ensure that error is properly decorated and internal state is updated before throwing + * @internal + */ + decorateCommandError(connection, cmd, options, error) { + if (typeof error !== 'object' || error == null || !('name' in error)) { + throw new error_1.MongoRuntimeError('An unexpected error type: ' + typeof error); + } + if (error.name === 'AbortError' && 'cause' in error && error.cause instanceof error_1.MongoError) { + error = error.cause; + } + if (!(error instanceof error_1.MongoError)) { + // Node.js or some other error we have not special handling for + return error; + } + if (connectionIsStale(this.pool, connection)) { + return error; + } + const session = options?.session; + if (error instanceof error_1.MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + // inActiveTransaction check handles commit and abort. + if (inActiveTransaction(session, cmd) && + !error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + error.addErrorLabel(error_1.MongoErrorLabel.TransientTransactionError); + } + if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && + (0, utils_1.supportsRetryableWrites)(this) && + !inActiveTransaction(session, cmd)) { + error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + } + else { + if ((isRetryableWritesEnabled(this.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && + (0, error_1.needsRetryableWriteLabel)(error, (0, utils_1.maxWireVersion)(this)) && + !inActiveTransaction(session, cmd)) { + error.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + } + if (session && + session.isPinned && + error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + session.unpin({ force: true }); + } + this.handleError(error, connection); + return error; + } + /** + * Decrement the operation count, returning the new count. + */ + decrementOperationCount() { + return (this.s.operationCount -= 1); + } + /** + * Increment the operation count, returning the new count. + */ + incrementOperationCount() { + return (this.s.operationCount += 1); + } +} +/** @event */ +Server.SERVER_HEARTBEAT_STARTED = constants_1.SERVER_HEARTBEAT_STARTED; +/** @event */ +Server.SERVER_HEARTBEAT_SUCCEEDED = constants_1.SERVER_HEARTBEAT_SUCCEEDED; +/** @event */ +Server.SERVER_HEARTBEAT_FAILED = constants_1.SERVER_HEARTBEAT_FAILED; +/** @event */ +Server.CONNECT = constants_1.CONNECT; +/** @event */ +Server.DESCRIPTION_RECEIVED = constants_1.DESCRIPTION_RECEIVED; +/** @event */ +Server.CLOSED = constants_1.CLOSED; +/** @event */ +Server.ENDED = constants_1.ENDED; +exports.Server = Server; +function calculateRoundTripTime(oldRtt, duration) { + if (oldRtt === -1) { + return duration; + } + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} +function markServerUnknown(server, error) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { + server.monitor?.reset(); + } + server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { error })); +} +function isPinnableCommand(cmd, session) { + if (session) { + return (session.inTransaction() || + (session.transaction.isCommitted && 'commitTransaction' in cmd) || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd); + } + return false; +} +function connectionIsStale(pool, connection) { + if (connection.serviceId) { + return (connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString())); + } + return connection.generation !== pool.generation; +} +function shouldHandleStateChangeError(server, err) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return (0, server_description_1.compareTopologyVersion)(stv, etv) < 0; +} +function inActiveTransaction(session, cmd) { + return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd); +} +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology) { + return topology.s.options.retryWrites !== false; +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server.js.map b/nodejs/node_modules/mongodb/lib/sdam/server.js.map new file mode 100644 index 00000000..db14ab2f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/sdam/server.ts"],"names":[],"mappings":";;;AAEA,mDAAqE;AACrE,6DAIiC;AACjC,2CAAkD;AAClD,4CAWsB;AACtB,oCAekB;AAElB,gDAAmD;AAGnD,kDAAuD;AACvD,oCAMkB;AAClB,qCAOkB;AAMlB,uCAAyD;AACzD,6DAAiF;AAGjF,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,q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GAAG,CAAC;YAC/D,WAAW,IAAI,GAAG;YAClB,MAAM,IAAI,GAAG;YACb,SAAS,IAAI,GAAG;YAChB,iBAAiB,IAAI,GAAG;YACxB,aAAa,IAAI,GAAG,CACrB,CAAC;KACH;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAoB,EAAE,UAAsB;IACrE,IAAI,UAAU,CAAC,SAAS,EAAE;QACxB,OAAO,CACL,UAAU,CAAC,UAAU,KAAK,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,CAC1F,CAAC;KACH;IAED,OAAO,UAAU,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,CAAC;AACnD,CAAC;AAED,SAAS,4BAA4B,CAAC,MAAc,EAAE,GAAe;IACnE,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAAC;IAChC,MAAM,GAAG,GAAG,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC;IAC/C,OAAO,IAAA,2CAAsB,EAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;AAC9C,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAkC,EAAE,GAAa;IAC5E,OAAO,OAAO,IAAI,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,IAAA,mCAAoB,EAAC,GAAG,CAAC,CAAC;AAC1E,CAAC;AAED;4DAC4D;AAC5D,SAAS,wBAAwB,CAAC,QAAkB;IAClD,OAAO,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server_description.js b/nodejs/node_modules/mongodb/lib/sdam/server_description.js new file mode 100644 index 00000000..1cf4da37 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server_description.js @@ -0,0 +1,189 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compareTopologyVersion = exports.parseServerType = exports.ServerDescription = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const WRITABLE_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.Standalone, + common_1.ServerType.Mongos, + common_1.ServerType.LoadBalancer +]); +const DATA_BEARING_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.RSSecondary, + common_1.ServerType.Mongos, + common_1.ServerType.Standalone, + common_1.ServerType.LoadBalancer +]); +/** + * The client's view of a single server, based on the most recent hello outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +class ServerDescription { + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param hello - An optional hello response for this server + */ + constructor(address, hello, options = {}) { + if (address == null || address === '') { + throw new error_1.MongoRuntimeError('ServerDescription must be provided with a non-empty address'); + } + this.address = + typeof address === 'string' + ? utils_1.HostAddress.fromString(address).toString() // Use HostAddress to normalize + : address.toString(); + this.type = parseServerType(hello, options); + this.hosts = hello?.hosts?.map((host) => host.toLowerCase()) ?? []; + this.passives = hello?.passives?.map((host) => host.toLowerCase()) ?? []; + this.arbiters = hello?.arbiters?.map((host) => host.toLowerCase()) ?? []; + this.tags = hello?.tags ?? {}; + this.minWireVersion = hello?.minWireVersion ?? 0; + this.maxWireVersion = hello?.maxWireVersion ?? 0; + this.roundTripTime = options?.roundTripTime ?? -1; + this.lastUpdateTime = (0, utils_1.now)(); + this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0; + this.error = options.error ?? null; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; + this.setName = hello?.setName ?? null; + this.setVersion = hello?.setVersion ?? null; + this.electionId = hello?.electionId ?? null; + this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; + this.primary = hello?.primary ?? null; + this.me = hello?.me?.toLowerCase() ?? null; + this.$clusterTime = hello?.$clusterTime ?? null; + } + get hostAddress() { + return utils_1.HostAddress.fromString(this.address); + } + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + /** Is this server available for reads*/ + get isReadable() { + return this.type === common_1.ServerType.RSSecondary || this.isWritable; + } + /** Is this server data bearing */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + /** Is this server available for writes */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } + get host() { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + get port() { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : 27017; + } + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other) { + // Despite using the comparator that would determine a nullish topologyVersion as greater than + // for equality we should only always perform direct equality comparison + const topologyVersionsEqual = this.topologyVersion === other?.topologyVersion || + compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; + const electionIdsEqual = this.electionId != null && other?.electionId != null + ? (0, utils_1.compareObjectId)(this.electionId, other.electionId) === 0 + : this.electionId === other?.electionId; + return (other != null && + (0, utils_1.errorStrictEqual)(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + (0, utils_1.arrayStrictEqual)(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual); + } +} +exports.ServerDescription = ServerDescription; +// Parses a `hello` message and determines the server type +function parseServerType(hello, options) { + if (options?.loadBalanced) { + return common_1.ServerType.LoadBalancer; + } + if (!hello || !hello.ok) { + return common_1.ServerType.Unknown; + } + if (hello.isreplicaset) { + return common_1.ServerType.RSGhost; + } + if (hello.msg && hello.msg === 'isdbgrid') { + return common_1.ServerType.Mongos; + } + if (hello.setName) { + if (hello.hidden) { + return common_1.ServerType.RSOther; + } + else if (hello.isWritablePrimary) { + return common_1.ServerType.RSPrimary; + } + else if (hello.secondary) { + return common_1.ServerType.RSSecondary; + } + else if (hello.arbiterOnly) { + return common_1.ServerType.RSArbiter; + } + else { + return common_1.ServerType.RSOther; + } + } + return common_1.ServerType.Standalone; +} +exports.parseServerType = parseServerType; +function tagsStrictEqual(tags, tags2) { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + return (tagsKeys.length === tags2Keys.length && + tagsKeys.every((key) => tags2[key] === tags[key])); +} +/** + * Compares two topology versions. + * + * 1. If the response topologyVersion is unset or the ServerDescription's + * topologyVersion is null, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is not equal to the + * ServerDescription's, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is equal to the + * ServerDescription's, the client MUST use the counter field to determine + * which topologyVersion is more recent. + * + * ```ts + * currentTv < newTv === -1 + * currentTv === newTv === 0 + * currentTv > newTv === 1 + * ``` + */ +function compareTopologyVersion(currentTv, newTv) { + if (currentTv == null || newTv == null) { + return -1; + } + if (!currentTv.processId.equals(newTv.processId)) { + return -1; + } + // TODO(NODE-2674): Preserve int64 sent from MongoDB + const currentCounter = bson_1.Long.isLong(currentTv.counter) + ? currentTv.counter + : bson_1.Long.fromNumber(currentTv.counter); + const newCounter = bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter); + return currentCounter.compare(newCounter); +} +exports.compareTopologyVersion = compareTopologyVersion; +//# sourceMappingURL=server_description.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server_description.js.map b/nodejs/node_modules/mongodb/lib/sdam/server_description.js.map new file mode 100644 index 00000000..00d94032 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_description.js","sourceRoot":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CAAC,EAAE;QAChD,OAAO,CAAC,CAAC,CAAC;KACX;IAED,oDAAoD;IACpD,MAAM,cAAc,GAAG,WAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC;QACnD,CAAC,CAAC,SAAS,CAAC,OAAO;QACnB,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAE/F,OAAO,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC5C,CAAC;AAnBD,wDAmBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server_selection.js b/nodejs/node_modules/mongodb/lib/sdam/server_selection.js new file mode 100644 index 00000000..d7e277f8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server_selection.js @@ -0,0 +1,234 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readPreferenceServerSelector = exports.secondaryWritableServerSelector = exports.sameServerSelector = exports.writableServerSelector = exports.MIN_SECONDARY_WRITE_WIRE_VERSION = void 0; +const error_1 = require("../error"); +const read_preference_1 = require("../read_preference"); +const common_1 = require("./common"); +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; +// Minimum version to try writes on secondaries. +exports.MIN_SECONDARY_WRITE_WIRE_VERSION = 13; +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return function writableServer(topologyDescription, servers) { + return latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); + }; +} +exports.writableServerSelector = writableServerSelector; +/** + * The purpose of this selector is to select the same server, only + * if it is in a state that it can have commands sent to it. + */ +function sameServerSelector(description) { + return function sameServerSelector(topologyDescription, servers) { + if (!description) + return []; + // Filter the servers to match the provided description only if + // the type is not unknown. + return servers.filter(sd => { + return sd.address === description.address && sd.type !== common_1.ServerType.Unknown; + }); + }; +} +exports.sameServerSelector = sameServerSelector; +/** + * Returns a server selector that uses a read preference to select a + * server potentially for a write on a secondary. + */ +function secondaryWritableServerSelector(wireVersion, readPreference) { + // If server version < 5.0, read preference always primary. + // If server version >= 5.0... + // - If read preference is supplied, use that. + // - If no read preference is supplied, use primary. + if (!readPreference || + !wireVersion || + (wireVersion && wireVersion < exports.MIN_SECONDARY_WRITE_WIRE_VERSION)) { + return readPreferenceServerSelector(read_preference_1.ReadPreference.primary); + } + return readPreferenceServerSelector(readPreference); +} +exports.secondaryWritableServerSelector = secondaryWritableServerSelector; +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param readPreference - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); + } + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { + const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); + return servers.reduce((result, server) => { + const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + return servers; +} +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param serverTags - The server's tags + */ +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + return true; +} +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns The list of servers matching the requested tags + */ +function tagSetReducer(readPreference, servers) { + if (readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0)) { + return servers; + } + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) + matched.push(server); + return matched; + }, []); + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + return []; +} +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param topologyDescription - The topology description + * @param servers - The list of servers to reduce + * @returns The servers which fall within an acceptable latency window + */ +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce((min, server) => min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), -1); + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) + result.push(server); + return result; + }, []); +} +// filters +function primaryFilter(server) { + return server.type === common_1.ServerType.RSPrimary; +} +function secondaryFilter(server) { + return server.type === common_1.ServerType.RSSecondary; +} +function nearestFilter(server) { + return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; +} +function knownFilter(server) { + return server.type !== common_1.ServerType.Unknown; +} +function loadBalancerFilter(server) { + return server.type === common_1.ServerType.LoadBalancer; +} +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new error_1.MongoInvalidArgumentError('Invalid read preference specified'); + } + return function readPreferenceServers(topologyDescription, servers, deprioritized = []) { + const commonWireVersion = topologyDescription.commonWireVersion; + if (commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion) { + throw new error_1.MongoCompatibilityError(`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`); + } + if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); + } + if (topologyDescription.type === common_1.TopologyType.Unknown) { + return []; + } + if (topologyDescription.type === common_1.TopologyType.Single) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + if (topologyDescription.type === common_1.TopologyType.Sharded) { + const filtered = servers.filter(server => { + return !deprioritized.includes(server); + }); + const selectable = filtered.length > 0 ? filtered : deprioritized; + return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter)); + } + const mode = readPreference.mode; + if (mode === read_preference_1.ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); + if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + return selectedServers; + }; +} +exports.readPreferenceServerSelector = readPreferenceServerSelector; +//# sourceMappingURL=server_selection.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server_selection.js.map b/nodejs/node_modules/mongodb/lib/sdam/server_selection.js.map new file mode 100644 index 00000000..d85c0f49 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server_selection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_selection.js","sourceRoot":"","sources":["../../src/sdam/server_selection.ts"],"names":[],"mappings":";;;AAAA,oCAA8E;AAC9E,wDAAoD;AACpD,qCAAoD;AAIpD,0BAA0B;AAC1B,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAChC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAE1C,iDAAiD;AACpC,QAAA,gCAAgC,GAAG,EAAE,CAAC;AASnD;;GAEG;AACH,SAAgB,sBAAsB;IACpC,OAAO,SAAS,cAAc,CAC5B,mBAAwC,EACxC,OAA4B;QAE5B,OAAO,oBAAoB,CACzB,mBAAmB,EACnB,OAAO,CAAC,MAAM,CAAC,CAAC,CAAoB,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvD,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAVD,wDAUC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAAC,WAA+B;IAChE,OAAO,SAAS,kBAAkB,CAChC,mBAAwC,EACxC,OAA4B;QAE5B,IAAI,CAAC,WAAW;YAAE,OAAO,EAAE,CAAC;QAC5B,+DAA+D;QAC/D,2BAA2B;QAC3B,OAAO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oEAoEC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server_selection_events.js b/nodejs/node_modules/mongodb/lib/sdam/server_selection_events.js new file mode 100644 index 00000000..20bc95b0 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server_selection_events.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WaitingForSuitableServerEvent = exports.ServerSelectionSucceededEvent = exports.ServerSelectionFailedEvent = exports.ServerSelectionStartedEvent = exports.ServerSelectionEvent = void 0; +const utils_1 = require(".././utils"); +const constants_1 = require("../constants"); +/** + * The base export class for all logs published from server selection + * @internal + * @category Log Type + */ +class ServerSelectionEvent { + /** @internal */ + constructor(selector, topologyDescription, operation) { + this.selector = selector; + this.operation = operation; + this.topologyDescription = topologyDescription; + } +} +exports.ServerSelectionEvent = ServerSelectionEvent; +/** + * An event published when server selection starts + * @internal + * @category Event + */ +class ServerSelectionStartedEvent extends ServerSelectionEvent { + /** @internal */ + constructor(selector, topologyDescription, operation) { + super(selector, topologyDescription, operation); + /** @internal */ + this.name = constants_1.SERVER_SELECTION_STARTED; + this.message = 'Server selection started'; + } +} +exports.ServerSelectionStartedEvent = ServerSelectionStartedEvent; +/** + * An event published when a server selection fails + * @internal + * @category Event + */ +class ServerSelectionFailedEvent extends ServerSelectionEvent { + /** @internal */ + constructor(selector, topologyDescription, error, operation) { + super(selector, topologyDescription, operation); + /** @internal */ + this.name = constants_1.SERVER_SELECTION_FAILED; + this.message = 'Server selection failed'; + this.failure = error; + } +} +exports.ServerSelectionFailedEvent = ServerSelectionFailedEvent; +/** + * An event published when server selection succeeds + * @internal + * @category Event + */ +class ServerSelectionSucceededEvent extends ServerSelectionEvent { + /** @internal */ + constructor(selector, topologyDescription, address, operation) { + super(selector, topologyDescription, operation); + /** @internal */ + this.name = constants_1.SERVER_SELECTION_SUCCEEDED; + this.message = 'Server selection succeeded'; + const { host, port } = utils_1.HostAddress.fromString(address).toHostPort(); + this.serverHost = host; + this.serverPort = port; + } +} +exports.ServerSelectionSucceededEvent = ServerSelectionSucceededEvent; +/** + * An event published when server selection is waiting for a suitable server to become available + * @internal + * @category Event + */ +class WaitingForSuitableServerEvent extends ServerSelectionEvent { + /** @internal */ + constructor(selector, topologyDescription, remainingTimeMS, operation) { + super(selector, topologyDescription, operation); + /** @internal */ + this.name = constants_1.WAITING_FOR_SUITABLE_SERVER; + this.message = 'Waiting for suitable server to become available'; + this.remainingTimeMS = remainingTimeMS; + } +} +exports.WaitingForSuitableServerEvent = WaitingForSuitableServerEvent; +//# sourceMappingURL=server_selection_events.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/server_selection_events.js.map b/nodejs/node_modules/mongodb/lib/sdam/server_selection_events.js.map new file mode 100644 index 00000000..b6c719ed --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/server_selection_events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server_selection_events.js","sourceRoot":"","sources":["../../src/sdam/server_selection_events.ts"],"names":[],"mappings":";;;AAAA,sCAAyC;AACzC,4CAKsB;AAKtB;;;;GAIG;AACH,MAAsB,oBAAoB;IAmBxC,gBAAgB;IAChB,YACE,QAAkD,EAClD,mBAAwC,EACxC,SAAiB;QAEjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IACjD,CAAC;CACF;AA7BD,oDA6BC;AAED;;;;GAIG;AACH,MAAa,2BAA4B,SAAQ,oBAAoB;IAKnE,gBAAgB;IAChB,YACE,QAAkD,EAClD,mBAAwC,EACxC,SAAiB;QAEjB,KAAK,CAAC,QAAQ,EAAE,mBAAmB,EAAE,SAAS,CAAC,CAAC;QAVlD,gBAAgB;QAChB,SAAI,GAAG,oCAAwB,CAAC;QAChC,YAAO,GAAG,0BAA0B,CAAC;IASrC,CAAC;CACF;AAbD,kE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_polling.js b/nodejs/node_modules/mongodb/lib/sdam/srv_polling.js new file mode 100644 index 00000000..dfa4120b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/srv_polling.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SrvPoller = exports.SrvPollingEvent = void 0; +const dns = require("dns"); +const timers_1 = require("timers"); +const error_1 = require("../error"); +const mongo_types_1 = require("../mongo_types"); +const utils_1 = require("../utils"); +/** + * @internal + * @category Event + */ +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + hostnames() { + return new Set(this.srvRecords.map(r => utils_1.HostAddress.fromSrvRecord(r).toString())); + } +} +exports.SrvPollingEvent = SrvPollingEvent; +/** @internal */ +class SrvPoller extends mongo_types_1.TypedEventEmitter { + constructor(options) { + super(); + if (!options || !options.srvHost) { + throw new error_1.MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + this.srvHost = options.srvHost; + this.srvMaxHosts = options.srvMaxHosts ?? 0; + this.srvServiceName = options.srvServiceName ?? 'mongodb'; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 10000; + this.haMode = false; + this.generation = 0; + this._timeout = undefined; + } + get srvAddress() { + return `_${this.srvServiceName}._tcp.${this.srvHost}`; + } + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + start() { + if (!this._timeout) { + this.schedule(); + } + } + stop() { + if (this._timeout) { + (0, timers_1.clearTimeout)(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + // TODO(NODE-4994): implement new logging logic for SrvPoller failures + schedule() { + if (this._timeout) { + (0, timers_1.clearTimeout)(this._timeout); + } + this._timeout = (0, timers_1.setTimeout)(() => { + this._poll().catch(() => null); + }, this.intervalMS); + } + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + failure() { + this.haMode = true; + this.schedule(); + } + async _poll() { + const generation = this.generation; + let srvRecords; + try { + srvRecords = await dns.promises.resolveSrv(this.srvAddress); + } + catch (dnsError) { + this.failure(); + return; + } + if (generation !== this.generation) { + return; + } + const finalAddresses = []; + for (const record of srvRecords) { + if ((0, utils_1.matchesParentDomain)(record.name, this.srvHost)) { + finalAddresses.push(record); + } + } + if (!finalAddresses.length) { + this.failure(); + return; + } + this.success(finalAddresses); + } +} +/** @event */ +SrvPoller.SRV_RECORD_DISCOVERY = 'srvRecordDiscovery'; +exports.SrvPoller = SrvPoller; +//# sourceMappingURL=srv_polling.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/srv_polling.js.map b/nodejs/node_modules/mongodb/lib/sdam/srv_polling.js.map new file mode 100644 index 00000000..0ba90515 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/srv_polling.js.map @@ -0,0 +1 @@ +{"version":3,"file":"srv_polling.js","sourceRoot":"","sources":["../../src/sdam/srv_polling.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAC3B,mCAAkD;AAElD,oCAA6C;AAC7C,gDAAmD;AACnD,oCAA4D;AAE5D;;;GAGG;AACH,MAAa,eAAe;IAE1B,YAAY,UAA2B;QACrC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,SAAS;QACP,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,mBAAW,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IACpF,CAAC;CACF;AATD,0CASC;AAeD,gBAAgB;AAChB,MAAa,SAAU,SAAQ,+BAAkC;IAa/D,YAAY,OAAyB;QACnC,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YAChC,MAAM,IAAI,yBAAiB,CAAC,sDAAsD,C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 No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/topology.js b/nodejs/node_modules/mongodb/lib/sdam/topology.js new file mode 100644 index 00000000..a86af8d3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/topology.js @@ -0,0 +1,647 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCapabilities = exports.Topology = void 0; +const util_1 = require("util"); +const connection_string_1 = require("../connection_string"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +const mongo_logger_1 = require("../mongo_logger"); +const mongo_types_1 = require("../mongo_types"); +const read_preference_1 = require("../read_preference"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const events_1 = require("./events"); +const server_1 = require("./server"); +const server_description_1 = require("./server_description"); +const server_selection_1 = require("./server_selection"); +const server_selection_events_1 = require("./server_selection_events"); +const srv_polling_1 = require("./srv_polling"); +const topology_description_1 = require("./topology_description"); +// Global state +let globalTopologyCounter = 0; +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +class Topology extends mongo_types_1.TypedEventEmitter { + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(client, seeds, options) { + super(); + this.client = client; + this.selectServerAsync = (0, util_1.promisify)((selector, options, callback) => this.selectServer(selector, options, callback)); + // Options should only be undefined in tests, MongoClient will always have defined options + options = options ?? { + hosts: [utils_1.HostAddress.fromString('localhost:27017')], + ...Object.fromEntries(connection_string_1.DEFAULT_OPTIONS.entries()), + ...Object.fromEntries(connection_string_1.FEATURE_FLAGS.entries()) + }; + if (typeof seeds === 'string') { + seeds = [utils_1.HostAddress.fromString(seeds)]; + } + else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + const seedlist = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(utils_1.HostAddress.fromString(seed)); + } + else if (seed instanceof utils_1.HostAddress) { + seedlist.push(seed); + } + else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + const selectedHosts = options.srvMaxHosts == null || + options.srvMaxHosts === 0 || + options.srvMaxHosts >= seedlist.length + ? seedlist + : (0, utils_1.shuffle)(seedlist, options.srvMaxHosts); + const serverDescriptions = new Map(); + for (const hostAddress of selectedHosts) { + serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress)); + } + this[kWaitQueue] = new utils_1.List(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: common_1.STATE_CLOSED, + // the topology description + description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, undefined, undefined, undefined, options), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + credentials: options?.credentials, + clusterTime: undefined, + // timer management + connectionTimers: new Set(), + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) + }; + this.mongoLogger = client.mongoLogger; + this.component = 'topology'; + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + options.srvPoller ?? + new srv_polling_1.SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, + srvMaxHosts: options.srvMaxHosts, + srvServiceName: options.srvServiceName + }); + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + } + } + detectShardedTopology(event) { + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; + const srvListeners = this.s.srvPoller?.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); + if (transitionToSharded && !listeningToSrvPolling) { + this.s.srvPoller?.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + this.s.srvPoller?.start(); + } + } + detectSrvRecords(ev) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent(ev, this.s.options.srvMaxHosts); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + updateServers(this); + this.emitAndLog(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + /** + * @returns A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + get loadBalanced() { + return this.s.options.loadBalanced; + } + get serverApi() { + return this.s.options.serverApi; + } + get capabilities() { + return new ServerCapabilities(this.lastHello()); + } + connect(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ?? {}; + if (this.s.state === common_1.STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // emit SDAM monitoring events + this.emitAndLog(Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id)); + // emit an event for the topology change + this.emitAndLog(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown), // initial is always Unknown + this.s.description)); + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + this.s.servers = new Map(serverDescriptions.map(serverDescription => [ + serverDescription.address, + createAndConnectServer(this, serverDescription) + ])); + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new server_description_1.ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); + } + } + const exitWithError = (error) => callback ? callback(error) : this.emit(Topology.ERROR, error); + const readPreference = options.readPreference ?? read_preference_1.ReadPreference.primary; + const selectServerOptions = { operationName: 'ping', ...options }; + this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), selectServerOptions, (err, server) => { + if (err) { + this.close(); + return exitWithError(err); + } + const skipPingOnConnect = this.s.options[Symbol.for('@@mdb.skipPingOnConnect')] === true; + if (!skipPingOnConnect && server && this.s.credentials) { + server.command((0, utils_1.ns)('admin.$cmd'), { ping: 1 }, {}).then(() => { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + callback?.(undefined, this); + }, exitWithError); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + callback?.(undefined, this); + }); + } + /** Close this topology */ + close() { + if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { + return; + } + for (const server of this.s.servers.values()) { + destroyServer(server, this); + } + this.s.servers.clear(); + stateTransition(this, common_1.STATE_CLOSING); + drainWaitQueue(this[kWaitQueue], new error_1.MongoTopologyClosedError()); + (0, common_1.drainTimerQueue)(this.s.connectionTimers); + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + stateTransition(this, common_1.STATE_CLOSED); + // emit an event for close + this.emitAndLog(Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id)); + } + /** + * Selects a server according to the selection predicate provided + * + * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window + * @param options - Optional settings related to server selection + * @param callback - The callback used to indicate success or failure + * @returns An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.fromString(selector)); + } + else { + let readPreference; + if (selector instanceof read_preference_1.ReadPreference) { + readPreference = selector; + } + else { + read_preference_1.ReadPreference.translate(options); + readPreference = options.readPreference || read_preference_1.ReadPreference.primary; + } + serverSelector = (0, server_selection_1.readPreferenceServerSelector)(readPreference); + } + } + else { + serverSelector = selector; + } + options = { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS, ...options }; + if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionStartedEvent(selector, this.description, options.operationName)); + } + const isSharded = this.description.type === common_1.TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + if (isSharded && transaction && transaction.server) { + if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(selector, this.description, transaction.server.pool.address, options.operationName)); + } + callback(undefined, transaction.server); + return; + } + const waitQueueMember = { + serverSelector, + topologyDescription: this.description, + mongoLogger: this.client.mongoLogger, + transaction, + callback, + timeoutController: new utils_1.TimeoutController(options.serverSelectionTimeoutMS), + startTime: (0, utils_1.now)(), + operationName: options.operationName, + waitingLogged: false, + previousServer: options.previousServer + }; + waitQueueMember.timeoutController.signal.addEventListener('abort', () => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timeoutController.clear(); + const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${options.serverSelectionTimeoutMS} ms`, this.description); + if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(selector, this.description, timeoutError, options.operationName)); + } + waitQueueMember.callback(timeoutError); + }); + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param serverDescription - The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + if (!previousServerDescription) { + return; + } + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + (0, common_1._advanceClusterTime)(this, clusterTime); + } + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = previousServerDescription && previousServerDescription.equals(serverDescription); + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit(Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit(Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription)); + } + } + // update server list from updated descriptions + updateServers(this, serverDescription); + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + if (!equalDescriptions) { + this.emitAndLog(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + } + auth(credentials, callback) { + if (typeof credentials === 'function') + (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') + callback(undefined, true); + } + get clientMetadata() { + return this.s.options.metadata; + } + isConnected() { + return this.s.state === common_1.STATE_CONNECTED; + } + isDestroyed() { + return this.s.state === common_1.STATE_CLOSED; + } + // NOTE: There are many places in code where we explicitly check the last hello + // to do feature support detection. This should be done any other way, but for + // now we will just return the first hello seen, which should suffice. + lastHello() { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) + return {}; + const sd = serverDescriptions.filter((sd) => sd.type !== common_1.ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + get commonWireVersion() { + return this.description.commonWireVersion; + } + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + get clusterTime() { + return this.s.clusterTime; + } + set clusterTime(clusterTime) { + this.s.clusterTime = clusterTime; + } +} +/** @event */ +Topology.SERVER_OPENING = constants_1.SERVER_OPENING; +/** @event */ +Topology.SERVER_CLOSED = constants_1.SERVER_CLOSED; +/** @event */ +Topology.SERVER_DESCRIPTION_CHANGED = constants_1.SERVER_DESCRIPTION_CHANGED; +/** @event */ +Topology.TOPOLOGY_OPENING = constants_1.TOPOLOGY_OPENING; +/** @event */ +Topology.TOPOLOGY_CLOSED = constants_1.TOPOLOGY_CLOSED; +/** @event */ +Topology.TOPOLOGY_DESCRIPTION_CHANGED = constants_1.TOPOLOGY_DESCRIPTION_CHANGED; +/** @event */ +Topology.ERROR = constants_1.ERROR; +/** @event */ +Topology.OPEN = constants_1.OPEN; +/** @event */ +Topology.CONNECT = constants_1.CONNECT; +/** @event */ +Topology.CLOSE = constants_1.CLOSE; +/** @event */ +Topology.TIMEOUT = constants_1.TIMEOUT; +exports.Topology = Topology; +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer(server, topology) { + for (const event of constants_1.LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + server.destroy(); + topology.emitAndLog(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address)); + for (const event of constants_1.SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } +} +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options) { + if (options?.directConnection) { + return common_1.TopologyType.Single; + } + if (options?.replicaSet) { + return common_1.TopologyType.ReplicaSetNoPrimary; + } + if (options?.loadBalanced) { + return common_1.TopologyType.LoadBalanced; + } + return common_1.TopologyType.Unknown; +} +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + */ +function createAndConnectServer(topology, serverDescription) { + topology.emitAndLog(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address)); + const server = new server_1.Server(topology, serverDescription, topology.s.options); + for (const event of constants_1.SERVER_RELAY_EVENTS) { + server.on(event, (e) => topology.emit(event, e)); + } + server.on(server_1.Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + server.connect(); + return server; +} +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +function updateServers(topology, incomingServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + if (server) { + server.s.description = incomingServerDescription; + if (incomingServerDescription.error instanceof error_1.MongoError && + incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.ResetPool)) { + const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); + server.pool.clear({ interruptInUseConnections }); + } + else if (incomingServerDescription.error == null) { + const newTopologyType = topology.s.description.type; + const shouldMarkPoolReady = incomingServerDescription.isDataBearing || + (incomingServerDescription.type !== common_1.ServerType.Unknown && + newTopologyType === common_1.TopologyType.Single); + if (shouldMarkPoolReady) { + server.pool.ready(); + } + } + } + } + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + if (!topology.s.servers.has(serverAddress)) { + continue; + } + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} +function drainWaitQueue(queue, err) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + waitQueueMember.timeoutController.clear(); + if (!waitQueueMember[kCancelled]) { + if (err) { + if (waitQueueMember.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + waitQueueMember.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, err, waitQueueMember.operationName)); + } + } + waitQueueMember.callback(err); + } + } +} +function processWaitQueue(topology) { + if (topology.s.state === common_1.STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new error_1.MongoTopologyClosedError()); + return; + } + const isSharded = topology.description.type === common_1.TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember[kCancelled]) { + continue; + } + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + const previousServer = waitQueueMember.previousServer; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions, previousServer ? [previousServer] : []) + : serverDescriptions; + } + catch (e) { + waitQueueMember.timeoutController.clear(); + if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, e, waitQueueMember.operationName)); + } + waitQueueMember.callback(e); + continue; + } + let selectedServer; + if (selectedDescriptions.length === 0) { + if (!waitQueueMember.waitingLogged) { + if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.INFORMATIONAL)) { + topology.client.mongoLogger?.info(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.WaitingForSuitableServerEvent(waitQueueMember.serverSelector, topology.description, topology.s.serverSelectionTimeoutMS !== 0 + ? topology.s.serverSelectionTimeoutMS - ((0, utils_1.now)() - waitQueueMember.startTime) + : -1, waitQueueMember.operationName)); + } + waitQueueMember.waitingLogged = true; + } + topology[kWaitQueue].push(waitQueueMember); + continue; + } + else if (selectedDescriptions.length === 1) { + selectedServer = topology.s.servers.get(selectedDescriptions[0].address); + } + else { + const descriptions = (0, utils_1.shuffle)(selectedDescriptions, 2); + const server1 = topology.s.servers.get(descriptions[0].address); + const server2 = topology.s.servers.get(descriptions[1].address); + selectedServer = + server1 && server2 && server1.s.operationCount < server2.s.operationCount + ? server1 + : server2; + } + if (!selectedServer) { + const error = new error_1.MongoServerSelectionError('server selection returned a server description but the server was not found in the topology', topology.description); + if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, error, waitQueueMember.operationName)); + } + waitQueueMember.callback(error); + return; + } + const transaction = waitQueueMember.transaction; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + waitQueueMember.timeoutController.clear(); + if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) { + topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, selectedServer.pool.address, waitQueueMember.operationName)); + } + waitQueueMember.callback(undefined, selectedServer); + } + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} +function isStaleServerDescription(topologyDescription, incomingServerDescription) { + const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address); + const currentTopologyVersion = currentServerDescription?.topologyVersion; + return ((0, server_description_1.compareTopologyVersion)(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0); +} +/** @public */ +class ServerCapabilities { + constructor(hello) { + this.minWireVersion = hello.minWireVersion || 0; + this.maxWireVersion = hello.maxWireVersion || 0; + } + get hasAggregationCursor() { + return this.maxWireVersion >= 1; + } + get hasWriteCommands() { + return this.maxWireVersion >= 2; + } + get hasTextSearch() { + return this.minWireVersion >= 0; + } + get hasAuthCommands() { + return this.maxWireVersion >= 1; + } + get hasListCollectionsCommand() { + return this.maxWireVersion >= 3; + } + get hasListIndexesCommand() { + return this.maxWireVersion >= 3; + } + get supportsSnapshotReads() { + return this.maxWireVersion >= 13; + } + get commandsTakeWriteConcern() { + return this.maxWireVersion >= 5; + } + get commandsTakeCollation() { + return this.maxWireVersion >= 5; + } +} +exports.ServerCapabilities = ServerCapabilities; +//# sourceMappingURL=topology.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/topology.js.map b/nodejs/node_modules/mongodb/lib/sdam/topology.js.map new file mode 100644 index 00000000..bbe18cd3 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/topology.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology.js","sourceRoot":"","sources":["../../src/sdam/topology.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AAOjC,4DAAsE;AACtE,4CAcsB;AACtB,oCAQkB;AAElB,kDAA0F;AAC1F,gDAAmD;AACnD,wDAA6E;AAG7E,oCAUkB;AAClB,qCAWkB;AAClB,qCAOkB;AAElB,qCAAyE;AACzE,6DAAiF;AACjF,yDAAuF;AACvF,uEAKmC;AACnC,+CAAgE;AAChE,iEAA6D;AAE7D,eAAe;AACf,IAAI,qBAAqB,GAAG,CAAC,CAAC;AAE9B,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,qBAAY,CAAC,EAAE,CAAC,qBAAY,EAAE,yBAAgB,CAAC;IAChD,CAAC,yBAAgB,CAAC,EAAE,CAAC,yBAAgB,EAAE,sBAAa,EAAE,wBAAe,EAAE,qBAAY,CAAC;IACpF,CAAC,wBAAe,CAAC,EAAE,CAAC,wBAAe,EAAE,sBAAa,EAAE,qBAAY,CAAC;IACjE,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,qBAAY,CAAC;CAC/C,CAAC,CAAC;AAEH,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC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C9D,yBAAyB,CAAC,OAAO,CAClC,CAAC;IACF,MAAM,sBAAsB,GAAG,wBAAwB,EAAE,eAAe,CAAC;IACzE,OAAO,CACL,IAAA,2CAAsB,EAAC,sBAAsB,EAAE,yBAAyB,CAAC,eAAe,CAAC,GAAG,CAAC,CAC9F,CAAC;AACJ,CAAC;AAED,cAAc;AACd,MAAa,kBAAkB;IAI7B,YAAY,KAAe;QACzB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,cAAc,IAAI,CAAC,CAAC;QAChD,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,cAAc,IAAI,CAAC,CAAC;IAClD,CAAC;IAED,IAAI,oBAAoB;QACtB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,gBAAgB;QAClB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,eAAe;QACjB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,yBAAyB;QAC3B,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC;IACnC,CAAC;IAED,IAAI,wBAAwB;QAC1B,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,qBAAqB;QACvB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,CAAC;IAClC,CAAC;CACF;AA3CD,gDA2CC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/topology_description.js b/nodejs/node_modules/mongodb/lib/sdam/topology_description.js new file mode 100644 index 00000000..6ee1b0c2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/topology_description.js @@ -0,0 +1,360 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TopologyDescription = void 0; +const WIRE_CONSTANTS = require("../cmap/wire_protocol/constants"); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const common_1 = require("./common"); +const server_description_1 = require("./server_description"); +// constants related to compatibility checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; +const MONGOS_OR_UNKNOWN = new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + common_1.ServerType.RSSecondary, + common_1.ServerType.RSArbiter, + common_1.ServerType.RSOther +]); +/** + * Representation of a deployment of servers + * @public + */ +class TopologyDescription { + /** + * Create a TopologyDescription + */ + constructor(topologyType, serverDescriptions = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) { + options = options ?? {}; + this.type = topologyType ?? common_1.TopologyType.Unknown; + this.servers = serverDescriptions ?? new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; + this.localThresholdMS = options.localThresholdMS ?? 15; + this.setName = setName ?? null; + this.maxElectionId = maxElectionId ?? null; + this.maxSetVersion = maxSetVersion ?? null; + this.commonWireVersion = commonWireVersion ?? 0; + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if (serverDescription.type === common_1.ServerType.Unknown || + serverDescription.type === common_1.ServerType.LoadBalancer) { + continue; + } + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + // Whenever a client updates the TopologyDescription from a hello response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + this.logicalSessionTimeoutMinutes = null; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = null; + break; + } + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes); + } + } + } + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev, srvMaxHosts = 0) { + /** The SRV addresses defines the set of addresses we should be using */ + const incomingHostnames = ev.hostnames(); + const currentHostnames = new Set(this.servers.keys()); + const hostnamesToAdd = new Set(incomingHostnames); + const hostnamesToRemove = new Set(); + for (const hostname of currentHostnames) { + // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames + hostnamesToAdd.delete(hostname); + if (!incomingHostnames.has(hostname)) { + // If the SRV Records no longer include this hostname + // we have to stop using it + hostnamesToRemove.add(hostname); + } + } + if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) { + // No new hosts to add and none to remove + return this; + } + const serverDescriptions = new Map(this.servers); + for (const removedHost of hostnamesToRemove) { + serverDescriptions.delete(removedHost); + } + if (hostnamesToAdd.size > 0) { + if (srvMaxHosts === 0) { + // Add all! + for (const hostToAdd of hostnamesToAdd) { + serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd)); + } + } + else if (serverDescriptions.size < srvMaxHosts) { + // Add only the amount needed to get us back to srvMaxHosts + const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size); + for (const selectedHostToAdd of selectedHosts) { + serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd)); + } + } + } + return new TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription) { + const address = serverDescription.address; + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } + else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + if (typeof serverDescription.setName === 'string' && + typeof setName === 'string' && + serverDescription.setName !== setName) { + if (topologyType === common_1.TopologyType.Single) { + // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove + serverDescription = new server_description_1.ServerDescription(address); + } + else { + serverDescriptions.delete(address); + } + } + // update the actual server description + serverDescriptions.set(address, serverDescription); + if (topologyType === common_1.TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + if (topologyType === common_1.TopologyType.Unknown) { + if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } + else { + topologyType = topologyTypeForServerType(serverType); + } + } + if (topologyType === common_1.TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } + } + if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } + } + if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } + else if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName); + } + else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + return new TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + get error() { + const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error); + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + return null; + } + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown); + } + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers() { + return Array.from(this.servers.values()).some((sd) => sd.isDataBearing); + } + /** + * Determines if the topology has a definition for the provided address + * @internal + */ + hasServer(address) { + return this.servers.has(address); + } +} +exports.TopologyDescription = TopologyDescription; +function topologyTypeForServerType(serverType) { + switch (serverType) { + case common_1.ServerType.Standalone: + return common_1.TopologyType.Single; + case common_1.ServerType.Mongos: + return common_1.TopologyType.Sharded; + case common_1.ServerType.RSPrimary: + return common_1.TopologyType.ReplicaSetWithPrimary; + case common_1.ServerType.RSOther: + case common_1.ServerType.RSSecondary: + return common_1.TopologyType.ReplicaSetNoPrimary; + default: + return common_1.TopologyType.Unknown; + } +} +function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + if (serverDescription.maxWireVersion >= 17) { + const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId); + const maxElectionIdIsEqual = electionIdComparison === 0; + const maxElectionIdIsLess = electionIdComparison === -1; + const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); + if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) { + // The reported electionId was greater + // or the electionId was equal and reported setVersion was greater + // Always update both values, they are a tuple + maxElectionId = serverDescription.electionId; + maxSetVersion = serverDescription.setVersion; + } + else { + // Stale primary + // replace serverDescription with a default ServerDescription of type "Unknown" + serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + else { + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if (maxSetVersion > serverDescription.setVersion || + (0, utils_1.compareObjectId)(maxElectionId, electionId) > 0) { + // this primary is stale, we must remove it + serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + maxElectionId = serverDescription.electionId; + } + if (serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) { + maxSetVersion = serverDescription.setVersion; + } + } + // We've heard from the primary. Is it the same primary as before? + for (const [address, server] of serverDescriptions) { + if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new server_description_1.ServerDescription(server.address)); + // There can only be one primary + break; + } + } + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach((address) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new server_description_1.ServerDescription(address)); + } + }); + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter((addr) => responseAddresses.indexOf(addr) === -1) + .forEach((address) => { + serverDescriptions.delete(address); + }); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} +function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName = null) { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + if (setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me)) { + serverDescriptions.delete(serverDescription.address); + } + return checkHasPrimary(serverDescriptions); +} +function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName = null) { + const topologyType = common_1.TopologyType.ReplicaSetNoPrimary; + setName = setName ?? serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + serverDescription.allHosts.forEach((address) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new server_description_1.ServerDescription(address)); + } + }); + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + return [topologyType, setName]; +} +function checkHasPrimary(serverDescriptions) { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === common_1.ServerType.RSPrimary) { + return common_1.TopologyType.ReplicaSetWithPrimary; + } + } + return common_1.TopologyType.ReplicaSetNoPrimary; +} +//# sourceMappingURL=topology_description.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sdam/topology_description.js.map b/nodejs/node_modules/mongodb/lib/sdam/topology_description.js.map new file mode 100644 index 00000000..33ff3752 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sdam/topology_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology_description.js","sourceRoot":"","sources":["../../src/sdam/topology_description.ts"],"names":[],"mappings":";;;AACA,kEAAkE;AAClE,oCAAoE;AACpE,oCAAoD;AACpD,qCAAoD;AACpD,6DAAyD;AAGzD,4CAA4C;AAC5C,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,0BAA0B,GAAG,cAAc,CAAC,0BAA0B,CAAC;AAC7E,MAAM,0BAA0B,GAAG,cAAc,CAAC,0BAA0B,CAAC;AAE7E,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAa,CAAC,mBAAU,CAAC,MAAM,EAAE,mBAAU,CAAC,OAAO,CAAC,CAAC,CAAC;AACvF,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAa,CAAC,mBAAU,CAAC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EAAE,EAAE;QAC3D,IAAI,iBAAiB,CAAC,IAAI,KAAK,mBAAU,CAAC,SAAS,EAAE;YACnD,OAAO,qBAAY,CAAC,qBAAqB,CAAC;SAC3C;KACF;IAED,OAAO,qBAAY,CAAC,mBAAmB,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sessions.js b/nodejs/node_modules/mongodb/lib/sessions.js new file mode 100644 index 00000000..46b4a3c8 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sessions.js @@ -0,0 +1,739 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateSessionFromResponse = exports.applySession = exports.ServerSessionPool = exports.ServerSession = exports.maybeClearPinnedConnection = exports.ClientSession = void 0; +const util_1 = require("util"); +const bson_1 = require("./bson"); +const metrics_1 = require("./cmap/metrics"); +const shared_1 = require("./cmap/wire_protocol/shared"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +const mongo_types_1 = require("./mongo_types"); +const execute_operation_1 = require("./operations/execute_operation"); +const run_command_1 = require("./operations/run_command"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const common_1 = require("./sdam/common"); +const transactions_1 = require("./transactions"); +const utils_1 = require("./utils"); +const write_concern_1 = require("./write_concern"); +const minWireVersionForShardedTransactions = 8; +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); +/** @internal Accumulates total number of increments to add to txnNumber when applying session to command */ +const kTxnNumberIncrement = Symbol('txnNumberIncrement'); +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +class ClientSession extends mongo_types_1.TypedEventEmitter { + /** + * Create a client session. + * @internal + * @param client - The current client + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor(client, sessionPool, options, clientOptions) { + super(); + /** @internal */ + this[_a] = false; + if (client == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a MongoClient'); + } + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + options = options ?? {}; + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive'); + } + } + this.client = client; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + this.explicit = !!options.explicit; + this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null; + this[kTxnNumberIncrement] = 0; + const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; + this.supports = { + // if we can enable causal consistency, do so by default + causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue + }; + this.clusterTime = options.initialClusterTime; + this.operationTime = undefined; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new transactions_1.Transaction(); + } + /** The server id associated with this session */ + get id() { + return this[kServerSession]?.id; + } + get serverSession() { + let serverSession = this[kServerSession]; + if (serverSession == null) { + if (this.explicit) { + throw new error_1.MongoRuntimeError('Unexpected null serverSession for an explicit session'); + } + if (this.hasEnded) { + throw new error_1.MongoRuntimeError('Unexpected null serverSession for an ended implicit session'); + } + serverSession = this.sessionPool.acquire(); + this[kServerSession] = serverSession; + } + return serverSession; + } + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled() { + return this[kSnapshotEnabled]; + } + get loadBalanced() { + return this.client.topology?.description.type === common_1.TopologyType.LoadBalanced; + } + /** @internal */ + get pinnedConnection() { + return this[kPinnedConnection]; + } + /** @internal */ + pin(conn) { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + this[kPinnedConnection] = conn; + conn.emit(constants_1.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR); + } + /** @internal */ + unpin(options) { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + this.transaction.unpinServer(); + } + get isPinned() { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + */ + async endSession(options) { + try { + if (this.inTransaction()) { + await this.abortTransaction(); + } + if (!this.hasEnded) { + const serverSession = this[kServerSession]; + if (serverSession != null) { + // release the server session back to the pool + this.sessionPool.release(serverSession); + // Make sure a new serverSession never makes it onto this ClientSession + Object.defineProperty(this, kServerSession, { + value: ServerSession.clone(serverSession), + writable: false + }); + } + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + } + } + catch { + // spec indicates that we should ignore all errors for `endSessions` + } + finally { + maybeClearPinnedConnection(this, { force: true, ...options }); + } + } + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime) { + if (!clusterTime || typeof clusterTime !== 'object') { + throw new error_1.MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp'); + } + if (!clusterTime.signature || + clusterTime.signature.hash?._bsontype !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'bigint' && + typeof clusterTime.signature.keyId !== 'number' && + clusterTime.signature.keyId?._bsontype !== 'Long') // apparently we decode the key to number? + ) { + throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId'); + } + (0, common_1._advanceClusterTime)(this, clusterTime); + } + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + if (this.id == null || session.id == null) { + return false; + } + return utils_1.ByteUtils.equals(this.id.id.buffer, session.id.id.buffer); + } + /** + * Increment the transaction number on the internal ServerSession + * + * @privateRemarks + * This helper increments a value stored on the client session that will be + * added to the serverSession's txnNumber upon applying it to a command. + * This is because the serverSession is lazily acquired after a connection is obtained + */ + incrementTransactionNumber() { + this[kTxnNumberIncrement] += 1; + } + /** @returns whether this session is currently in a transaction or not */ + inTransaction() { + return this.transaction.isActive; + } + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options) { + if (this[kSnapshotEnabled]) { + throw new error_1.MongoCompatibilityError('Transactions are not supported in snapshot sessions'); + } + if (this.inTransaction()) { + throw new error_1.MongoTransactionError('Transaction already in progress'); + } + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + const topologyMaxWireVersion = (0, utils_1.maxWireVersion)(this.client.topology); + if ((0, shared_1.isSharded)(this.client.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions) { + throw new error_1.MongoCompatibilityError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new transactions_1.Transaction({ + readConcern: options?.readConcern ?? + this.defaultTransactionOptions.readConcern ?? + this.clientOptions?.readConcern, + writeConcern: options?.writeConcern ?? + this.defaultTransactionOptions.writeConcern ?? + this.clientOptions?.writeConcern, + readPreference: options?.readPreference ?? + this.defaultTransactionOptions.readPreference ?? + this.clientOptions?.readPreference, + maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS + }); + this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION); + } + /** + * Commits the currently active transaction in this session. + */ + async commitTransaction() { + return endTransactionAsync(this, 'commitTransaction'); + } + /** + * Aborts the currently active transaction in this session. + */ + async abortTransaction() { + return endTransactionAsync(this, 'abortTransaction'); + } + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON() { + throw new error_1.MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + /** + * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed. + * + * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations. + * + * @remarks + * This function: + * - If all operations successfully complete and the `commitTransaction` operation is successful, then this function will return the result of the provided function. + * - If the transaction is unable to complete or an error is thrown from within the provided function, then this function will throw an error. + * - If the transaction is manually aborted within the provided function it will not throw. + * - May be called multiple times if the driver needs to attempt to retry the operations. + * + * Checkout a descriptive example here: + * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions + * + * @param fn - callback to run within a transaction + * @param options - optional settings for the transaction + * @returns A raw command response or undefined + */ + async withTransaction(fn, options) { + const startTime = (0, utils_1.now)(); + return attemptTransaction(this, startTime, fn, options); + } +} +exports.ClientSession = ClientSession; +_a = kSnapshotEnabled; +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); +function hasNotTimedOut(startTime, max) { + return (0, utils_1.calculateDurationInMs)(startTime) < max; +} +function isUnknownTransactionCommitResult(err) { + const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + return (isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern)); +} +function maybeClearPinnedConnection(session, options) { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options?.error; + if (session.inTransaction() && + error && + error instanceof error_1.MongoError && + error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + return; + } + const topology = session.client.topology; + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn && topology != null) { + const servers = Array.from(topology.s.servers.values()); + const loadBalancer = servers[0]; + if (options?.error == null || options?.force) { + loadBalancer.pool.checkIn(conn); + conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION + ? metrics_1.ConnectionPoolMetrics.TXN + : metrics_1.ConnectionPoolMetrics.CURSOR); + if (options?.forceClear) { + loadBalancer.pool.clear({ serviceId: conn.serviceId }); + } + } + session[kPinnedConnection] = undefined; + } +} +exports.maybeClearPinnedConnection = maybeClearPinnedConnection; +function isMaxTimeMSExpiredError(err) { + if (err == null || !(err instanceof error_1.MongoServerError)) { + return false; + } + return (err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired)); +} +function attemptTransactionCommit(session, startTime, fn, result, options) { + return session.commitTransaction().then(() => result, (err) => { + if (err instanceof error_1.MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err)) { + if (err.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult)) { + return attemptTransactionCommit(session, startTime, fn, result, options); + } + if (err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + return attemptTransaction(session, startTime, fn, options); + } + } + throw err; + }); +} +const USER_EXPLICIT_TXN_END_STATES = new Set([ + transactions_1.TxnState.NO_TRANSACTION, + transactions_1.TxnState.TRANSACTION_COMMITTED, + transactions_1.TxnState.TRANSACTION_ABORTED +]); +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} +function attemptTransaction(session, startTime, fn, options = {}) { + session.startTransaction(options); + let promise; + try { + promise = fn(session); + } + catch (err) { + promise = Promise.reject(err); + } + if (!(0, utils_1.isPromiseLike)(promise)) { + session.abortTransaction().catch(() => null); + return Promise.reject(new error_1.MongoInvalidArgumentError('Function provided to `withTransaction` must return a Promise')); + } + return promise.then(result => { + if (userExplicitlyEndedTransaction(session)) { + return result; + } + return attemptTransactionCommit(session, startTime, fn, result, options); + }, err => { + function maybeRetryOrThrow(err) { + if (err instanceof error_1.MongoError && + err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) { + return attemptTransaction(session, startTime, fn, options); + } + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult); + } + throw err; + } + if (session.inTransaction()) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + return maybeRetryOrThrow(err); + }); +} +const endTransactionAsync = (0, util_1.promisify)(endTransaction); +function endTransaction(session, commandName, callback) { + // handle any initial problematic cases + const txnState = session.transaction.state; + if (txnState === transactions_1.TxnState.NO_TRANSACTION) { + callback(new error_1.MongoTransactionError('No transaction started')); + return; + } + if (commandName === 'commitTransaction') { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } + else { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + callback(); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction twice')); + return; + } + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + // construct and send the command + const command = { [commandName]: 1 }; + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } + else if (session.clientOptions && session.clientOptions.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeoutMS: 10000 }, writeConcern, { w: 'majority' }); + } + if (writeConcern) { + write_concern_1.WriteConcern.apply(command, writeConcern); + } + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + function commandHandler(error) { + if (commandName !== 'commitTransaction') { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); + } + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED); + if (error instanceof error_1.MongoError) { + if ((0, error_1.isRetryableWriteError)(error) || + error instanceof error_1.MongoWriteConcernError || + isMaxTimeMSExpiredError(error)) { + if (isUnknownTransactionCommitResult(error)) { + error.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult); + // per txns spec, must unpin session in this case + session.unpin({ error }); + } + } + else if (error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + session.unpin({ error }); + } + } + callback(error); + } + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + const handleFirstCommandAttempt = (error) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + if (error instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(error)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + })).then(() => commandHandler(), commandHandler); + return; + } + commandHandler(error); + }; + // send the command + (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + })).then(() => handleFirstCommandAttempt(), handleFirstCommandAttempt); +} +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +class ServerSession { + /** @internal */ + constructor() { + this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) }; + this.lastUse = (0, utils_1.now)(); + this.txnNumber = 0; + this.isDirty = false; + } + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round((((0, utils_1.calculateDurationInMs)(this.lastUse) % 86400000) % 3600000) / 60000); + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } + /** + * @internal + * Cloning meant to keep a readable reference to the server session data + * after ClientSession has ended + */ + static clone(serverSession) { + const arrayBuffer = new ArrayBuffer(16); + const idBytes = Buffer.from(arrayBuffer); + idBytes.set(serverSession.id.id.buffer); + const id = new bson_1.Binary(idBytes, serverSession.id.id.sub_type); + // Manual prototype construction to avoid modifying the constructor of this class + return Object.setPrototypeOf({ + id: { id }, + lastUse: serverSession.lastUse, + txnNumber: serverSession.txnNumber, + isDirty: serverSession.isDirty + }, ServerSession.prototype); + } +} +exports.ServerSession = ServerSession; +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +class ServerSessionPool { + constructor(client) { + if (client == null) { + throw new error_1.MongoRuntimeError('ServerSessionPool requires a MongoClient'); + } + this.client = client; + this.sessions = new utils_1.List(); + } + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession is created. + */ + acquire() { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + let session = null; + // Try to obtain from session pool + while (this.sessions.length > 0) { + const potentialSession = this.sessions.shift(); + if (potentialSession != null && + (!!this.client.topology?.loadBalanced || + !potentialSession.hasTimedOut(sessionTimeoutMinutes))) { + session = potentialSession; + break; + } + } + // If nothing valid came from the pool make a new one + if (session == null) { + session = new ServerSession(); + } + return session; + } + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * + * @param session - The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + if (!sessionTimeoutMinutes) { + return; + } + this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes)); + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} +exports.ServerSessionPool = ServerSessionPool; +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + * + * @internal + */ +function applySession(session, command, options) { + if (session.hasEnded) { + return new error_1.MongoExpiredSessionError(); + } + // May acquire serverSession here + const serverSession = session.serverSession; + if (serverSession == null) { + return new error_1.MongoRuntimeError('Unable to acquire server session'); + } + if (options.writeConcern?.w === 0) { + if (session && session.explicit) { + // Error if user provided an explicit session to an unacknowledged write (SPEC-1019) + return new error_1.MongoAPIError('Cannot have explicit session with unacknowledged writes'); + } + return; + } + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = (0, utils_1.now)(); + command.lsid = serverSession.id; + const inTxnOrTxnCommand = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command); + const isRetryableWrite = !!options.willRetryWrite; + if (isRetryableWrite || inTxnOrTxnCommand) { + serverSession.txnNumber += session[kTxnNumberIncrement]; + session[kTxnNumberIncrement] = 0; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber); + } + if (!inTxnOrTxnCommand) { + if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION); + } + if (session.supports.causalConsistency && + session.operationTime && + (0, utils_1.commandSupportsReadConcern)(command)) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + else if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); + } + } + return; + } + // now attempt to apply transaction-specific sessions data + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + const readConcern = session.transaction.options.readConcern || session?.clientOptions?.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } + return; +} +exports.applySession = applySession; +function updateSessionFromResponse(session, document) { + if (document.$clusterTime) { + (0, common_1._advanceClusterTime)(session, document.$clusterTime); + } + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } + if (session?.[kSnapshotEnabled] && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = document.cursor?.atClusterTime || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; + } + } +} +exports.updateSessionFromResponse = updateSessionFromResponse; +//# sourceMappingURL=sessions.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sessions.js.map b/nodejs/node_modules/mongodb/lib/sessions.js.map new file mode 100644 index 00000000..7b98ed35 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sessions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":";;;;AAAA,+BAAiC;AAEjC,iCAAqE;AAErE,4CAAuD;AACvD,wDAAwD;AACxD,2CAA+C;AAE/C,mCAeiB;AAEjB,+CAAkD;AAClD,sEAAkE;AAClE,0DAAoE;AACpE,iDAAkD;AAClD,uDAAmD;AACnD,0CAAoF;AACpF,iDAKwB;AACxB,mCAUiB;AACjB,mDAA+C;AAE/C,MAAM,oCAAoC,GAAG,CAAC,CAAC;AA2B/C,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAC/C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAC7C,gBAAgB;AAChB,MAAM,gBAAgB,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACnD,gBAAgB;AAChB,MAAM,iBAAiB,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrD,4GAA4G;AAC5G,MAAM,mBAAmB,GAAG,MAAM,CAAC,oBAAoB,CAAC,C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AAC;KACrD;IAED,IAAI,QAAQ,CAAC,aAAa,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,iBAAiB,EAAE;QAC3E,OAAO,CAAC,oBAAoB,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;KACtD;IAED,IAAI,QAAQ,CAAC,aAAa,IAAI,OAAO,IAAI,OAAO,CAAC,aAAa,EAAE,EAAE;QAChE,OAAO,CAAC,WAAW,CAAC,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC7D;IAED,IAAI,OAAO,EAAE,CAAC,gBAAgB,CAAC,IAAI,OAAO,CAAC,aAAa,CAAC,IAAI,IAAI,EAAE;QACjE,iEAAiE;QACjE,4CAA4C;QAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,EAAE,aAAa,IAAI,QAAQ,CAAC,aAAa,CAAC;QAC/E,IAAI,aAAa,EAAE;YACjB,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAC;SACxC;KACF;AACH,CAAC;AArBD,8DAqBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sort.js b/nodejs/node_modules/mongodb/lib/sort.js new file mode 100644 index 00000000..c04b6b54 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sort.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatSort = void 0; +const error_1 = require("./error"); +/** @internal */ +function prepareDirection(direction = 1) { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) + return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} +/** @internal */ +function isMeta(t) { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} +/** @internal */ +function isPair(t) { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; + } + catch (e) { + return false; + } + } + return false; +} +function isDeep(t) { + return Array.isArray(t) && Array.isArray(t[0]); +} +function isMap(t) { + return t instanceof Map && t.size > 0; +} +/** @internal */ +function pairToMap(v) { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} +/** @internal */ +function deepToMap(t) { + const sortEntries = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} +/** @internal */ +function stringsToMap(t) { + const sortEntries = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} +/** @internal */ +function objectToMap(t) { + const sortEntries = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** @internal */ +function mapToMap(t) { + const sortEntries = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +function formatSort(sort, direction) { + if (sort == null) + return undefined; + if (typeof sort === 'string') + return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) + return undefined; + if (isDeep(sort)) + return deepToMap(sort); + if (isPair(sort)) + return pairToMap(sort); + return stringsToMap(sort); +} +exports.formatSort = formatSort; +//# sourceMappingURL=sort.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/sort.js.map b/nodejs/node_modules/mongodb/lib/sort.js.map new file mode 100644 index 00000000..4072af4c --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/sort.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.js","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":";;;AAAA,mCAAoD;AAiCpD,gBAAgB;AAChB,SAAS,gBAAgB,CAAC,YAAiB,CAAC;IAC1C,MAAM,KAAK,GAAG,GAAG,S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,gBAAgB,CAAC,CAAC,CAAC;KACpB,CAAC,CAAC;IACH,OAAO,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;AAC9B,CAAC;AAED,iFAAiF;AACjF,SAAgB,UAAU,CACxB,IAAsB,EACtB,SAAyB;IAEzB,IAAI,IAAI,IAAI,IAAI;QAAE,OAAO,SAAS,CAAC;IACnC,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACpF,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,MAAM,IAAI,iCAAyB,CACjC,wBAAwB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,8BAA8B,CAC3E,CAAC;KACH;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACxB,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;KAChG;IACD,IAAI,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IACnC,IAAI,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzC,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC;AAlBD,gCAkBC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/transactions.js b/nodejs/node_modules/mongodb/lib/transactions.js new file mode 100644 index 00000000..a4235b07 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/transactions.js @@ -0,0 +1,138 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTransactionCommand = exports.Transaction = exports.TxnState = void 0; +const error_1 = require("./error"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const write_concern_1 = require("./write_concern"); +/** @internal */ +exports.TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +}); +const stateMachine = { + [exports.TxnState.NO_TRANSACTION]: [exports.TxnState.NO_TRANSACTION, exports.TxnState.STARTING_TRANSACTION], + [exports.TxnState.STARTING_TRANSACTION]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_IN_PROGRESS]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_COMMITTED]: [ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.NO_TRANSACTION + ], + [exports.TxnState.TRANSACTION_ABORTED]: [exports.TxnState.STARTING_TRANSACTION, exports.TxnState.NO_TRANSACTION], + [exports.TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.NO_TRANSACTION + ] +}; +const ACTIVE_STATES = new Set([ + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.TRANSACTION_IN_PROGRESS +]); +const COMMITTED_STATES = new Set([ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED +]); +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +class Transaction { + /** Create a transaction @internal */ + constructor(options) { + options = options ?? {}; + this.state = exports.TxnState.NO_TRANSACTION; + this.options = {}; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new error_1.MongoTransactionError('Transactions do not support unacknowledged write concern'); + } + this.options.writeConcern = writeConcern; + } + if (options.readConcern) { + this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options); + } + if (options.readPreference) { + this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options); + } + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + /** @internal */ + get server() { + return this._pinnedServer; + } + get recoveryToken() { + return this._recoveryToken; + } + get isPinned() { + return !!this.server; + } + /** @returns Whether the transaction has started */ + get isStarting() { + return this.state === exports.TxnState.STARTING_TRANSACTION; + } + /** + * @returns Whether this session is presently in a transaction + */ + get isActive() { + return ACTIVE_STATES.has(this.state); + } + get isCommitted() { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if (this.state === exports.TxnState.NO_TRANSACTION || + this.state === exports.TxnState.STARTING_TRANSACTION || + this.state === exports.TxnState.TRANSACTION_ABORTED) { + this.unpinServer(); + } + return; + } + throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`); + } + /** @internal */ + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; + } + } + /** @internal */ + unpinServer() { + this._pinnedServer = undefined; + } +} +exports.Transaction = Transaction; +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} +exports.isTransactionCommand = isTransactionCommand; +//# sourceMappingURL=transactions.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/transactions.js.map b/nodejs/node_modules/mongodb/lib/transactions.js.map new file mode 100644 index 00000000..021aa3b2 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/transactions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transactions.js","sourceRoot":"","sources":["../src/transactions.ts"],"names":[],"mappings":";;;AACA,mCAAmE;AAEnE,iDAAmE;AAEnE,uDAAmD;AAEnD,mDAA+C;AAE/C,gBAAgB;AACH,QAAA,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,cAAc,EAAE,gBAAgB;IAChC,oBAAoB,EAAE,sBAAsB;IAC5C,uBAAuB,EAAE,yBAAyB;IAClD,qBAAqB,EAAE,uBAAuB;IAC9C,2BAA2B,EAAE,6BAA6B;IAC1D,mBAAmB,EAAE,qBAAqB;CAClC,CAAC,CAAC;AAKZ,MAAM,YAAY,GAAwC;IACxD,CAAC,gBAAQ,CAAC,cAAc,CAAC,EAAE,CAAC,gBAAQ,CAAC,cAAc,EAAE,gBAAQ,CAAC,oBAAoB,CAAC;IACnF,CAAC,gBAAQ,CAAC,oBAAoB,CAAC,EAAE;QAC/B,gBAAQ,CAAC,uBAAuB;QAChC,gBAAQ,CAAC,qBAAqB;QAC9B,gBAAQ,CAAC,2BAA2B;QACpC,gBAAQ,CAAC,mBAAmB;KAC7B;IACD,CAAC,gBAAQ,CAAC,uBAAuB,CAAC,EAAE;QAClC,gBAAQ,CAAC,uBAAuB;QAChC,gBAAQ,CAAC,qBAAqB;QAC9B,gBAAQ,CAAC,mBAAmB;KAC7B;IACD,CAAC,gBAAQ,CAAC,qBAAqB,CAAC,EAAE;QAChC,gBAAQ,CAAC,qBAAqB;QAC9B,gBAAQ,CAAC,2BAA2B;QACpC,gBAAQ,CAAC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ACR;QAED,MAAM,IAAI,yBAAiB,CACzB,4CAA4C,IAAI,CAAC,KAAK,SAAS,SAAS,GAAG,CAC5E,CAAC;IACJ,CAAC;IAED,gBAAgB;IAChB,SAAS,CAAC,MAAc;QACtB,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC;SAC7B;IACH,CAAC;IAED,gBAAgB;IAChB,WAAW;QACT,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;IACjC,CAAC;CACF;AAxGD,kCAwGC;AAED,SAAgB,oBAAoB,CAAC,OAAiB;IACpD,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC;AACnE,CAAC;AAFD,oDAEC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/utils.js b/nodejs/node_modules/mongodb/lib/utils.js new file mode 100644 index 00000000..85f6be0b --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/utils.js @@ -0,0 +1,1036 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.TimeoutController = exports.request = exports.matchesParentDomain = exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.maxWireVersion = exports.uuidV4 = exports.makeCounter = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.hostMatchesWildcards = exports.ByteUtils = void 0; +exports.once = exports.randomBytes = exports.promiseWithResolvers = exports.isHostMatch = exports.COSMOS_DB_MSG = void 0; +const crypto = require("crypto"); +const http = require("http"); +const timers_1 = require("timers"); +const url = require("url"); +const url_1 = require("url"); +const util_1 = require("util"); +const bson_1 = require("./bson"); +const constants_1 = require("./cmap/wire_protocol/constants"); +const constants_2 = require("./constants"); +const error_1 = require("./error"); +const read_concern_1 = require("./read_concern"); +const read_preference_1 = require("./read_preference"); +const common_1 = require("./sdam/common"); +const write_concern_1 = require("./write_concern"); +exports.ByteUtils = { + toLocalBufferType(buffer) { + return Buffer.isBuffer(buffer) + ? buffer + : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + equals(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + compare(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + toBase64(uint8array) { + return exports.ByteUtils.toLocalBufferType(uint8array).toString('base64'); + } +}; +/** + * Determines if a connection's address matches a user provided list + * of domain wildcards. + */ +function hostMatchesWildcards(host, wildcards) { + for (const wildcard of wildcards) { + if (host === wildcard || + (wildcard.startsWith('*.') && host?.endsWith(wildcard.substring(2, wildcard.length))) || + (wildcard.startsWith('*/') && host?.endsWith(wildcard.substring(2, wildcard.length)))) { + return true; + } + } + return false; +} +exports.hostMatchesWildcards = hostMatchesWildcards; +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +function normalizeHintField(hint) { + let finalHint = undefined; + if (typeof hint === 'string') { + finalHint = hint; + } + else if (Array.isArray(hint)) { + finalHint = {}; + hint.forEach(param => { + finalHint[param] = 1; + }); + } + else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (const name in hint) { + finalHint[name] = hint[name]; + } + } + return finalHint; +} +exports.normalizeHintField = normalizeHintField; +const TO_STRING = (object) => Object.prototype.toString.call(object); +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ +function isObject(arg) { + return '[object Object]' === TO_STRING(arg); +} +exports.isObject = isObject; +/** @internal */ +function mergeOptions(target, source) { + return { ...target, ...source }; +} +exports.mergeOptions = mergeOptions; +/** @internal */ +function filterOptions(options, names) { + const filterOptions = {}; + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; + } + } + // Filtered options + return filterOptions; +} +exports.filterOptions = filterOptions; +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + if (db && db.s.options?.retryWrites) { + target.retryWrites = true; + } + return target; +} +exports.applyRetryableWrites = applyRetryableWrites; +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ +/** + * Checks if a given value is a Promise + * + * @typeParam T - The resolution type of the possible promise + * @param value - An object that could be a promise + * @returns true if the provided value is a Promise + */ +function isPromiseLike(value) { + return (value != null && + typeof value === 'object' && + 'then' in value && + typeof value.then === 'function'); +} +exports.isPromiseLike = isPromiseLike; +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } + else { + throw new error_1.MongoCompatibilityError(`Current topology does not support collation`); + } + } +} +exports.decorateWithCollation = decorateWithCollation; +/** + * Applies a read concern to a given command. + * @internal + * + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} +exports.decorateWithReadConcern = decorateWithReadConcern; +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +function decorateWithExplain(command, explain) { + if (command.explain) { + return command; + } + return { explain: command, verbosity: explain.verbosity }; +} +exports.decorateWithExplain = decorateWithExplain; +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @throws MongoNotConnectedError + * @internal + */ +function getTopology(provider) { + // MongoClient or ClientSession or AbstractCursor + if ('topology' in provider && provider.topology) { + return provider.topology; + } + else if ('client' in provider && provider.client.topology) { + return provider.client.topology; + } + throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} +exports.getTopology = getTopology; +/** @internal */ +function ns(ns) { + return MongoDBNamespace.fromString(ns); +} +exports.ns = ns; +/** @public */ +class MongoDBNamespace { + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db, collection) { + this.db = db; + this.collection = collection; + this.collection = collection === '' ? undefined : collection; + } + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + withCollection(collection) { + return new MongoDBCollectionNamespace(this.db, collection); + } + static fromString(namespace) { + if (typeof namespace !== 'string' || namespace === '') { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + const [db, ...collectionParts] = namespace.split('.'); + const collection = collectionParts.join('.'); + return new MongoDBNamespace(db, collection === '' ? undefined : collection); + } +} +exports.MongoDBNamespace = MongoDBNamespace; +/** + * @public + * + * A class representing a collection's namespace. This class enforces (through Typescript) that + * the `collection` portion of the namespace is defined and should only be + * used in scenarios where this can be guaranteed. + */ +class MongoDBCollectionNamespace extends MongoDBNamespace { + constructor(db, collection) { + super(db, collection); + this.collection = collection; + } + static fromString(namespace) { + return super.fromString(namespace); + } +} +exports.MongoDBCollectionNamespace = MongoDBCollectionNamespace; +/** @internal */ +function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} +exports.makeCounter = makeCounter; +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +function uuidV4() { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} +exports.uuidV4 = uuidV4; +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced || topologyOrServer.serverApi?.version) { + // Since we do not have a monitor in the load balanced mode, + // we assume the load-balanced server is always pointed at the latest mongodb version. + // There is a risk that for on-prem deployments + // that don't upgrade immediately that this could alert to the + // application that a feature is available that is actually not. + // We also return the max supported wire version for serverAPI. + return constants_1.MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.hello) { + return topologyOrServer.hello.maxWireVersion; + } + if ('lastHello' in topologyOrServer && typeof topologyOrServer.lastHello === 'function') { + const lastHello = topologyOrServer.lastHello(); + if (lastHello) { + return lastHello.maxWireVersion; + } + } + if (topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null) { + return topologyOrServer.description.maxWireVersion; + } + } + return 0; +} +exports.maxWireVersion = maxWireVersion; +/** @internal */ +function arrayStrictEqual(arr, arr2) { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} +exports.arrayStrictEqual = arrayStrictEqual; +/** @internal */ +function errorStrictEqual(lhs, rhs) { + if (lhs === rhs) { + return true; + } + if (!lhs || !rhs) { + return lhs === rhs; + } + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + if (lhs.message !== rhs.message) { + return false; + } + return true; +} +exports.errorStrictEqual = errorStrictEqual; +/** @internal */ +function makeStateMachine(stateTable) { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); + } + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} +exports.makeStateMachine = makeStateMachine; +/** @internal */ +function now() { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} +exports.now = now; +/** @internal */ +function calculateDurationInMs(started) { + if (typeof started !== 'number') { + return -1; + } + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} +exports.calculateDurationInMs = calculateDurationInMs; +/** @internal */ +function hasAtomicOperators(doc) { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } + } + return false; + } + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} +exports.hasAtomicOperators = hasAtomicOperators; +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +function resolveOptions(parent, options) { + const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent)); + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options?.session; + if (!session?.inTransaction()) { + const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? parent?.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + return result; +} +exports.resolveOptions = resolveOptions; +function isSuperset(set, subset) { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; + } + } + return true; +} +exports.isSuperset = isSuperset; +/** + * Checks if the document is a Hello request + * @internal + */ +function isHello(doc) { + return doc[constants_2.LEGACY_HELLO_COMMAND] || doc.hello ? true : false; +} +exports.isHello = isHello; +/** Returns the items that are uniquely in setA */ +function setDifference(setA, setB) { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} +exports.setDifference = setDifference; +const HAS_OWN = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop); +function isRecord(value, requiredKeys = undefined) { + if (!isObject(value)) { + return false; + } + const ctor = value.constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + // Check to see if some method exists from the Object exists + if (!HAS_OWN(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + if (requiredKeys) { + const keys = Object.keys(value); + return isSuperset(keys, requiredKeys); + } + return true; +} +exports.isRecord = isRecord; +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +function deepCopy(value) { + if (value == null) { + return value; + } + else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)); + } + else if (isRecord(value)) { + const res = {}; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + const ctor = value.constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value); + case 'set': + return new Set(value); + case 'buffer': + return Buffer.from(value); + } + } + return value; +} +exports.deepCopy = deepCopy; +/** + * A sequential list of items in a circularly linked list + * @remarks + * The head node is special, it is always defined and has a value of null. + * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator. + * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero. + * New nodes are declared as object literals with keys always in the same order: next, prev, value. + * @internal + */ +class List { + get length() { + return this.count; + } + get [Symbol.toStringTag]() { + return 'List'; + } + constructor() { + this.count = 0; + // this is carefully crafted: + // declaring a complete and consistently key ordered + // object is beneficial to the runtime optimizations + this.head = { + next: null, + prev: null, + value: null + }; + this.head.next = this.head; + this.head.prev = this.head; + } + toArray() { + return Array.from(this); + } + toString() { + return `head <=> ${this.toArray().join(' <=> ')} <=> head`; + } + *[Symbol.iterator]() { + for (const node of this.nodes()) { + yield node.value; + } + } + *nodes() { + let ptr = this.head.next; + while (ptr !== this.head) { + // Save next before yielding so that we make removing within iteration safe + const { next } = ptr; + yield ptr; + ptr = next; + } + } + /** Insert at end of list */ + push(value) { + this.count += 1; + const newNode = { + next: this.head, + prev: this.head.prev, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + /** Inserts every item inside an iterable instead of the iterable itself */ + pushMany(iterable) { + for (const value of iterable) { + this.push(value); + } + } + /** Insert at front of list */ + unshift(value) { + this.count += 1; + const newNode = { + next: this.head.next, + prev: this.head, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + remove(node) { + if (node === this.head || this.length === 0) { + return null; + } + this.count -= 1; + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + return node.value; + } + /** Removes the first node at the front of the list */ + shift() { + return this.remove(this.head.next); + } + /** Removes the last node at the end of the list */ + pop() { + return this.remove(this.head.prev); + } + /** Iterates through the list and removes nodes where filter returns true */ + prune(filter) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); + } + } + } + clear() { + this.count = 0; + this.head.next = this.head; + this.head.prev = this.head; + } + /** Returns the first item in the list, does not remove */ + first() { + // If the list is empty, value will be the head's null + return this.head.next.value; + } + /** Returns the last item in the list, does not remove */ + last() { + // If the list is empty, value will be the head's null + return this.head.prev.value; + } +} +exports.List = List; +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +class BufferPool { + constructor() { + this.buffers = new List(); + this.totalByteLength = 0; + } + get length() { + return this.totalByteLength; + } + /** Adds a buffer to the internal buffer pool list */ + append(buffer) { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + /** + * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, + * otherwise return null. Size can be negative, caller should error check. + */ + getInt32() { + if (this.totalByteLength < 4) { + return null; + } + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); + } + // Unlikely case: an int32 is split across buffers. + // Use read and put the returned buffer back on top + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + // Put it back. + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + return value; + } + /** Reads the requested number of bytes, optionally consuming them */ + read(size) { + if (typeof size !== 'number' || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + // oversized request returns empty buffer + if (size > this.totalByteLength) { + return Buffer.alloc(0); + } + // We know we have enough, we just don't know how it is spread across chunks + // TODO(NODE-4732): alloc API should change based on raw option + const result = Buffer.allocUnsafe(size); + for (let bytesRead = 0; bytesRead < size;) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + result.set(bytes, bytesRead); + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + return result; + } +} +exports.BufferPool = BufferPool; +/** @public */ +class HostAddress { + constructor(hostString) { + this.host = undefined; + this.port = undefined; + this.socketPath = undefined; + this.isIPv6 = false; + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + if (escapedHost.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(escapedHost); + return; + } + const urlString = `iLoveJS://${escapedHost}`; + let url; + try { + url = new url_1.URL(urlString); + } + catch (urlError) { + const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + const hostname = url.hostname; + const port = url.port; + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + this.host = normalized.toLowerCase(); + if (typeof port === 'number') { + this.port = port; + } + else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } + else { + this.port = 27017; + } + if (this.port === 0) { + throw new error_1.MongoParseError('Invalid port (zero) with hostname'); + } + Object.freeze(this); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new HostAddress('${this.toString()}')`; + } + toString() { + if (typeof this.host === 'string') { + if (this.isIPv6) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; + } + return `${this.socketPath}`; + } + static fromString(s) { + return new HostAddress(s); + } + static fromHostPort(host, port) { + if (host.includes(':')) { + host = `[${host}]`; // IPv6 address + } + return HostAddress.fromString(`${host}:${port}`); + } + static fromSrvRecord({ name, port }) { + return HostAddress.fromHostPort(name, port); + } + toHostPort() { + if (this.socketPath) { + return { host: this.socketPath, port: 0 }; + } + const host = this.host ?? ''; + const port = this.port ?? 0; + return { host, port }; + } +} +exports.HostAddress = HostAddress; +exports.DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk() { + return new bson_1.ObjectId(); + } +}; +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```ts + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +exports.MONGODB_WARNING_CODE = 'MONGODB DRIVER'; +/** @internal */ +function emitWarning(message) { + return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE }); +} +exports.emitWarning = emitWarning; +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +function emitWarningOnce(message) { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} +exports.emitWarningOnce = emitWarningOnce; +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +function enumToString(en) { + return Object.values(en).join(', '); +} +exports.enumToString = enumToString; +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +function supportsRetryableWrites(server) { + if (!server) { + return false; + } + if (server.loadBalanced) { + // Loadbalanced topologies will always support retry writes + return true; + } + if (server.description.logicalSessionTimeoutMinutes != null) { + // that supports sessions + if (server.description.type !== common_1.ServerType.Standalone) { + // and that is not a standalone + return true; + } + } + return false; +} +exports.supportsRetryableWrites = supportsRetryableWrites; +/** + * Fisher–Yates Shuffle + * + * Reference: https://bost.ocks.org/mike/shuffle/ + * @param sequence - items to be shuffled + * @param limit - Defaults to `0`. If nonzero shuffle will slice the randomized array e.g, `.slice(0, limit)` otherwise will return the entire randomized array. + */ +function shuffle(sequence, limit = 0) { + const items = Array.from(sequence); // shallow copy in order to never shuffle the input + if (limit > items.length) { + throw new error_1.MongoRuntimeError('Limit must be less than the number of items'); + } + let remainingItemsToShuffle = items.length; + const lowerBound = limit % items.length === 0 ? 1 : items.length - limit; + while (remainingItemsToShuffle > lowerBound) { + // Pick a remaining element + const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); + remainingItemsToShuffle -= 1; + // And swap it with the current element + const swapHold = items[remainingItemsToShuffle]; + items[remainingItemsToShuffle] = items[randomIndex]; + items[randomIndex] = swapHold; + } + return limit % items.length === 0 ? items : items.slice(lowerBound); +} +exports.shuffle = shuffle; +// TODO(NODE-4936): read concern eligibility for commands should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +function commandSupportsReadConcern(command) { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; + } + return false; +} +exports.commandSupportsReadConcern = commandSupportsReadConcern; +/** + * Compare objectIds. `null` is always less + * - `+1 = oid1 is greater than oid2` + * - `-1 = oid1 is less than oid2` + * - `+0 = oid1 is equal oid2` + */ +function compareObjectId(oid1, oid2) { + if (oid1 == null && oid2 == null) { + return 0; + } + if (oid1 == null) { + return -1; + } + if (oid2 == null) { + return 1; + } + return exports.ByteUtils.compare(oid1.id, oid2.id); +} +exports.compareObjectId = compareObjectId; +function parseInteger(value) { + if (typeof value === 'number') + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + return Number.isNaN(parsedValue) ? null : parsedValue; +} +exports.parseInteger = parseInteger; +function parseUnsignedInteger(value) { + const parsedInt = parseInteger(value); + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; +} +exports.parseUnsignedInteger = parseUnsignedInteger; +/** + * Determines whether a provided address matches the provided parent domain. + * + * If a DNS server were to become compromised SRV records would still need to + * advertise addresses that are under the same domain as the srvHost. + * + * @param address - The address to check against a domain + * @param srvHost - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +function matchesParentDomain(address, srvHost) { + // Remove trailing dot if exists on either the resolved address or the srv hostname + const normalizedAddress = address.endsWith('.') ? address.slice(0, address.length - 1) : address; + const normalizedSrvHost = srvHost.endsWith('.') ? srvHost.slice(0, srvHost.length - 1) : srvHost; + const allCharacterBeforeFirstDot = /^.*?\./; + // Remove all characters before first dot + // Add leading dot back to string so + // an srvHostDomain = '.trusted.site' + // will not satisfy an addressDomain that endsWith '.fake-trusted.site' + const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, '')}`; + const srvHostDomain = `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, '')}`; + return addressDomain.endsWith(srvHostDomain); +} +exports.matchesParentDomain = matchesParentDomain; +async function request(uri, options = {}) { + return new Promise((resolve, reject) => { + const requestOptions = { + method: 'GET', + timeout: 10000, + json: true, + ...url.parse(uri), + ...options + }; + const req = http.request(requestOptions, res => { + res.setEncoding('utf8'); + let data = ''; + res.on('data', d => { + data += d; + }); + res.once('end', () => { + if (options.json === false) { + resolve(data); + return; + } + try { + const parsed = JSON.parse(data); + resolve(parsed); + } + catch { + // TODO(NODE-3483) + reject(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + req.once('timeout', () => req.destroy(new error_1.MongoNetworkTimeoutError(`Network request to ${uri} timed out after ${options.timeout} ms`))); + req.once('error', error => reject(error)); + req.end(); + }); +} +exports.request = request; +/** + * A custom AbortController that aborts after a specified timeout. + * + * If `timeout` is undefined or \<=0, the abort controller never aborts. + * + * This class provides two benefits over the built-in AbortSignal.timeout() method. + * - This class provides a mechanism for cancelling the timeout + * - This class supports infinite timeouts by interpreting a timeout of 0 as infinite. This is + * consistent with existing timeout options in the Node driver (serverSelectionTimeoutMS, for example). + * @internal + */ +class TimeoutController extends AbortController { + constructor(timeout = 0, timeoutId = timeout > 0 ? (0, timers_1.setTimeout)(() => this.abort(), timeout) : null) { + super(); + this.timeoutId = timeoutId; + } + clear() { + if (this.timeoutId != null) { + (0, timers_1.clearTimeout)(this.timeoutId); + } + this.timeoutId = null; + } +} +exports.TimeoutController = TimeoutController; +/** @internal */ +exports.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/; +/** @internal */ +exports.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/; +/** @internal */ +exports.DOCUMENT_DB_MSG = 'You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb'; +/** @internal */ +exports.COSMOS_DB_MSG = 'You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb'; +/** @internal */ +function isHostMatch(match, host) { + return host && match.test(host.toLowerCase()) ? true : false; +} +exports.isHostMatch = isHostMatch; +function promiseWithResolvers() { + let resolve; + let reject; + const promise = new Promise(function withResolversExecutor(promiseResolve, promiseReject) { + resolve = promiseResolve; + reject = promiseReject; + }); + return { promise, resolve, reject }; +} +exports.promiseWithResolvers = promiseWithResolvers; +exports.randomBytes = (0, util_1.promisify)(crypto.randomBytes); +/** + * Replicates the events.once helper. + * + * Removes unused signal logic and It **only** supports 0 or 1 argument events. + * + * @param ee - An event emitter that may emit `ev` + * @param name - An event name to wait for + */ +async function once(ee, name) { + const { promise, resolve, reject } = promiseWithResolvers(); + const onEvent = (data) => resolve(data); + const onError = (error) => reject(error); + ee.once(name, onEvent).once('error', onError); + try { + const res = await promise; + ee.off('error', onError); + return res; + } + catch (error) { + ee.off(name, onEvent); + throw error; + } +} +exports.once = once; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/utils.js.map b/nodejs/node_modules/mongodb/lib/utils.js.map new file mode 100644 index 00000000..87a1f001 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;AAAA,iCAAiC;AAGjC,6BAA6B;AAC7B,mCAAkD;AAClD,2BAA2B;AAC3B,6BAA0B;AAC1B,+BAAiC;AAEjC,iCAAqE;AAErE,8DAA4E;AAE5E,2CAAmD;AAInD,mCAQiB;AAKjB,iDAA6C;AAC7C,uDAAmD;AACnD,0CAA2C;AAI3C,mDAA+C;AAUlC,QAAA,SAAS,GAAG;IACvB,iBAAiB,CAAa,MAA2B;QACvD,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;YAC5B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,CAAa,IAAgB,EAAE,IAAgB;QACnD,OAAO,iBAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACxD,CAAC;IAED,OAAO,CAAa,IAAgB,EAAE,IAAgB;QACpD,OAAO,iBAAS,CAAC,iB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CAEC;AAED,SAAgB,oBAAoB;IAClC,IAAI,OAAoE,CAAC;IACzE,IAAI,MAAmE,CAAC;IACxE,MAAM,OAAO,GAAG,IAAI,OAAO,CAAI,SAAS,qBAAqB,CAAC,cAAc,EAAE,aAAa;QACzF,OAAO,GAAG,cAAc,CAAC;QACzB,MAAM,GAAG,aAAa,CAAC;IACzB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAW,CAAC;AAC/C,CAAC;AARD,oDAQC;AAEY,QAAA,WAAW,GAAG,IAAA,gBAAS,EAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAEzD;;;;;;;GAOG;AACI,KAAK,UAAU,IAAI,CAAI,EAAgB,EAAE,IAAY;IAC1D,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,oBAAoB,EAAK,CAAC;IAC/D,MAAM,OAAO,GAAG,CAAC,IAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,CAAC,KAAY,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhD,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9C,IAAI;QACF,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC;QAC1B,EAAE,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACzB,OAAO,GAAG,CAAC;KACZ;IAAC,OAAO,KAAK,EAAE;QACd,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtB,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAdD,oBAcC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/write_concern.js b/nodejs/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 00000000..a3df0b0f --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/write_concern.js @@ -0,0 +1,86 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WriteConcern = exports.WRITE_CONCERN_KEYS = void 0; +exports.WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://www.mongodb.com/docs/manual/reference/write-concern/ + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely + * @param journal - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version. + */ + constructor(w, wtimeoutMS, journal, fsync) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } + else { + this.w = w; + } + } + if (wtimeoutMS != null) { + this.wtimeoutMS = this.wtimeout = wtimeoutMS; + } + if (journal != null) { + this.journal = this.j = journal; + } + if (fsync != null) { + this.journal = this.j = fsync ? true : false; + } + } + /** + * Apply a write concern to a command document. Will modify and return the command. + */ + static apply(command, writeConcern) { + const wc = {}; + // The write concern document sent to the server has w/wtimeout/j fields. + if (writeConcern.w != null) + wc.w = writeConcern.w; + if (writeConcern.wtimeoutMS != null) + wc.wtimeout = writeConcern.wtimeoutMS; + if (writeConcern.journal != null) + wc.j = writeConcern.j; + command.writeConcern = wc; + return command; + } + /** Construct a WriteConcern given an options object. */ + static fromOptions(options, inherit) { + if (options == null) + return undefined; + inherit = inherit ?? {}; + let opts; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } + else if (options instanceof WriteConcern) { + opts = options; + } + else { + opts = options.writeConcern; + } + const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + const { w = undefined, wtimeout = undefined, j = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = { + ...parentOpts, + ...opts + }; + if (w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null) { + return new WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync); + } + return undefined; + } +} +exports.WriteConcern = WriteConcern; +//# sourceMappingURL=write_concern.js.map \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/lib/write_concern.js.map b/nodejs/node_modules/mongodb/lib/write_concern.js.map new file mode 100644 index 00000000..9f2f5473 --- /dev/null +++ b/nodejs/node_modules/mongodb/lib/write_concern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"write_concern.js","sourceRoot":"","sources":["../src/write_concern.ts"],"names":[],"mappings":";;;AAsCa,QAAA,kBAAkB,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAY7E;;;;;;GAMG;AACH,MAAa,YAAY;IAuBvB;;;;;;OAMG;IACH,YAAY,CAAK,EAAE,UAAmB,EAAE,OAAiB,EAAE,KAAmB;QAC5E,IAAI,CAAC,IAAI,IAAI,EAAE;YACb,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;gBAC5B,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;aACpB;iBAAM;gBACL,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;aACZ;SACF;QACD,IAAI,UAAU,IAAI,IAAI,EAAE;YACtB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,GAAG,UAAU,CAAC;SAC9C;QACD,IAAI,OAAO,IAAI,IAAI,EAAE;YACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,GAAG,OAAO,CAAC;SACjC;QACD,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,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B,GAAG;YACF,GAAG,UAAU;YACb,GAAG,IAAI;SACR,CAAC;QACF,IACE,CAAC,IAAI,IAAI;YACT,QAAQ,IAAI,IAAI;YAChB,UAAU,IAAI,IAAI;YAClB,CAAC,IAAI,IAAI;YACT,OAAO,IAAI,IAAI;YACf,KAAK,IAAI,IAAI,EACb;YACA,OAAO,IAAI,YAAY,CAAC,CAAC,EAAE,QAAQ,IAAI,UAAU,EAAE,CAAC,IAAI,OAAO,EAAE,KAAK,CAAC,CAAC;SACzE;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAvGD,oCAuGC"} \ No newline at end of file diff --git a/nodejs/node_modules/mongodb/mongodb.d.ts b/nodejs/node_modules/mongodb/mongodb.d.ts new file mode 100644 index 00000000..4255247a --- /dev/null +++ b/nodejs/node_modules/mongodb/mongodb.d.ts @@ -0,0 +1,7608 @@ +/// + +import type { DeserializeOptions , ObjectIdLike , SerializeOptions } from 'bson'; +import { Binary , BSON , BSONRegExp , BSONSymbol , BSONType , Code , DBRef , Decimal128 , deserialize , Document , Double , Int32 , Long , MaxKey , MinKey , ObjectId , serialize , Timestamp , UUID } from 'bson'; +import type { SrvRecord } from 'dns'; +import { EventEmitter } from 'events'; +import type { Socket , TcpNetConnectOpts } from 'net'; +import { Readable , Writable } from 'stream'; +import type { ConnectionOptions as ConnectionOptions_2 , TLSSocket , TLSSocketOptions } from 'tls'; + +/** @public */ +export declare abstract class AbstractCursor extends TypedEventEmitter { + /* Excluded from this release type: [kId] */ + /* Excluded from this release type: [kSession] */ + /* Excluded from this release type: [kServer] */ + /* Excluded from this release type: [kNamespace] */ + /* Excluded from this release type: [kDocuments] */ + /* Excluded from this release type: [kClient] */ + /* Excluded from this release type: [kTransform] */ + /* Excluded from this release type: [kInitialized] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kKilled] */ + /* Excluded from this release type: [kOptions] */ + /** @event */ + static readonly CLOSE: "close"; + /* Excluded from this release type: __constructor */ + get id(): Long | undefined; + /* Excluded from this release type: isDead */ + /* Excluded from this release type: client */ + /* Excluded from this release type: server */ + get namespace(): MongoDBNamespace; + get readPreference(): ReadPreference; + get readConcern(): ReadConcern | undefined; + /* Excluded from this release type: session */ + /* Excluded from this release type: session */ + /* Excluded from this release type: cursorOptions */ + get closed(): boolean; + get killed(): boolean; + get loadBalanced(): boolean; + /** Returns current buffered documents length */ + bufferedCount(): number; + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[]; + [Symbol.asyncIterator](): AsyncGenerator; + stream(options?: CursorStreamOptions): Readable & AsyncIterable; + hasNext(): Promise; + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + * @deprecated - Will be removed in a future release. Use for await...of instead. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + close(): Promise; + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + */ + toArray(): Promise; + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this; + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * + * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this; + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this; + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void; + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: getMore */ + /* Excluded from this release type: [kInit] */ +} + +/** @public */ +export declare type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; + +/** @public */ +export declare interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + /** + * Specifies the number of documents to return in each response from MongoDB + */ + batchSize?: number; + /** + * When applicable `maxTimeMS` controls the amount of time the initial command + * that constructs a cursor should take. (ex. find, aggregate, listCollections) + */ + maxTimeMS?: number; + /** + * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores + * that a cursor uses to fetch more data should take. (ex. cursor.next()) + */ + maxAwaitTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + /** + * By default, MongoDB will automatically close a cursor when the + * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections) + * you may use a Tailable Cursor that remains open after the client exhausts + * the results in the initial cursor. + */ + tailable?: boolean; + /** + * If awaitData is set to true, when the cursor reaches the end of the capped collection, + * MongoDB blocks the query thread for a period of time waiting for new data to arrive. + * When new data is inserted into the capped collection, the blocked thread is signaled + * to wake up and return the next batch to the client. + */ + awaitData?: boolean; + noCursorTimeout?: boolean; +} + +/* Excluded from this release type: AbstractOperation */ + +/** @public */ +export declare type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; + +/** @public */ +export declare type AddToSetOperators = { + $each?: Array>; +}; + +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +export declare class Admin { + /* Excluded from this release type: s */ + /* Excluded from this release type: __constructor */ + /** + * Execute a command + * + * The driver will ensure the following fields are attached to the command sent to the server: + * - `lsid` - sourced from an implicit session or options.session + * - `$readPreference` - defaults to primary or can be configured by options.readPreference + * - `$db` - sourced from the name of this database + * + * If the client has a serverApi setting: + * - `apiVersion` + * - `apiStrict` + * - `apiDeprecationErrors` + * + * When in a transaction: + * - `readConcern` - sourced from readConcern set on the TransactionOptions + * - `writeConcern` - sourced from writeConcern set on the TransactionOptions + * + * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. + * + * @param command - The command to execute + * @param options - Optional settings for the command + */ + command(command: Document, options?: RunCommandOptions): Promise; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + buildInfo(options?: CommandOperationOptions): Promise; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + serverInfo(options?: CommandOperationOptions): Promise; + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + serverStatus(options?: CommandOperationOptions): Promise; + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + ping(options?: CommandOperationOptions): Promise; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + removeUser(username: string, options?: RemoveUserOptions): Promise; + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise; + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + listDatabases(options?: ListDatabasesOptions): Promise; + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + replSetGetStatus(options?: CommandOperationOptions): Promise; +} + +/* Excluded from this release type: AdminPrivate */ + +/* Excluded from this release type: AggregateOperation */ + +/** @public */ +export declare interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + out?: string; +} + +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export declare class AggregationCursor extends AbstractCursor { + /* Excluded from this release type: [kPipeline] */ + /* Excluded from this release type: [kOptions] */ + /* Excluded from this release type: __constructor */ + get pipeline(): Document[]; + clone(): AggregationCursor; + map(transform: (doc: TSchema) => T): AggregationCursor; + /* Excluded from this release type: _initialize */ + /** Execute the explain for the cursor */ + explain(verbosity?: ExplainVerbosityLike): Promise; + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this; + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this; + /** Add an out stage to the aggregation pipeline */ + out($out: { + db: string; + coll: string; + } | string): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor; + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this; + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this; + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this; + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this; + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this; + /** Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this; +} + +/** @public */ +export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions { +} + +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export declare type AlternativeType = T extends ReadonlyArray ? T | RegExpOrString : RegExpOrString; + +/** @public */ +export declare type AnyBulkWriteOperation = { + insertOne: InsertOneModel; +} | { + replaceOne: ReplaceOneModel; +} | { + updateOne: UpdateOneModel; +} | { + updateMany: UpdateManyModel; +} | { + deleteOne: DeleteOneModel; +} | { + deleteMany: DeleteManyModel; +}; + +/** @public */ +export declare type AnyError = MongoError | Error; + +/** @public */ +export declare type ArrayElement = Type extends ReadonlyArray ? Item : never; + +/** @public */ +export declare type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; + +/** @public */ +export declare interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} + +/* Excluded from this release type: AuthContext */ + +/** @public */ +export declare const AuthMechanism: Readonly<{ + readonly MONGODB_AWS: "MONGODB-AWS"; + readonly MONGODB_CR: "MONGODB-CR"; + readonly MONGODB_DEFAULT: "DEFAULT"; + readonly MONGODB_GSSAPI: "GSSAPI"; + readonly MONGODB_PLAIN: "PLAIN"; + readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1"; + readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256"; + readonly MONGODB_X509: "MONGODB-X509"; + /** @experimental */ + readonly MONGODB_OIDC: "MONGODB-OIDC"; +}>; + +/** @public */ +export declare type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism]; + +/** @public */ +export declare interface AuthMechanismProperties extends Document { + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + AWS_SESSION_TOKEN?: string; + /** @experimental */ + REQUEST_TOKEN_CALLBACK?: OIDCRequestFunction; + /** @experimental */ + REFRESH_TOKEN_CALLBACK?: OIDCRefreshFunction; + /** @experimental */ + PROVIDER_NAME?: 'aws' | 'azure'; + /** @experimental */ + ALLOWED_HOSTS?: string[]; + /** @experimental */ + TOKEN_AUDIENCE?: string; +} + +/* Excluded from this release type: AuthProvider */ + +/* Excluded from this release type: AutoEncrypter */ + +/** + * @public + * + * Extra options related to the mongocryptd process + * \* _Available in MongoDB 6.0 or higher._ + */ +export declare type AutoEncryptionExtraOptions = NonNullable; + +/** @public */ +export declare const AutoEncryptionLoggerLevel: Readonly<{ + readonly FatalError: 0; + readonly Error: 1; + readonly Warning: 2; + readonly Info: 3; + readonly Trace: 4; +}>; + +/** + * @public + * The level of severity of the log message + * + * | Value | Level | + * |-------|-------| + * | 0 | Fatal Error | + * | 1 | Error | + * | 2 | Warning | + * | 3 | Info | + * | 4 | Trace | + */ +export declare type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel]; + +/** @public */ +export declare interface AutoEncryptionOptions { + /* Excluded from this release type: metadataClient */ + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + } | Record; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + } | { + /** + * If present, an access token to authenticate with Azure. + */ + accessToken: string; + } | Record; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + } | { + /** + * If present, an access token to authenticate with GCP. + */ + accessToken: string; + } | Record; + /** + * Configuration options for using 'kmip' as your KMS provider + */ + kmip?: { + /** + * The output endpoint string. + * The endpoint consists of a hostname and port separated by a colon. + * E.g. "example.com:123". A port is always present. + */ + endpoint?: string; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** Supply a schema for the encrypted fields in the document */ + encryptedFieldsMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + /** Allows users to bypass query analysis */ + bypassQueryAnalysis?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + /** + * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd). + * + * This needs to be the path to the file itself, not a directory. + * It can be an absolute or relative path. If the path is relative and + * its first component is `$ORIGIN`, it will be replaced by the directory + * containing the mongodb-client-encryption native addon file. Otherwise, + * the path will be interpreted relative to the current working directory. + * + * Currently, loading different MongoDB Crypt shared library files from different + * MongoClients in the same process is not supported. + * + * If this option is provided and no MongoDB Crypt shared library could be loaded + * from the specified location, creating the MongoClient will fail. + * + * If this option is not provided and `cryptSharedLibRequired` is not specified, + * the AutoEncrypter will attempt to spawn and/or use mongocryptd according + * to the mongocryptd-specific `extraOptions` options. + * + * Specifying a path prevents mongocryptd from being used as a fallback. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibPath?: string; + /** + * If specified, never use mongocryptd and instead fail when the MongoDB Crypt + * shared library could not be loaded. + * + * This is always true when `cryptSharedLibPath` is specified. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibRequired?: boolean; + /* Excluded from this release type: cryptSharedLibSearchPaths */ + }; + proxyOptions?: ProxyOptions; + /** The TLS options to use connecting to the KMS provider */ + tlsOptions?: CSFLEKMSTlsOptions; +} + +/** + * @public + * Configuration options for making an AWS encryption key + */ +export declare interface AWSEncryptionKeyOptions { + /** + * The AWS region of the KMS + */ + region: string; + /** + * The Amazon Resource Name (ARN) to the AWS customer master key (CMK) + */ + key: string; + /** + * An alternate host to send KMS requests to. May include port number. + */ + endpoint?: string | undefined; +} + +/** + * @public + * Configuration options for making an Azure encryption key + */ +export declare interface AzureEncryptionKeyOptions { + /** + * Key name + */ + keyName: string; + /** + * Key vault URL, typically `.vault.azure.net` + */ + keyVaultEndpoint: string; + /** + * Key version + */ + keyVersion?: string | undefined; +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export declare class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + constructor(batchType: BatchType, originalZeroIndex: number); +} + +/** @public */ +export declare const BatchType: Readonly<{ + readonly INSERT: 1; + readonly UPDATE: 2; + readonly DELETE: 3; +}>; + +/** @public */ +export declare type BatchType = (typeof BatchType)[keyof typeof BatchType]; + +export { Binary } + +/** @public */ +export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray; + +export { BSON } + +export { BSONRegExp } + +/** + * BSON Serialization options. + * @public + */ +export declare interface BSONSerializeOptions extends Omit, Omit { + /** + * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html) + * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize). + * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe) + * for more detail about what "unsafe" refers to in this context. + * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate + * your own buffer and clone the contents: + * + * @example + * ```ts + * const raw = await collection.findOne({}, { raw: true }); + * const myBuffer = Buffer.alloc(raw.byteLength); + * myBuffer.set(raw, 0); + * // Only save and use `myBuffer` beyond this point + * ``` + * + * @remarks + * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)). + * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work. + */ + raw?: boolean; + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export { BSONSymbol } + +export { BSONType } + +/** @public */ +export declare type BSONTypeAlias = keyof typeof BSONType; + +/* Excluded from this release type: BufferPool */ + +/** @public */ +export declare abstract class BulkOperationBase { + private collection; + isOrdered: boolean; + /* Excluded from this release type: s */ + operationId?: number; + /* Excluded from this release type: __constructor */ + /** + * Add a single insert document to the bulk operation + * + * @example + * ```ts + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase; + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```ts + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators; + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this; + get bsonOptions(): BSONSerializeOptions; + get writeConcern(): WriteConcern | undefined; + get batches(): Batch[]; + execute(options?: BulkWriteOptions): Promise; + /* Excluded from this release type: handleWriteError */ + abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; + private shouldForceServerObjectId; +} + +/* Excluded from this release type: BulkOperationPrivate */ + +/* Excluded from this release type: BulkResult */ + +/** @public */ +export declare interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} + +/** @public */ +export declare interface BulkWriteOptions extends CommandOperationOptions { + /** + * Allow driver to bypass schema validation. + * @defaultValue `false` - documents will be validated by default + **/ + bypassDocumentValidation?: boolean; + /** + * If true, when an insert fails, don't execute the remaining writes. + * If false, continue with remaining inserts when one fails. + * @defaultValue `true` - inserts are ordered by default + */ + ordered?: boolean; + /** + * Force server to assign _id values instead of driver. + * @defaultValue `false` - the driver generates `_id` fields by default + **/ + forceServerObjectId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * @public + * The result of a bulk write. + */ +export declare class BulkWriteResult { + private readonly result; + /** Number of documents inserted. */ + readonly insertedCount: number; + /** Number of documents matched for update. */ + readonly matchedCount: number; + /** Number of documents modified. */ + readonly modifiedCount: number; + /** Number of documents deleted. */ + readonly deletedCount: number; + /** Number of documents upserted. */ + readonly upsertedCount: number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { + [key: number]: any; + }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { + [key: number]: any; + }; + private static generateIdMap; + /* Excluded from this release type: __constructor */ + /** Evaluates to true if the bulk operation correctly executes */ + get ok(): number; + /* Excluded from this release type: getSuccessfullyInsertedIds */ + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined; + /** Returns raw internal result */ + getRawResponse(): Document; + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean; + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number; + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined; + /** Retrieve all write errors */ + getWriteErrors(): WriteError[]; + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined; + toString(): string; + isOk(): boolean; +} + +/** + * MongoDB Driver style callback + * @public + */ +export declare type Callback = (error?: AnyError, result?: T) => void; + +/** @public */ +export declare class CancellationToken extends TypedEventEmitter<{ + cancel(): void; +}> { +} + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export declare class ChangeStream> extends TypedEventEmitter> { + pipeline: Document[]; + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + options: ChangeStreamOptions & { + writeConcern?: never; + }; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /* Excluded from this release type: cursor */ + streamOptions?: CursorStreamOptions; + /* Excluded from this release type: [kCursorStream] */ + /* Excluded from this release type: [kClosed] */ + /* Excluded from this release type: [kMode] */ + /** @event */ + static readonly RESPONSE: "response"; + /** @event */ + static readonly MORE: "more"; + /** @event */ + static readonly INIT: "init"; + /** @event */ + static readonly CLOSE: "close"; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE: "change"; + /** @event */ + static readonly END: "end"; + /** @event */ + static readonly ERROR: "error"; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: cursorStream */ + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken(): ResumeToken; + /** Check if there is any document still available in the Change Stream */ + hasNext(): Promise; + /** Get the next available document from the Change Stream. */ + next(): Promise; + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + [Symbol.asyncIterator](): AsyncGenerator; + /** Is the cursor closed */ + get closed(): boolean; + /** Close the Change Stream */ + close(): Promise; + /** + * Return a modified Readable stream including a possible transform method. + * + * NOTE: When using a Stream to process change stream events, the stream will + * NOT automatically resume in the case a resumable error is encountered. + * + * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed + */ + stream(options?: CursorStreamOptions): Readable & AsyncIterable; + /* Excluded from this release type: _setIsEmitter */ + /* Excluded from this release type: _setIsIterator */ + /* Excluded from this release type: _createChangeStreamCursor */ + /* Excluded from this release type: _closeEmitterModeWithError */ + /* Excluded from this release type: _streamEvents */ + /* Excluded from this release type: _endStream */ + /* Excluded from this release type: _processChange */ + /* Excluded from this release type: _processErrorStreamMode */ + /* Excluded from this release type: _processErrorIteratorMode */ +} + +/* Excluded from this release type: ChangeStreamAggregateRawResult */ + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamCollModDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'modify'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamCreateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'create'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamCreateIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'createIndexes'; +} + +/* Excluded from this release type: ChangeStreamCursor */ + +/* Excluded from this release type: ChangeStreamCursorOptions */ + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event + */ +export declare interface ChangeStreamDeleteDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'delete'; + /** Namespace the delete event occurred on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** @public */ +export declare type ChangeStreamDocument = ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument | ChangeStreamDropDocument | ChangeStreamRenameDocument | ChangeStreamDropDatabaseDocument | ChangeStreamInvalidateDocument | ChangeStreamCreateIndexDocument | ChangeStreamCreateDocument | ChangeStreamCollModDocument | ChangeStreamDropIndexDocument | ChangeStreamShardCollectionDocument | ChangeStreamReshardCollectionDocument | ChangeStreamRefineCollectionShardKeyDocument; + +/** @public */ +export declare interface ChangeStreamDocumentCollectionUUID { + /** + * The UUID (Binary subtype 4) of the collection that the operation was performed on. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers + * flag is enabled. + * + * @sinceServerVersion 6.1.0 + */ + collectionUUID: Binary; +} + +/** @public */ +export declare interface ChangeStreamDocumentCommon { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: ResumeToken; + /** + * The timestamp from the oplog entry associated with the event. + * For events that happened as part of a multi-document transaction, the associated change stream + * notifications will have the same clusterTime value, namely the time when the transaction was committed. + * On a sharded cluster, events that occur on different shards can have the same clusterTime but be + * associated with different transactions or even not be associated with any transaction. + * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document. + */ + clusterTime?: Timestamp; + /** + * The transaction number. + * Only present if the operation is part of a multi-document transaction. + * + * **NOTE:** txnNumber can be a Long if promoteLongs is set to false + */ + txnNumber?: number; + /** + * The identifier for the session associated with the transaction. + * Only present if the operation is part of a multi-document transaction. + */ + lsid?: ServerSessionId; + /** + * When the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent + * stage, events larger than 16MB will be split into multiple events and contain the + * following information about which fragment the current event is. + */ + splitEvent?: ChangeStreamSplitEvent; +} + +/** @public */ +export declare interface ChangeStreamDocumentKey { + /** + * For unsharded collections this contains a single field `_id`. + * For sharded collections, this will contain all the components of the shard key + */ + documentKey: { + _id: InferIdType; + [shardKey: string]: any; + }; +} + +/** @public */ +export declare interface ChangeStreamDocumentOperationDescription { + /** + * An description of the operation. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * @sinceServerVersion 6.1.0 + */ + operationDescription?: Document; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event + */ +export declare interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropDatabase'; + /** The database dropped */ + ns: { + db: string; + }; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event + */ +export declare interface ChangeStreamDropDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'drop'; + /** Namespace the drop event occurred on */ + ns: ChangeStreamNameSpace; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamDropIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropIndexes'; +} + +/** @public */ +export declare type ChangeStreamEvents> = { + resumeTokenChanged(token: ResumeToken): void; + init(response: any): void; + more(response?: any): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: TChange): void; +} & AbstractCursorEvents; + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event + */ +export declare interface ChangeStreamInsertDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'insert'; + /** This key will contain the document being inserted */ + fullDocument: TSchema; + /** Namespace the insert event occurred on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event + */ +export declare interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'invalidate'; +} + +/** @public */ +export declare interface ChangeStreamNameSpace { + db: string; + coll: string; +} + +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export declare interface ChangeStreamOptions extends Omit { + /** + * Allowed values: 'updateLookup', 'whenAvailable', 'required'. + * + * When set to 'updateLookup', the change notification for partial updates + * will include both a delta describing the changes to the document as well + * as a copy of the entire document that was changed from some time after + * the change occurred. + * + * When set to 'whenAvailable', configures the change stream to return the + * post-image of the modified document for replace and update change events + * if the post-image for this event is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the post-image is not available. + */ + fullDocument?: string; + /** + * Allowed values: 'whenAvailable', 'required', 'off'. + * + * The default is to not send a value, which is equivalent to 'off'. + * + * When set to 'whenAvailable', configures the change stream to return the + * pre-image of the modified document for replace, update, and delete change + * events if it is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the pre-image is not available. + */ + fullDocumentBeforeChange?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** + * Allows you to start a changeStream after a specified event. + * @see https://www.mongodb.com/docs/manual/changeStreams/#resumeafter-for-change-streams + */ + resumeAfter?: ResumeToken; + /** + * Similar to resumeAfter, but will allow you to start after an invalidated event. + * @see https://www.mongodb.com/docs/manual/changeStreams/#startafter-for-change-streams + */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** + * The number of documents to return per batch. + * @see https://www.mongodb.com/docs/manual/reference/command/aggregate + */ + batchSize?: number; + /** + * When enabled, configures the change stream to include extra change events. + * + * - createIndexes + * - dropIndexes + * - modify + * - create + * - shardCollection + * - reshardCollection + * - refineCollectionShardKey + */ + showExpandedEvents?: boolean; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamRefineCollectionShardKeyDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'refineCollectionShardKey'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event + */ +export declare interface ChangeStreamRenameDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'rename'; + /** The new name for the `ns.coll` collection */ + to: { + db: string; + coll: string; + }; + /** The "from" namespace that the rename occurred on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event + */ +export declare interface ChangeStreamReplaceDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey { + /** Describes the type of operation represented in this change notification */ + operationType: 'replace'; + /** The fullDocument of a replace event represents the document after the insert of the replacement document */ + fullDocument: TSchema; + /** Namespace the replace event occurred on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamReshardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'reshardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export declare interface ChangeStreamShardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'shardCollection'; +} + +/** @public */ +export declare interface ChangeStreamSplitEvent { + /** Which fragment of the change this is. */ + fragment: number; + /** The total number of fragments. */ + of: number; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event + */ +export declare interface ChangeStreamUpdateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'update'; + /** + * This is only set if `fullDocument` is set to `'updateLookup'` + * Contains the point-in-time post-image of the modified document if the + * post-image is available and either 'required' or 'whenAvailable' was + * specified for the 'fullDocument' option when creating the change stream. + */ + fullDocument?: TSchema; + /** Contains a description of updated and removed fields in this operation */ + updateDescription: UpdateDescription; + /** Namespace the update event occurred on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * The public interface for explicit in-use encryption + */ +export declare class ClientEncryption { + /* Excluded from this release type: _client */ + /* Excluded from this release type: _keyVaultNamespace */ + /* Excluded from this release type: _keyVaultClient */ + /* Excluded from this release type: _proxyOptions */ + /* Excluded from this release type: _tlsOptions */ + /* Excluded from this release type: _kmsProviders */ + /* Excluded from this release type: _mongoCrypt */ + /* Excluded from this release type: getMongoCrypt */ + /** + * Create a new encryption instance + * + * @example + * ```ts + * new ClientEncryption(mongoClient, { + * keyVaultNamespace: 'client.encryption', + * kmsProviders: { + * local: { + * key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer + * } + * } + * }); + * ``` + * + * @example + * ```ts + * new ClientEncryption(mongoClient, { + * keyVaultNamespace: 'client.encryption', + * kmsProviders: { + * aws: { + * accessKeyId: AWS_ACCESS_KEY, + * secretAccessKey: AWS_SECRET_KEY + * } + * } + * }); + * ``` + */ + constructor(client: MongoClient, options: ClientEncryptionOptions); + /** + * Creates a data key used for explicit encryption and inserts it into the key vault namespace + * + * @example + * ```ts + * // Using async/await to create a local key + * const dataKeyId = await clientEncryption.createDataKey('local'); + * ``` + * + * @example + * ```ts + * // Using async/await to create an aws key + * const dataKeyId = await clientEncryption.createDataKey('aws', { + * masterKey: { + * region: 'us-east-1', + * key: 'xxxxxxxxxxxxxx' // CMK ARN here + * } + * }); + * ``` + * + * @example + * ```ts + * // Using async/await to create an aws key with a keyAltName + * const dataKeyId = await clientEncryption.createDataKey('aws', { + * masterKey: { + * region: 'us-east-1', + * key: 'xxxxxxxxxxxxxx' // CMK ARN here + * }, + * keyAltNames: [ 'mySpecialKey' ] + * }); + * ``` + */ + createDataKey(provider: ClientEncryptionDataKeyProvider, options?: ClientEncryptionCreateDataKeyProviderOptions): Promise; + /** + * Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options. + * + * If no matches are found, then no bulk write is performed. + * + * @example + * ```ts + * // rewrapping all data data keys (using a filter that matches all documents) + * const filter = {}; + * + * const result = await clientEncryption.rewrapManyDataKey(filter); + * if (result.bulkWriteResult != null) { + * // keys were re-wrapped, results will be available in the bulkWrite object. + * } + * ``` + * + * @example + * ```ts + * // attempting to rewrap all data keys with no matches + * const filter = { _id: new Binary() } // assume _id matches no documents in the database + * const result = await clientEncryption.rewrapManyDataKey(filter); + * + * if (result.bulkWriteResult == null) { + * // no keys matched, `bulkWriteResult` does not exist on the result object + * } + * ``` + */ + rewrapManyDataKey(filter: Filter, options: ClientEncryptionRewrapManyDataKeyProviderOptions): Promise<{ + bulkWriteResult?: BulkWriteResult; + }>; + /** + * Deletes the key with the provided id from the keyvault, if it exists. + * + * @example + * ```ts + * // delete a key by _id + * const id = new Binary(); // id is a bson binary subtype 4 object + * const { deletedCount } = await clientEncryption.deleteKey(id); + * + * if (deletedCount != null && deletedCount > 0) { + * // successful deletion + * } + * ``` + * + */ + deleteKey(_id: Binary): Promise; + /** + * Finds all the keys currently stored in the keyvault. + * + * This method will not throw. + * + * @returns a FindCursor over all keys in the keyvault. + * @example + * ```ts + * // fetching all keys + * const keys = await clientEncryption.getKeys().toArray(); + * ``` + */ + getKeys(): FindCursor; + /** + * Finds a key in the keyvault with the specified _id. + * + * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // getting a key by id + * const id = new Binary(); // id is a bson binary subtype 4 object + * const key = await clientEncryption.getKey(id); + * if (!key) { + * // key is null if there was no matching key + * } + * ``` + */ + getKey(_id: Binary): Promise; + /** + * Finds a key in the keyvault which has the specified keyAltName. + * + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the keyAltName. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // get a key by alt name + * const keyAltName = 'keyAltName'; + * const key = await clientEncryption.getKeyByAltName(keyAltName); + * if (!key) { + * // key is null if there is no matching key + * } + * ``` + */ + getKeyByAltName(keyAltName: string): Promise | null>; + /** + * Adds a keyAltName to a key identified by the provided _id. + * + * This method resolves to/returns the *old* key value (prior to adding the new altKeyName). + * + * @param _id - The id of the document to update. + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // adding an keyAltName to a data key + * const id = new Binary(); // id is a bson binary subtype 4 object + * const keyAltName = 'keyAltName'; + * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName); + * if (!oldKey) { + * // null is returned if there is no matching document with an id matching the supplied id + * } + * ``` + */ + addKeyAltName(_id: Binary, keyAltName: string): Promise | null>; + /** + * Adds a keyAltName to a key identified by the provided _id. + * + * This method resolves to/returns the *old* key value (prior to removing the new altKeyName). + * + * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document. + * + * @param _id - The id of the document to update. + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // removing a key alt name from a data key + * const id = new Binary(); // id is a bson binary subtype 4 object + * const keyAltName = 'keyAltName'; + * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName); + * + * if (!oldKey) { + * // null is returned if there is no matching document with an id matching the supplied id + * } + * ``` + */ + removeKeyAltName(_id: Binary, keyAltName: string): Promise | null>; + /** + * A convenience method for creating an encrypted collection. + * This method will create data keys for any encryptedFields that do not have a `keyId` defined + * and then create a new collection with the full set of encryptedFields. + * + * @param db - A Node.js driver Db object with which to create the collection + * @param name - The name of the collection to be created + * @param options - Options for createDataKey and for createCollection + * @returns created collection and generated encryptedFields + * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created. + * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created. + */ + createEncryptedCollection(db: Db, name: string, options: { + provider: ClientEncryptionDataKeyProvider; + createCollectionOptions: Omit & { + encryptedFields: Document; + }; + masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions; + }): Promise<{ + collection: Collection; + encryptedFields: Document; + }>; + /** + * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must + * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. + * + * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON + * @param options - + * @returns a Promise that either resolves with the encrypted value, or rejects with an error. + * + * @example + * ```ts + * // Encryption with async/await api + * async function encryptMyData(value) { + * const keyId = await clientEncryption.createDataKey('local'); + * return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); + * } + * ``` + * + * @example + * ```ts + * // Encryption using a keyAltName + * async function encryptMyData(value) { + * await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' }); + * return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); + * } + * ``` + */ + encrypt(value: unknown, options: ClientEncryptionEncryptOptions): Promise; + /** + * Encrypts a Match Expression or Aggregate Expression to query a range index. + * + * Only supported when queryType is "rangePreview" and algorithm is "RangePreview". + * + * @experimental The Range algorithm is experimental only. It is not intended for production use. It is subject to breaking changes. + * + * @param expression - a BSON document of one of the following forms: + * 1. A Match Expression of this form: + * `{$and: [{: {$gt: }}, {: {$lt: }}]}` + * 2. An Aggregate Expression of this form: + * `{$and: [{$gt: [, ]}, {$lt: [, ]}]}` + * + * `$gt` may also be `$gte`. `$lt` may also be `$lte`. + * + * @param options - + * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error. + */ + encryptExpression(expression: Document, options: ClientEncryptionEncryptOptions): Promise; + /** + * Explicitly decrypt a provided encrypted value + * + * @param value - An encrypted value + * @returns a Promise that either resolves with the decrypted value, or rejects with an error + * + * @example + * ```ts + * // Decrypting value with async/await API + * async function decryptMyValue(value) { + * return clientEncryption.decrypt(value); + * } + * ``` + */ + decrypt(value: Binary): Promise; + /* Excluded from this release type: askForKMSCredentials */ + static get libmongocryptVersion(): string; + /* Excluded from this release type: _encrypt */ +} + +/** + * @public + * Options to provide when creating a new data key. + */ +export declare interface ClientEncryptionCreateDataKeyProviderOptions { + /** + * Identifies a new KMS-specific key used to encrypt the new data key + */ + masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | undefined; + /** + * An optional list of string alternate names used to reference a key. + * If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id. + */ + keyAltNames?: string[] | undefined; + /** @experimental */ + keyMaterial?: Buffer | Binary; +} + +/** + * @public + */ +export declare type ClientEncryptionDataKeyProvider = 'aws' | 'azure' | 'gcp' | 'local' | 'kmip'; + +/** + * @public + * Options to provide when encrypting data. + */ +export declare interface ClientEncryptionEncryptOptions { + /** + * The algorithm to use for encryption. + */ + algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' | 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' | 'Indexed' | 'Unindexed' | 'RangePreview'; + /** + * The id of the Binary dataKey to use for encryption + */ + keyId?: Binary; + /** + * A unique string name corresponding to an already existing dataKey. + */ + keyAltName?: string; + /** The contention factor. */ + contentionFactor?: bigint | number; + /** + * The query type supported. Only the queryType `equality` is stable. + * + * @experimental Public Technical Preview: The queryType `rangePreview` is experimental. + */ + queryType?: 'equality' | 'rangePreview'; + /** @experimental Public Technical Preview: The index options for a Queryable Encryption field supporting "rangePreview" queries.*/ + rangeOptions?: RangeOptions; +} + +/** + * @public + * Options to provide when encrypting data. + */ +export declare interface ClientEncryptionEncryptOptions { + /** + * The algorithm to use for encryption. + */ + algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' | 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' | 'Indexed' | 'Unindexed' | 'RangePreview'; + /** + * The id of the Binary dataKey to use for encryption + */ + keyId?: Binary; + /** + * A unique string name corresponding to an already existing dataKey. + */ + keyAltName?: string; + /** The contention factor. */ + contentionFactor?: bigint | number; + /** + * The query type supported. Only the queryType `equality` is stable. + * + * @experimental Public Technical Preview: The queryType `rangePreview` is experimental. + */ + queryType?: 'equality' | 'rangePreview'; + /** @experimental Public Technical Preview: The index options for a Queryable Encryption field supporting "rangePreview" queries.*/ + rangeOptions?: RangeOptions; +} + +/** + * @public + * Additional settings to provide when creating a new `ClientEncryption` instance. + */ +export declare interface ClientEncryptionOptions { + /** + * The namespace of the key vault, used to store encryption keys + */ + keyVaultNamespace: string; + /** + * A MongoClient used to fetch keys from a key vault. Defaults to client. + */ + keyVaultClient?: MongoClient | undefined; + /** + * Options for specific KMS providers to use + */ + kmsProviders?: KMSProviders; + /** + * Options for specifying a Socks5 proxy to use for connecting to the KMS. + */ + proxyOptions?: ProxyOptions; + /** + * TLS options for kms providers to use. + */ + tlsOptions?: CSFLEKMSTlsOptions; +} + +/** + * @public + * @experimental + */ +export declare interface ClientEncryptionRewrapManyDataKeyProviderOptions { + provider: ClientEncryptionDataKeyProvider; + masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | undefined; +} + +/** + * @public + * @experimental + */ +export declare interface ClientEncryptionRewrapManyDataKeyProviderOptions { + provider: ClientEncryptionDataKeyProvider; + masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | undefined; +} + +/** + * @public + * @experimental + */ +export declare interface ClientEncryptionRewrapManyDataKeyResult { + /** The result of rewrapping data keys. If unset, no keys matched the filter. */ + bulkWriteResult?: BulkWriteResult; +} + +/** + * @public + * + * TLS options to use when connecting. The spec specifically calls out which insecure + * tls options are not allowed: + * + * - tlsAllowInvalidCertificates + * - tlsAllowInvalidHostnames + * - tlsInsecure + * + * These options are not included in the type, and are ignored if provided. + */ +export declare type ClientEncryptionTlsOptions = Pick; + +/** + * @public + * @see https://github.com/mongodb/specifications/blob/master/source/mongodb-handshake/handshake.rst#hello-command + */ +export declare interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name?: NodeJS.Platform; + architecture?: string; + version?: string; + }; + platform: string; + application?: { + name: string; + }; + /** FaaS environment information */ + env?: { + name: 'aws.lambda' | 'gcp.func' | 'azure.func' | 'vercel'; + timeout_sec?: Int32; + memory_mb?: Int32; + region?: string; + url?: string; + }; +} + +/** @public */ +export declare interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} + +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export declare class ClientSession extends TypedEventEmitter { + /* Excluded from this release type: client */ + /* Excluded from this release type: sessionPool */ + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { + causalConsistency: boolean; + }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /* Excluded from this release type: owner */ + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /* Excluded from this release type: [kServerSession] */ + /* Excluded from this release type: [kSnapshotTime] */ + /* Excluded from this release type: [kSnapshotEnabled] */ + /* Excluded from this release type: [kPinnedConnection] */ + /* Excluded from this release type: [kTxnNumberIncrement] */ + /* Excluded from this release type: __constructor */ + /** The server id associated with this session */ + get id(): ServerSessionId | undefined; + get serverSession(): ServerSession; + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled(): boolean; + get loadBalanced(): boolean; + /* Excluded from this release type: pinnedConnection */ + /* Excluded from this release type: pin */ + /* Excluded from this release type: unpin */ + get isPinned(): boolean; + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + */ + endSession(options?: EndSessionOptions): Promise; + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void; + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void; + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean; + /** + * Increment the transaction number on the internal ServerSession + * + * @privateRemarks + * This helper increments a value stored on the client session that will be + * added to the serverSession's txnNumber upon applying it to a command. + * This is because the serverSession is lazily acquired after a connection is obtained + */ + incrementTransactionNumber(): void; + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean; + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void; + /** + * Commits the currently active transaction in this session. + */ + commitTransaction(): Promise; + /** + * Aborts the currently active transaction in this session. + */ + abortTransaction(): Promise; + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never; + /** + * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed. + * + * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations. + * + * @remarks + * This function: + * - If all operations successfully complete and the `commitTransaction` operation is successful, then this function will return the result of the provided function. + * - If the transaction is unable to complete or an error is thrown from within the provided function, then this function will throw an error. + * - If the transaction is manually aborted within the provided function it will not throw. + * - May be called multiple times if the driver needs to attempt to retry the operations. + * + * Checkout a descriptive example here: + * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions + * + * @param fn - callback to run within a transaction + * @param options - optional settings for the transaction + * @returns A raw command response or undefined + */ + withTransaction(fn: WithTransactionCallback, options?: TransactionOptions): Promise; +} + +/** @public */ +export declare type ClientSessionEvents = { + ended(session: ClientSession): void; +}; + +/** @public */ +export declare interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; + /* Excluded from this release type: owner */ + /* Excluded from this release type: explicit */ + /* Excluded from this release type: initialClusterTime */ +} + +/** + * @public + * @deprecated This interface is deprecated and will be removed in a future release as it is not used + * in the driver + */ +export declare interface CloseOptions { + force?: boolean; +} + +/** @public + * Configuration options for clustered collections + * @see https://www.mongodb.com/docs/manual/core/clustered-collections/ + */ +export declare interface ClusteredCollectionOptions extends Document { + name?: string; + key: Document; + unique: boolean; +} + +/** @public */ +export declare interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} + +export { Code } + +/** @public */ +export declare interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} + +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +export declare class Collection { + /* Excluded from this release type: s */ + /* Excluded from this release type: client */ + /* Excluded from this release type: __constructor */ + /** + * The name of the database this collection belongs to + */ + get dbName(): string; + /** + * The name of this collection + */ + get collectionName(): string; + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace(): string; + /* Excluded from this release type: fullNamespace */ + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern(): ReadConcern | undefined; + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference(): ReadPreference | undefined; + get bsonOptions(): BSONSerializeOptions; + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern(): WriteConcern | undefined; + /** The current index hint for the collection */ + get hint(): Hint | undefined; + set hint(v: Hint | undefined); + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + */ + insertOne(doc: OptionalUnlessRequiredId, options?: InsertOneOptions): Promise>; + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + */ + insertMany(docs: OptionalUnlessRequiredId[], options?: BulkWriteOptions): Promise>; + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[], options?: BulkWriteOptions): Promise; + /** + * Update a single document in a collection + * + * The value of `update` can be either: + * - UpdateFilter - A document that contains update operator expressions, + * - Document[] - an aggregation pipeline. + * + * @param filter - The filter used to select the document to update + * @param update - The modifications to apply + * @param options - Optional settings for the command + */ + updateOne(filter: Filter, update: UpdateFilter | Document[], options?: UpdateOptions): Promise>; + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + */ + replaceOne(filter: Filter, replacement: WithoutId, options?: ReplaceOptions): Promise | Document>; + /** + * Update multiple documents in a collection + * + * The value of `update` can be either: + * - UpdateFilter - A document that contains update operator expressions, + * - Document[] - an aggregation pipeline. + * + * @param filter - The filter used to select the document to update + * @param update - The modifications to apply + * @param options - Optional settings for the command + */ + updateMany(filter: Filter, update: UpdateFilter | Document[], options?: UpdateOptions): Promise>; + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + deleteOne(filter?: Filter, options?: DeleteOptions): Promise; + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + deleteMany(filter?: Filter, options?: DeleteOptions): Promise; + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + */ + rename(newName: string, options?: RenameOptions): Promise; + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + drop(options?: DropCollectionOptions): Promise; + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + */ + findOne(): Promise | null>; + findOne(filter: Filter): Promise | null>; + findOne(filter: Filter, options: FindOptions): Promise | null>; + findOne(): Promise; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor; + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + */ + options(options?: OperationOptions): Promise; + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + isCapped(options?: OperationOptions): Promise; + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * + * @example + * ```ts + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + createIndex(indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise; + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * + * @example + * ```ts + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + createIndexes(indexSpecs: IndexDescription[], options?: CreateIndexesOptions): Promise; + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + dropIndex(indexName: string, options?: DropIndexesOptions): Promise; + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + dropIndexes(options?: DropIndexesOptions): Promise; + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor; + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + */ + indexExists(indexes: string | string[], options?: IndexInformationOptions): Promise; + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + indexInformation(options?: IndexInformationOptions): Promise; + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * This will always run a count command on all server versions. + * + * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, + * which estimatedDocumentCount uses in its implementation, was not included in v1 of + * the Stable API, and so users of the Stable API with estimatedDocumentCount are + * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid + * encountering errors. + * + * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior} + * @param options - Optional settings for the command + */ + estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise; + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/ + * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ + * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center + * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * + * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/ + * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ + * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center + * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + countDocuments(filter?: Filter, options?: CountDocumentsOptions): Promise; + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + */ + distinct>(key: Key): Promise[Key]>>>; + distinct>(key: Key, filter: Filter): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, options: DistinctOptions): Promise[Key]>>>; + distinct(key: string): Promise; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + indexes(options?: IndexInformationOptions): Promise; + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions & { + includeResultMetadata: true; + }): Promise>; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions & { + includeResultMetadata: false; + }): Promise | null>; + findOneAndDelete(filter: Filter, options: FindOneAndDeleteOptions): Promise | null>; + findOneAndDelete(filter: Filter): Promise | null>; + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + */ + findOneAndReplace(filter: Filter, replacement: WithoutId, options: FindOneAndReplaceOptions & { + includeResultMetadata: true; + }): Promise>; + findOneAndReplace(filter: Filter, replacement: WithoutId, options: FindOneAndReplaceOptions & { + includeResultMetadata: false; + }): Promise | null>; + findOneAndReplace(filter: Filter, replacement: WithoutId, options: FindOneAndReplaceOptions): Promise | null>; + findOneAndReplace(filter: Filter, replacement: WithoutId): Promise | null>; + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + */ + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions & { + includeResultMetadata: true; + }): Promise>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions & { + includeResultMetadata: false; + }): Promise | null>; + findOneAndUpdate(filter: Filter, update: UpdateFilter, options: FindOneAndUpdateOptions): Promise | null>; + findOneAndUpdate(filter: Filter, update: UpdateFilter): Promise | null>; + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to override the schema that may be defined for this specific collection + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * @example + * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` + * ```ts + * collection.watch<{ _id: number }>() + * .on('change', change => console.log(change._id.toFixed(4))); + * ``` + * + * @example + * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. + * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. + * No need start from scratch on the ChangeStreamInsertDocument type! + * By using an intersection we can save time and ensure defaults remain the same type! + * ```ts + * collection + * .watch & { comment: string }>([ + * { $addFields: { comment: 'big changes' } }, + * { $match: { operationType: 'insert' } } + * ]) + * .on('change', change => { + * change.comment.startsWith('big'); + * change.operationType === 'insert'; + * // No need to narrow in code because the generics did that for us! + * expectType(change.fullDocument); + * }); + * ``` + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TLocal - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation; + /** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation; + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + */ + count(filter?: Filter, options?: CountOptions): Promise; + /** + * Returns all search indexes for the current collection. + * + * @param options - The options for the list indexes operation. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + listSearchIndexes(options?: ListSearchIndexesOptions): ListSearchIndexesCursor; + /** + * Returns all search indexes for the current collection. + * + * @param name - The name of the index to search for. Only indexes with matching index names will be returned. + * @param options - The options for the list indexes operation. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + listSearchIndexes(name: string, options?: ListSearchIndexesOptions): ListSearchIndexesCursor; + /** + * Creates a single search index for the collection. + * + * @param description - The index description for the new search index. + * @returns A promise that resolves to the name of the new search index. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + createSearchIndex(description: SearchIndexDescription): Promise; + /** + * Creates multiple search indexes for the current collection. + * + * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes. + * @returns A promise that resolves to an array of the newly created search index names. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + * @returns + */ + createSearchIndexes(descriptions: SearchIndexDescription[]): Promise; + /** + * Deletes a search index by index name. + * + * @param name - The name of the search index to be deleted. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + dropSearchIndex(name: string): Promise; + /** + * Updates a search index by replacing the existing index definition with the provided definition. + * + * @param name - The name of the search index to update. + * @param definition - The new search index definition. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + updateSearchIndex(name: string, definition: Document): Promise; +} + +/** @public */ +export declare interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} + +/** @public */ +export declare interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions { + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} + +/* Excluded from this release type: CollectionPrivate */ + +/* Excluded from this release type: COMMAND_FAILED */ + +/* Excluded from this release type: COMMAND_STARTED */ + +/* Excluded from this release type: COMMAND_SUCCEEDED */ + +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export declare class CommandFailedEvent { + address: string; + /** Driver generated connection id */ + connectionId?: string | number; + /** + * Server generated connection id + * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+. + */ + serverConnectionId: bigint | null; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/* Excluded from this release type: CommandOperation */ + +/** @public */ +export declare interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions { + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + /** Should retry failed writes */ + retryWrites?: boolean; + dbName?: string; + authdb?: string; + noResponse?: boolean; +} + +/* Excluded from this release type: CommandOptions */ + +/** + * An event indicating the start of a given command + * @public + * @category Event + */ +export declare class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + /** Driver generated connection id */ + connectionId?: string | number; + /** + * Server generated connection id + * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" + * from the server on 4.2+. + */ + serverConnectionId: bigint | null; + serviceId?: ObjectId; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export declare class CommandSucceededEvent { + address: string; + /** Driver generated connection id */ + connectionId?: string | number; + /** + * Server generated connection id + * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+. + */ + serverConnectionId: bigint | null; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ + get hasServiceId(): boolean; +} + +/** @public */ +export declare type CommonEvents = 'newListener' | 'removeListener'; + +/** @public */ +export declare const Compressor: Readonly<{ + readonly none: 0; + readonly snappy: 1; + readonly zlib: 2; + readonly zstd: 3; +}>; + +/** @public */ +export declare type Compressor = (typeof Compressor)[CompressorName]; + +/** @public */ +export declare type CompressorName = keyof typeof Compressor; + +/** @public */ +export declare type Condition = AlternativeType | FilterOperators>; + +/* Excluded from this release type: Connection */ + +/* Excluded from this release type: CONNECTION_CHECK_OUT_FAILED */ + +/* Excluded from this release type: CONNECTION_CHECK_OUT_STARTED */ + +/* Excluded from this release type: CONNECTION_CHECKED_IN */ + +/* Excluded from this release type: CONNECTION_CHECKED_OUT */ + +/* Excluded from this release type: CONNECTION_CLOSED */ + +/* Excluded from this release type: CONNECTION_CREATED */ + +/* Excluded from this release type: CONNECTION_POOL_CLEARED */ + +/* Excluded from this release type: CONNECTION_POOL_CLOSED */ + +/* Excluded from this release type: CONNECTION_POOL_CREATED */ + +/* Excluded from this release type: CONNECTION_POOL_READY */ + +/* Excluded from this release type: CONNECTION_READY */ + +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export declare class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export declare class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: string; + /* Excluded from this release type: error */ + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export declare class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export declare class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; + /* Excluded from this release type: name */ + /* Excluded from this release type: error */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export declare class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; + +/** @public */ +export declare interface ConnectionOptions extends SupportedNodeConnectionOptions, StreamDescriptionOptions, ProxyOptions { + id: number | ''; + generation: number; + hostAddress: HostAddress; + /* Excluded from this release type: autoEncrypter */ + serverApi?: ServerApi; + monitorCommands: boolean; + /* Excluded from this release type: connectionType */ + credentials?: MongoCredentials; + /* Excluded from this release type: authProviders */ + connectTimeoutMS?: number; + tls: boolean; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + metadata: ClientMetadata; + /* Excluded from this release type: extendedMetadata */ + /* Excluded from this release type: mongoLogger */ +} + +/* Excluded from this release type: ConnectionPool */ + +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export declare class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: serviceId */ + interruptInUseConnections?: boolean; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export declare class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export declare class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options: Pick; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolReady(event: ConnectionPoolReadyEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Omit; + +/* Excluded from this release type: ConnectionPoolMetrics */ + +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export declare abstract class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface ConnectionPoolOptions extends Omit { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; + /* Excluded from this release type: minPoolSizeCheckFrequencyMS */ +} + +/** + * An event published when a connection pool is ready + * @public + * @category Event + */ +export declare class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export declare class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface ConnectOptions { + readPreference?: ReadPreference; +} + +/** @public */ +export declare interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} + +/** @public */ +export declare interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} + +/** @public */ +export declare interface CreateCollectionOptions extends CommandOperationOptions { + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view (i.e., does not include the database name and implies the same database as the view to create) */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */ + clusteredIndex?: ClusteredCollectionOptions; + /** The number of seconds after which a document in a timeseries or clustered collection expires. */ + expireAfterSeconds?: number; + /** @experimental */ + encryptedFields?: Document; + /** + * If set, enables pre-update and post-update document events to be included for any + * change streams that listen on this collection. + */ + changeStreamPreAndPostImages?: { + enabled: boolean; + }; +} + +/** @public */ +export declare interface CreateIndexesOptions extends Omit { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + bucketSize?: number; + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} + +/** @public */ +export declare type CSFLEKMSTlsOptions = { + aws?: ClientEncryptionTlsOptions; + gcp?: ClientEncryptionTlsOptions; + kmip?: ClientEncryptionTlsOptions; + local?: ClientEncryptionTlsOptions; + azure?: ClientEncryptionTlsOptions; +}; + +/** @public */ +export declare const CURSOR_FLAGS: readonly ["tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial"]; + +/** @public */ +export declare type CursorFlag = (typeof CURSOR_FLAGS)[number]; + +/** @public */ +export declare interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(this: void, doc: Document): Document; +} + +/** + * @public + * The schema for a DataKey in the key vault collection. + */ +export declare interface DataKey { + _id: UUID; + version?: number; + keyAltNames?: string[]; + keyMaterial: Binary; + creationDate: Date; + updateDate: Date; + status: number; + masterKey: Document; +} + +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +export declare class Db { + /* Excluded from this release type: s */ + /* Excluded from this release type: client */ + static SYSTEM_NAMESPACE_COLLECTION: string; + static SYSTEM_INDEX_COLLECTION: string; + static SYSTEM_PROFILE_COLLECTION: string; + static SYSTEM_USER_COLLECTION: string; + static SYSTEM_COMMAND_COLLECTION: string; + static SYSTEM_JS_COLLECTION: string; + /** + * Creates a new Db instance. + * + * Db name cannot contain a dot, the server may apply more restrictions when an operation is run. + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction. + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions); + get databaseName(): string; + get options(): DbOptions | undefined; + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk(): boolean; + get readConcern(): ReadConcern | undefined; + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference(): ReadPreference; + get bsonOptions(): BSONSerializeOptions; + get writeConcern(): WriteConcern | undefined; + get namespace(): string; + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/ + * + * Collection namespace validation is performed server-side. + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + */ + createCollection(name: string, options?: CreateCollectionOptions): Promise>; + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * The driver will ensure the following fields are attached to the command sent to the server: + * - `lsid` - sourced from an implicit session or options.session + * - `$readPreference` - defaults to primary or can be configured by options.readPreference + * - `$db` - sourced from the name of this database + * + * If the client has a serverApi setting: + * - `apiVersion` + * - `apiStrict` + * - `apiDeprecationErrors` + * + * When in a transaction: + * - `readConcern` - sourced from readConcern set on the TransactionOptions + * - `writeConcern` - sourced from writeConcern set on the TransactionOptions + * + * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. + * + * @param command - The command to run + * @param options - Optional settings for the command + */ + command(command: Document, options?: RunCommandOptions): Promise; + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline?: Document[], options?: AggregateOptions): AggregationCursor; + /** Return the Admin db instance */ + admin(): Admin; + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * Collection namespace validation is performed server-side. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name: string, options?: CollectionOptions): Collection; + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + stats(options?: DbStatsOptions): Promise; + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections(filter: Document, options: Exclude & { + nameOnly: true; + }): ListCollectionsCursor>; + listCollections(filter: Document, options: Exclude & { + nameOnly: false; + }): ListCollectionsCursor; + listCollections | CollectionInfo = Pick | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + */ + renameCollection(fromCollection: string, toCollection: string, options?: RenameOptions): Promise>; + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + */ + dropCollection(name: string, options?: DropCollectionOptions): Promise; + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + dropDatabase(options?: DropDatabaseOptions): Promise; + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + collections(options?: ListCollectionsOptions): Promise; + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + */ + createIndex(name: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + removeUser(username: string, options?: RemoveUserOptions): Promise; + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + setProfilingLevel(level: ProfilingLevel, options?: SetProfilingLevelOptions): Promise; + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + profilingLevel(options?: ProfilingLevelOptions): Promise; + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + indexInformation(name: string, options?: IndexInformationOptions): Promise; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to provide the schema that may be defined for all the collections within this database + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; + /** + * A low level cursor API providing basic driver functionality: + * - ClientSession management + * - ReadPreference for server selection + * - Running getMores automatically when a local batch is exhausted + * + * @param command - The command that will start a cursor on the server. + * @param options - Configurations for running the command, bson options will apply to getMores + */ + runCursorCommand(command: Document, options?: RunCursorCommandOptions): RunCommandCursor; +} + +/* Excluded from this release type: DB_AGGREGATE_COLLECTION */ + +/** @public */ +export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} + +/* Excluded from this release type: DbPrivate */ +export { DBRef } + +/** @public */ +export declare interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +export { Decimal128 } + +/** @public */ +export declare interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export declare interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export declare interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export declare interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} + +/** @public */ +export declare interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +export { deserialize } + +/** @public */ +export declare type DistinctOptions = CommandOperationOptions; + +export { Document } + +export { Double } + +/** @public */ +export declare interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} + +/** @public */ +export declare interface DropCollectionOptions extends CommandOperationOptions { + /** @experimental */ + encryptedFields?: Document; +} + +/** @public */ +export declare type DropDatabaseOptions = CommandOperationOptions; + +/** @public */ +export declare type DropIndexesOptions = CommandOperationOptions; + +/* Excluded from this release type: Encrypter */ + +/* Excluded from this release type: EncrypterOptions */ + +/** @public */ +export declare interface EndSessionOptions { + /* Excluded from this release type: error */ + force?: boolean; + forceClear?: boolean; +} + +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export declare type EnhancedOmit = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick> : never; + +/** @public */ +export declare interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} + +/** @public */ +export declare interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} + +/** @public */ +export declare type EventEmitterWithState = { + /* Excluded from this release type: stateChanged */ +}; + +/** + * Event description type + * @public + */ +export declare type EventsDescription = Record; + +/* Excluded from this release type: ExecutionResult */ + +/* Excluded from this release type: Explain */ + +/** @public */ +export declare interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} + +/** @public */ +export declare const ExplainVerbosity: Readonly<{ + readonly queryPlanner: "queryPlanner"; + readonly queryPlannerExtended: "queryPlannerExtended"; + readonly executionStats: "executionStats"; + readonly allPlansExecution: "allPlansExecution"; +}>; + +/** @public */ +export declare type ExplainVerbosity = string; + +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export declare type ExplainVerbosityLike = ExplainVerbosity | boolean; + +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export declare type Filter = { + [P in keyof WithId]?: Condition[P]>; +} & RootFilterOperators>; + +/** @public */ +export declare type FilterOperations = T extends Record ? { + [key in keyof T]?: FilterOperators; +} : FilterOperators; + +/** @public */ +export declare interface FilterOperators extends NonObjectIdLikeDocument { + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [number, number] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + $geoIntersects?: { + $geometry: Document; + }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} + +/** @public */ +export declare class FindCursor extends AbstractCursor { + /* Excluded from this release type: [kFilter] */ + /* Excluded from this release type: [kNumReturned] */ + /* Excluded from this release type: [kBuiltOptions] */ + /* Excluded from this release type: __constructor */ + clone(): FindCursor; + map(transform: (doc: TSchema) => T): FindCursor; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: getMore */ + /** + * Get the count of documents for this cursor + * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead + */ + count(options?: CountOptions): Promise; + /** Execute the explain for the cursor */ + explain(verbosity?: ExplainVerbosityLike): Promise; + /** Set the cursor query */ + filter(filter: Document): this; + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this; + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this; + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this; + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this; + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this; + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this; + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this; + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this; + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this; + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor; + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this; + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(allow?: boolean): this; + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this; + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this; + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this; +} + +/** @public */ +export declare interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Return the ModifyResult instead of the modified document. Defaults to false + */ + includeResultMetadata?: boolean; +} + +/** @public */ +export declare interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Return the ModifyResult instead of the modified document. Defaults to false + */ + includeResultMetadata?: boolean; +} + +/** @public */ +export declare interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Return the ModifyResult instead of the modified document. Defaults to false + */ + includeResultMetadata?: boolean; +} + +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export declare class FindOperators { + bulkOperation: BulkOperationBase; + /* Excluded from this release type: __constructor */ + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document | Document[]): BulkOperationBase; + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document | Document[]): BulkOperationBase; + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase; + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase; + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase; + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this; + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this; + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this; + /** Specifies hint for the bulk operation. */ + hint(hint: Hint): this; +} + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +export declare interface FindOptions extends Omit { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true. + * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored. + */ + oplogReplay?: boolean; +} + +/** @public */ +export declare type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** + * @public + * Configuration options for making an AWS encryption key + */ +export declare interface GCPEncryptionKeyOptions { + /** + * GCP project ID + */ + projectId: string; + /** + * Location name (e.g. "global") + */ + location: string; + /** + * Key ring name + */ + keyRing: string; + /** + * Key name + */ + keyName: string; + /** + * Key version + */ + keyVersion?: string | undefined; + /** + * KMS URL, defaults to `https://www.googleapis.com/auth/cloudkms` + */ + endpoint?: string | undefined; +} + +/** @public */ +export declare type GenericListener = (...args: any[]) => void; + +/** + * Constructor for a streaming GridFS interface + * @public + */ +export declare class GridFSBucket extends TypedEventEmitter { + /* Excluded from this release type: s */ + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX: "index"; + constructor(db: Db, options?: GridFSBucketOptions); + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId(id: ObjectId, filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream; + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id: ObjectId, options?: GridFSBucketReadStreamOptions): GridFSBucketReadStream; + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + delete(id: ObjectId): Promise; + /** Convenience wrapper around find on the files collection */ + find(filter?: Filter, options?: FindOptions): FindCursor; + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName(filename: string, options?: GridFSBucketReadStreamOptionsWithRevision): GridFSBucketReadStream; + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + rename(id: ObjectId, filename: string): Promise; + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; +} + +/** @public */ +export declare type GridFSBucketEvents = { + index(): void; +}; + +/** @public */ +export declare interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} + +/* Excluded from this release type: GridFSBucketPrivate */ + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export declare class GridFSBucketReadStream extends Readable { + /* Excluded from this release type: s */ + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE: "file"; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: _read */ + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start?: number): this; + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end?: number): this; + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + */ + abort(): Promise; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** + * 0-indexed non-negative byte offset from the beginning of the file + */ + start?: number; + /** + * 0-indexed non-negative byte offset to the end of the file contents + * to be returned by the stream. `end` is non-inclusive + */ + end?: number; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} + +/* Excluded from this release type: GridFSBucketReadStreamPrivate */ + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export declare class GridFSBucketWriteStream extends Writable { + bucket: GridFSBucket; + /** A Collection instance where the file's chunks are stored */ + chunks: Collection; + /** A Collection instance where the file's GridFSFile document is stored */ + files: Collection; + /** The name of the file */ + filename: string; + /** Options controlling the metadata inserted along with the file */ + options: GridFSBucketWriteStreamOptions; + /** Indicates the stream is finished uploading */ + done: boolean; + /** The ObjectId used for the `_id` field on the GridFSFile document */ + id: ObjectId; + /** The number of bytes that each chunk will be limited to */ + chunkSizeBytes: number; + /** Space used to store a chunk currently being inserted */ + bufToStore: Buffer; + /** Accumulates the number of bytes inserted as the stream uploads chunks */ + length: number; + /** Accumulates the number of chunks inserted as the stream uploads file contents */ + n: number; + /** Tracks the current offset into the buffered bytes being uploaded */ + pos: number; + /** Contains a number of properties indicating the current state of the stream */ + state: { + /** If set the stream has ended */ + streamEnd: boolean; + /** Indicates the number of chunks that still need to be inserted to exhaust the current buffered data */ + outstandingRequests: number; + /** If set an error occurred during insertion */ + errored: boolean; + /** If set the stream was intentionally aborted */ + aborted: boolean; + }; + /** The write concern setting to be used with every insert operation */ + writeConcern?: WriteConcern; + /** + * The document containing information about the inserted file. + * This property is defined _after_ the finish event has been emitted. + * It will remain `null` if an error occurs. + * + * @example + * ```ts + * fs.createReadStream('file.txt') + * .pipe(bucket.openUploadStream('file.txt')) + * .on('finish', function () { + * console.log(this.gridFSFile) + * }) + * ``` + */ + gridFSFile: GridFSFile | null; + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: _construct */ + /* Excluded from this release type: _write */ + /* Excluded from this release type: _final */ + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + abort(): Promise; +} + +/** @public */ +export declare interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** + * String to store in the file document's `contentType` field. + * @deprecated Will be removed in the next major version. Add a contentType field to the metadata document instead. + */ + contentType?: string; + /** + * Array of strings to store in the file document's `aliases` field. + * @deprecated Will be removed in the next major version. Add an aliases field to the metadata document instead. + */ + aliases?: string[]; +} + +/** @public */ +export declare interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} + +/** @public */ +export declare interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + metadata?: Document; + uploadDate: Date; + /** @deprecated Will be removed in the next major version. */ + contentType?: string; + /** @deprecated Will be removed in the next major version. */ + aliases?: string[]; +} + +/** @public */ +export declare const GSSAPICanonicalizationValue: Readonly<{ + readonly on: true; + readonly off: false; + readonly none: "none"; + readonly forward: "forward"; + readonly forwardAndReverse: "forwardAndReverse"; +}>; + +/** @public */ +export declare type GSSAPICanonicalizationValue = (typeof GSSAPICanonicalizationValue)[keyof typeof GSSAPICanonicalizationValue]; + +/* Excluded from this release type: HandshakeDocument */ + +/** @public */ +export declare interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} + +/** @public */ +export declare type Hint = string | Document; + +/** @public */ +export declare class HostAddress { + host: string | undefined; + port: number | undefined; + socketPath: string | undefined; + isIPv6: boolean; + constructor(hostString: string); + inspect(): string; + toString(): string; + static fromString(this: void, s: string): HostAddress; + static fromHostPort(host: string, port: number): HostAddress; + static fromSrvRecord({ name, port }: SrvRecord): HostAddress; + toHostPort(): { + host: string; + port: number; + }; +} + +/** + * @public + * @experimental + */ +export declare interface IdPServerInfo { + issuer: string; + clientId: string; + requestScopes?: string[]; +} + +/** + * @public + * @experimental + */ +export declare interface IdPServerResponse { + accessToken: string; + expiresInSeconds?: number; + refreshToken?: string; +} + +/** @public */ +export declare interface IndexDescription extends Pick { + collation?: CollationOptions; + name?: string; + key: { + [key: string]: IndexDirection; + } | Map; +} + +/** @public */ +export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | 'hashed' | number; + +/** @public */ +export declare interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} + +/** @public */ +export declare type IndexSpecification = OneOrMore>; + +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export declare type InferIdType = TSchema extends { + _id: infer IdType; +} ? Record extends IdType ? never : IdType : TSchema extends { + _id?: infer IdType; +} ? unknown extends IdType ? ObjectId : IdType : ObjectId; + +/** @public */ +export declare interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { + [key: number]: InferIdType; + }; +} + +/** @public */ +export declare interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} + +/** @public */ +export declare interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export declare interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} + +export { Int32 } + +/** @public */ +export declare type IntegerType = number | Int32 | Long | bigint; + +/* Excluded from this release type: InternalAbstractCursorOptions */ + +/** @public */ +export declare type IsAny = true extends false & Type ? ResultIfAny : ResultIfNotAny; + +/** + * Helper types for dot-notation filter attributes + */ +/** @public */ +export declare type Join = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join}` : string; + +/* Excluded from this release type: kBeforeHandshake */ + +/* Excluded from this release type: kBuiltOptions */ + +/* Excluded from this release type: kCancellationToken */ + +/* Excluded from this release type: kCancellationToken_2 */ + +/* Excluded from this release type: kCancelled */ + +/* Excluded from this release type: kCancelled_2 */ + +/* Excluded from this release type: kCheckedOut */ + +/* Excluded from this release type: kClient */ + +/* Excluded from this release type: kClosed */ + +/* Excluded from this release type: kClosed_2 */ + +/* Excluded from this release type: kConnectionCounter */ + +/* Excluded from this release type: kConnections */ + +/* Excluded from this release type: kCursorStream */ + +/* Excluded from this release type: kDecorateResult */ + +/* Excluded from this release type: kDocuments */ + +/* Excluded from this release type: kErrorLabels */ + +/** @public */ +export declare type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; + +/** @public */ +export declare type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; + +/* Excluded from this release type: kFilter */ + +/* Excluded from this release type: kGeneration */ + +/* Excluded from this release type: kId */ + +/* Excluded from this release type: kInit */ + +/* Excluded from this release type: kInitialized */ + +/* Excluded from this release type: kInternalClient */ + +/* Excluded from this release type: kKilled */ + +/* Excluded from this release type: kMetrics */ + +/* Excluded from this release type: kMinPoolSizeTimer */ + +/* Excluded from this release type: kMode */ + +/* Excluded from this release type: kMonitorId */ + +/** + * @public + * Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. + */ +export declare interface KMSProviders { + /** + * Configuration options for using 'aws' as your KMS provider + */ + aws?: { + /** + * The access key used for the AWS KMS provider + */ + accessKeyId: string; + /** + * The secret access key used for the AWS KMS provider + */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + } | Record; + /** + * Configuration options for using 'local' as your KMS provider + */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** + * Configuration options for using 'kmip' as your KMS provider + */ + kmip?: { + /** + * The output endpoint string. + * The endpoint consists of a hostname and port separated by a colon. + * E.g. "example.com:123". A port is always present. + */ + endpoint?: string; + }; + /** + * Configuration options for using 'azure' as your KMS provider + */ + azure?: { + /** + * The tenant ID identifies the organization for the account + */ + tenantId: string; + /** + * The client ID to authenticate a registered application + */ + clientId: string; + /** + * The client secret to authenticate a registered application + */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + } | { + /** + * If present, an access token to authenticate with Azure. + */ + accessToken: string; + } | Record; + /** + * Configuration options for using 'gcp' as your KMS provider + */ + gcp?: { + /** + * The service account email to authenticate + */ + email: string; + /** + * A PKCS#8 encrypted key. This can either be a base64 string or a binary representation + */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + } | { + /** + * If present, an access token to authenticate with GCP. + */ + accessToken: string; + } | Record; +} + +/* Excluded from this release type: kNamespace */ + +/* Excluded from this release type: kNumReturned */ + +/* Excluded from this release type: kOptions */ + +/* Excluded from this release type: kOptions_2 */ + +/* Excluded from this release type: kOptions_3 */ + +/* Excluded from this release type: kPending */ + +/* Excluded from this release type: kPinnedConnection */ + +/* Excluded from this release type: kPipeline */ + +/* Excluded from this release type: kPoolState */ + +/* Excluded from this release type: kProcessingWaitQueue */ + +/* Excluded from this release type: kRoundTripTime */ + +/* Excluded from this release type: kServer */ + +/* Excluded from this release type: kServer_2 */ + +/* Excluded from this release type: kServer_3 */ + +/* Excluded from this release type: kServerError */ + +/* Excluded from this release type: kServerSession */ + +/* Excluded from this release type: kServiceGenerations */ + +/* Excluded from this release type: kSession */ + +/* Excluded from this release type: kSession_2 */ + +/* Excluded from this release type: kSnapshotEnabled */ + +/* Excluded from this release type: kSnapshotTime */ + +/* Excluded from this release type: kTransform */ + +/* Excluded from this release type: kTxnNumberIncrement */ + +/* Excluded from this release type: kWaitQueue */ + +/* Excluded from this release type: kWaitQueue_2 */ + +/** @public */ +export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["family", "hints", "localAddress", "localPort", "lookup"]; + +/** @public */ +export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly ["ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"]; + +/* Excluded from this release type: List */ + +/** @public */ +export declare class ListCollectionsCursor | CollectionInfo = Pick | CollectionInfo> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + constructor(db: Db, filter: Document, options?: ListCollectionsOptions); + clone(): ListCollectionsCursor; + /* Excluded from this release type: _initialize */ +} + +/** @public */ +export declare interface ListCollectionsOptions extends Omit { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** Since 4.0: If true and nameOnly is true, allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced. */ + authorizedCollections?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @public */ +export declare interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} + +/** @public */ +export declare interface ListDatabasesResult { + databases: ({ + name: string; + sizeOnDisk?: number; + empty?: boolean; + } & Document)[]; + totalSize?: number; + totalSizeMb?: number; + ok: 1 | 0; +} + +/** @public */ +export declare class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + constructor(collection: Collection, options?: ListIndexesOptions); + clone(): ListIndexesCursor; + /* Excluded from this release type: _initialize */ +} + +/** @public */ +export declare interface ListIndexesOptions extends Omit { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @public */ +export declare class ListSearchIndexesCursor extends AggregationCursor<{ + name: string; +}> { + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare type ListSearchIndexesOptions = AggregateOptions; + +/* Excluded from this release type: Log */ + +/* Excluded from this release type: LogComponentSeveritiesClientOptions */ + +/* Excluded from this release type: LogConvertible */ + +/* Excluded from this release type: Loggable */ + +/* Excluded from this release type: LoggableCommandFailedEvent */ + +/* Excluded from this release type: LoggableCommandSucceededEvent */ + +/* Excluded from this release type: LoggableEvent */ + +/* Excluded from this release type: LoggableServerHeartbeatFailedEvent */ + +/* Excluded from this release type: LoggableServerHeartbeatStartedEvent */ + +/* Excluded from this release type: LoggableServerHeartbeatSucceededEvent */ +export { Long } + +/** @public */ +export declare type MatchKeysAndValues = Readonly> & Record; + +export { MaxKey } + +/* Excluded from this release type: MessageHeader */ +export { MinKey } + +/** @public */ +export declare interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export declare const MONGO_CLIENT_EVENTS: readonly ["connectionPoolCreated", "connectionPoolReady", "connectionPoolCleared", "connectionPoolClosed", "connectionCreated", "connectionReady", "connectionClosed", "connectionCheckOutStarted", "connectionCheckOutFailed", "connectionCheckedOut", "connectionCheckedIn", "commandStarted", "commandSucceeded", "commandFailed", "serverOpening", "serverClosed", "serverDescriptionChanged", "topologyOpening", "topologyClosed", "topologyDescriptionChanged", "error", "timeout", "close", "serverHeartbeatStarted", "serverHeartbeatSucceeded", "serverHeartbeatFailed"]; + +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +export declare class MongoAPIError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { + cause?: Error; + }); + get name(): string; +} + +/** + * A error generated when the user attempts to authenticate + * via AWS, but fails + * + * @public + * @category Error + */ +export declare class MongoAWSError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * A error generated when the user attempts to authenticate + * via Azure, but fails. + * + * @public + * @category Error + */ +export declare class MongoAzureError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a batch command is re-executed after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export declare class MongoBatchReExecutionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export declare class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore; + err?: WriteConcernError; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(error: { + message: string; + code: number; + writeErrors?: WriteError[]; + } | WriteConcernError | AnyError, result: BulkWriteResult); + get name(): string; + /** Number of documents inserted. */ + get insertedCount(): number; + /** Number of documents matched for update. */ + get matchedCount(): number; + /** Number of documents modified. */ + get modifiedCount(): number; + /** Number of documents deleted. */ + get deletedCount(): number; + /** Number of documents upserted. */ + get upsertedCount(): number; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { + [key: number]: any; + }; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { + [key: number]: any; + }; +} + +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoChangeStreamError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +export declare class MongoClient extends TypedEventEmitter { + /* Excluded from this release type: s */ + /* Excluded from this release type: topology */ + /* Excluded from this release type: mongoLogger */ + /* Excluded from this release type: connectionLock */ + /* Excluded from this release type: [kOptions] */ + constructor(url: string, options?: MongoClientOptions); + /* Excluded from this release type: checkForNonGenuineHosts */ + /** @see MongoOptions */ + get options(): Readonly; + get serverApi(): Readonly; + /* Excluded from this release type: monitorCommands */ + /* Excluded from this release type: monitorCommands */ + /* Excluded from this release type: autoEncrypter */ + get readConcern(): ReadConcern | undefined; + get writeConcern(): WriteConcern | undefined; + get readPreference(): ReadPreference; + get bsonOptions(): BSONSerializeOptions; + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + /* Excluded from this release type: _connect */ + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + close(force?: boolean): Promise; + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db; + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @see https://www.mongodb.com/docs/manual/reference/connection-string/ + */ + static connect(url: string, options?: MongoClientOptions): Promise; + /** + * Creates a new ClientSession. When using the returned session in an operation + * a corresponding ServerSession will be created. + * + * @remarks + * A ClientSession instance may only be passed to operations being performed on the same + * MongoClient it was started from. + */ + startSession(options?: ClientSessionOptions): ClientSession; + /** + * A convenience method for creating and handling the clean up of a ClientSession. + * The session will always be ended when the executor finishes. + * + * @param executor - An executor function that all operations using the provided session must be invoked in + * @param options - optional settings for the session + */ + withSession(executor: WithSessionCallback): Promise; + withSession(options: ClientSessionOptions, executor: WithSessionCallback): Promise; + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to provide the schema that may be defined for all the data within the current cluster + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream; +} + +/* Excluded from this release type: MongoClientAuthProviders */ + +/** @public */ +export declare type MongoClientEvents = Pick & { + open(mongoClient: MongoClient): void; +}; + +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://www.mongodb.com/docs/manual/reference/connection-string + */ +export declare interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /* Excluded from this release type: timeoutMS */ + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Specifies the location of a local CRL .pem file that contains the client revokation list. */ + tlsCRLFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */ + srvMaxHosts?: number; + /** + * Modifies the srv URI to look like: + * + * `_{srvServiceName}._tcp.{hostname}.{domainname}` + * + * Querying this DNS URI is expected to respond with SRV records + */ + srvServiceName?: string; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + /** + * The write concern w value + * @deprecated Please use the `writeConcern` option instead + */ + w?: W; + /** + * The write concern timeout + * @deprecated Please use the `writeConcern` option instead + */ + wtimeoutMS?: number; + /** + * The journal write concern + * @deprecated Please use the `writeConcern` option instead + */ + journal?: boolean; + /** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * + * @see https://www.mongodb.com/docs/manual/reference/write-concern/ + */ + writeConcern?: WriteConcern | WriteConcernSettings; + /** TCP Connection no delay */ + noDelay?: boolean; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable in-use auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; + /** Configures a Socks5 proxy host used for creating TCP connections. */ + proxyHost?: string; + /** Configures a Socks5 proxy port used for creating TCP connections. */ + proxyPort?: number; + /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */ + proxyUsername?: string; + /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */ + proxyPassword?: string; + /** Instructs the driver monitors to use a specific monitoring mode */ + serverMonitoringMode?: ServerMonitoringMode; + /* Excluded from this release type: srvPoller */ + /* Excluded from this release type: connectionType */ + /* Excluded from this release type: mongodbLogPath */ + /* Excluded from this release type: mongodbLogComponentSeverities */ + /* Excluded from this release type: mongodbLogMaxDocumentLength */ + /* Excluded from this release type: __index */ +} + +/* Excluded from this release type: MongoClientPrivate */ + +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export declare class MongoCompatibilityError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * A representation of the credentials used by MongoDB + * @public + */ +export declare class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + constructor(options: MongoCredentialsOptions); + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean; + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param hello - A hello response from the server + */ + resolveAuthMechanism(hello: Document | null): MongoCredentials; + validate(): void; + static merge(creds: MongoCredentials | undefined, options: Partial): MongoCredentials; +} + +/** @public */ +export declare interface MongoCredentialsOptions { + username?: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} + +/** + * @public + * An error indicating that mongodb-client-encryption failed to auto-refresh Azure KMS credentials. + */ +export declare class MongoCryptAzureKMSRequestError extends MongoCryptError { + /** The body of the http response that failed, if present. */ + body?: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, body?: Document); + get name(): string; +} + +/** + * @public + * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create data keys + */ +export declare class MongoCryptCreateDataKeyError extends MongoCryptError { + encryptedFields: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(encryptedFields: Document, { cause }: { + cause: Error; + }); + get name(): string; +} + +/** + * @public + * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create a collection + */ +export declare class MongoCryptCreateEncryptedCollectionError extends MongoCryptError { + encryptedFields: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(encryptedFields: Document, { cause }: { + cause: Error; + }); + get name(): string; +} + +/* Excluded from this release type: MongocryptdManager */ + +/** + * @public + * An error indicating that something went wrong specifically with MongoDB Client Encryption + */ +export declare class MongoCryptError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { + cause?: Error; + }); + get name(): string; +} + +/** + * @public + * + * An error indicating an invalid argument was provided to an encryption API. + */ +export declare class MongoCryptInvalidArgumentError extends MongoCryptError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** @public */ +export declare class MongoCryptKMSRequestNetworkTimeoutError extends MongoCryptError { + get name(): string; +} + +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export declare class MongoCursorExhaustedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export declare class MongoCursorInUseError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * @public + * + * A class representing a collection's namespace. This class enforces (through Typescript) that + * the `collection` portion of the namespace is defined and should only be + * used in scenarios where this can be guaranteed. + */ +export declare class MongoDBCollectionNamespace extends MongoDBNamespace { + collection: string; + constructor(db: string, collection: string); + static fromString(namespace?: string): MongoDBCollectionNamespace; +} + +/* Excluded from this release type: MongoDBLogWritable */ + +/** @public */ +export declare class MongoDBNamespace { + db: string; + collection?: string | undefined; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string | undefined); + toString(): string; + withCollection(collection: string): MongoDBCollectionNamespace; + static fromString(namespace?: string): MongoDBNamespace; +} + +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export declare class MongoDecompressionError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export declare class MongoDriverError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { + cause?: Error; + }); + get name(): string; +} + +/** + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument + */ +export declare class MongoError extends Error { + /* Excluded from this release type: [kErrorLabels] */ + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + connectionGeneration?: number; + cause?: Error; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { + cause?: Error; + }); + /* Excluded from this release type: buildErrorMessage */ + get name(): string; + /** Legacy name for server error responses */ + get errmsg(): string; + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean; + addErrorLabel(label: string): void; + get errorLabels(): string[]; +} + +/** @public */ +export declare const MongoErrorLabel: Readonly<{ + readonly RetryableWriteError: "RetryableWriteError"; + readonly TransientTransactionError: "TransientTransactionError"; + readonly UnknownTransactionCommitResult: "UnknownTransactionCommitResult"; + readonly ResumableChangeStreamError: "ResumableChangeStreamError"; + readonly HandshakeError: "HandshakeError"; + readonly ResetPool: "ResetPool"; + readonly PoolRequstedRetry: "PoolRequstedRetry"; + readonly InterruptInUseConnections: "InterruptInUseConnections"; + readonly NoWritesPerformed: "NoWritesPerformed"; +}>; + +/** @public */ +export declare type MongoErrorLabel = (typeof MongoErrorLabel)[keyof typeof MongoErrorLabel]; + +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export declare class MongoExpiredSessionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export declare class MongoGridFSChunkError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export declare class MongoGridFSStreamError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export declare class MongoInvalidArgumentError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export declare class MongoKerberosError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/* Excluded from this release type: MongoLoggableComponent */ + +/* Excluded from this release type: MongoLogger */ + +/* Excluded from this release type: MongoLoggerEnvOptions */ + +/* Excluded from this release type: MongoLoggerMongoClientOptions */ + +/* Excluded from this release type: MongoLoggerOptions */ + +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export declare class MongoMissingCredentialsError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export declare class MongoMissingDependencyError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { + cause?: Error; + }); + get name(): string; +} + +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export declare class MongoNetworkError extends MongoError { + /* Excluded from this release type: [kBeforeHandshake] */ + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: MongoNetworkErrorOptions); + get name(): string; +} + +/** @public */ +export declare interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake?: boolean; + cause?: Error; +} + +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption has a dependency on this error with an instanceof check + */ +export declare class MongoNetworkTimeoutError extends MongoNetworkError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: MongoNetworkErrorOptions); + get name(): string; +} + +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export declare class MongoNotConnectedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * Parsed Mongo Client Options. + * + * User supplied options are documented by `MongoClientOptions`. + * + * **NOTE:** The client's options parsing is subject to change to support new features. + * This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically. + * + * Options are sourced from: + * - connection string + * - options object passed to the MongoClient constructor + * - file system (ex. tls settings) + * - environment variables + * - DNS SRV records and TXT records + * + * Not all options may be present after client construction as some are obtained from asynchronous operations. + * + * @public + */ +export declare interface MongoOptions extends Required>, SupportedNodeConnectionOptions { + appName?: string; + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + directConnection: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + /* Excluded from this release type: extendedMetadata */ + /* Excluded from this release type: autoEncrypter */ + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; + serverMonitoringMode: ServerMonitoringMode; + /* Excluded from this release type: connectionType */ + /* Excluded from this release type: authProviders */ + /* Excluded from this release type: encrypter */ + /* Excluded from this release type: userSpecifiedAuthSource */ + /* Excluded from this release type: userSpecifiedReplicaSet */ + /** + * # NOTE ABOUT TLS Options + * + * If `tls` is provided as an option, it is equivalent to setting the `ssl` option. + * + * NodeJS native TLS options are passed through to the socket and retain their original types. + * + * ### Additional options: + * + * | nodejs native option | driver spec equivalent option name | driver option type | + * |:----------------------|:----------------------------------------------|:-------------------| + * | `ca` | `tlsCAFile` | `string` | + * | `crl` | `tlsCRLFile` | `string` | + * | `cert` | `tlsCertificateKeyFile` | `string` | + * | `key` | `tlsCertificateKeyFile` | `string` | + * | `passphrase` | `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `tlsAllowInvalidCertificates` | `boolean` | + * | `checkServerIdentity` | `tlsAllowInvalidHostnames` | `boolean` | + * | see note below | `tlsInsecure` | `boolean` | + * + * If `tlsInsecure` is set to `true`, then it will set the node native options `checkServerIdentity` + * to a no-op and `rejectUnauthorized` to `false`. + * + * If `tlsInsecure` is set to `false`, then it will set the node native options `checkServerIdentity` + * to a no-op and `rejectUnauthorized` to the inverse value of `tlsAllowInvalidCertificates`. If + * `tlsAllowInvalidCertificates` is not set, then `rejectUnauthorized` will be set to `true`. + * + * ### Note on `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile` + * + * The files specified by the paths passed in to the `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile` + * fields are read lazily on the first call to `MongoClient.connect`. Once these files have been read and + * the `ca`, `cert`, `crl` and `key` fields are populated, they will not be read again on subsequent calls to + * `MongoClient.connect`. As a result, until the first call to `MongoClient.connect`, the `ca`, + * `cert`, `crl` and `key` fields will be undefined. + */ + tls: boolean; + tlsCAFile?: string; + tlsCRLFile?: string; + tlsCertificateKeyFile?: string; + /* Excluded from this release type: __index */ + /* Excluded from this release type: mongoLoggerOptions */ + /* Excluded from this release type: mongodbLogPath */ +} + +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export declare class MongoParseError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export declare class MongoRuntimeError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { + cause?: Error; + }); + get name(): string; +} + +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export declare class MongoServerClosedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export declare class MongoServerError extends MongoError { + /** Raw error result document returned by server. */ + errorResponse: ErrorDescription; + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: ErrorDescription); + get name(): string; +} + +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export declare class MongoServerSelectionError extends MongoSystemError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, reason: TopologyDescription); + get name(): string; +} + +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export declare class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, reason: TopologyDescription); + get name(): string; +} + +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +export declare class MongoTailableCursorError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export declare class MongoTopologyClosedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string); + get name(): string; +} + +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export declare class MongoTransactionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error generated when a **parsable** unexpected response comes from the server. + * This is generally an error where the driver in a state expecting a certain behavior to occur in + * the next message from MongoDB but it receives something else. + * This error **does not** represent an issue with wire message formatting. + * + * #### Example + * When an operation fails, it is the driver's job to retry it. It must perform serverSelection + * again to make sure that it attempts the operation against a server in a good state. If server + * selection returns a server that does not support retryable operations, this error is used. + * This scenario is unlikely as retryable support would also have been determined on the first attempt + * but it is possible the state change could report a selectable server that does not support retries. + * + * @public + * @category Error + */ +export declare class MongoUnexpectedServerResponseError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string); + get name(): string; +} + +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export declare class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: ErrorDescription, result?: Document); + get name(): string; +} + +/* Excluded from this release type: Monitor */ + +/** @public */ +export declare type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: MongoError): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/* Excluded from this release type: MonitorInterval */ + +/* Excluded from this release type: MonitorIntervalOptions */ + +/** @public */ +export declare interface MonitorOptions extends Omit { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + serverMonitoringMode: ServerMonitoringMode; +} + +/* Excluded from this release type: MonitorPrivate */ + +/** + * @public + * returns tuple of strings (keys to be joined on '.') that represent every path into a schema + * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/ + * + * @remarks + * Through testing we determined that a depth of 8 is safe for the typescript compiler + * and provides reasonable compilation times. This number is otherwise not special and + * should be changed if issues are found with this level of checking. Beyond this + * depth any helpers that make use of NestedPaths should devolve to not asserting any + * type safety on the input. + */ +export declare type NestedPaths = Depth['length'] extends 8 ? [] : Type extends string | number | bigint | boolean | Date | RegExp | Buffer | Uint8Array | ((...args: any[]) => any) | { + _bsontype: string; +} ? [] : Type extends ReadonlyArray ? [] | [number, ...NestedPaths] : Type extends Map ? [string] : Type extends object ? { + [Key in Extract]: Type[Key] extends Type ? [Key] : Type extends Type[Key] ? [Key] : Type[Key] extends ReadonlyArray ? Type extends ArrayType ? [Key] : ArrayType extends Type ? [Key] : [ + Key, + ...NestedPaths + ] : // child is not structured the same as the parent + [ + Key, + ...NestedPaths + ] | [Key]; +}[Extract] : []; + +/** + * @public + * returns keys (strings) for every path into a schema with a value of type + * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/ + */ +export declare type NestedPathsOfType = KeysOfAType<{ + [Property in Join, '.'>]: PropertyType; +}, Type>; + +/** + * @public + * A type that extends Document but forbids anything that "looks like" an object id. + */ +export declare type NonObjectIdLikeDocument = { + [key in keyof ObjectIdLike]?: never; +} & Document; + +/** It avoids using fields with not acceptable types @public */ +export declare type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; + +/** @public */ +export declare type NumericType = IntegerType | Decimal128 | Double; + +export { ObjectId } + +/** + * @public + * @experimental + */ +export declare interface OIDCCallbackContext { + refreshToken?: string; + timeoutSeconds?: number; + timeoutContext?: AbortSignal; + version: number; +} + +/** + * @public + * @experimental + */ +export declare type OIDCRefreshFunction = (info: IdPServerInfo, context: OIDCCallbackContext) => Promise; + +/** + * @public + * @experimental + */ +export declare type OIDCRequestFunction = (info: IdPServerInfo, context: OIDCCallbackContext) => Promise; + +/** @public */ +export declare type OneOrMore = T | ReadonlyArray; + +/** @public */ +export declare type OnlyFieldsOfType = IsAny, AcceptedFields & NotAcceptedFields & Record>; + +/* Excluded from this release type: OpCompressedRequest */ + +/** @public */ +export declare interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrite?: boolean; + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; + /* Excluded from this release type: bypassPinningCheck */ + omitReadPreference?: boolean; +} + +/* Excluded from this release type: OperationParent */ + +/** + * Represents a specific point in time on a server. Can be retrieved by using `db.command()` + * @public + * @see https://www.mongodb.com/docs/manual/reference/method/db.runCommand/#response + */ +export declare type OperationTime = Timestamp; + +/* Excluded from this release type: OpMsgOptions */ + +/* Excluded from this release type: OpMsgRequest */ + +/* Excluded from this release type: OpMsgResponse */ + +/* Excluded from this release type: OpQueryOptions */ + +/* Excluded from this release type: OpQueryRequest */ + +/* Excluded from this release type: OpQueryResponse */ + +/* Excluded from this release type: OpResponseOptions */ + +/** + * Add an optional _id field to an object shaped type + * @public + */ +export declare type OptionalId = EnhancedOmit & { + _id?: InferIdType; +}; + +/** + * Adds an optional _id field to an object shaped type, unless the _id field is required on that type. + * In the case _id is required, this method continues to require_id. + * + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export declare type OptionalUnlessRequiredId = TSchema extends { + _id: any; +} ? TSchema : OptionalId; + +/** @public */ +export declare class OrderedBulkOperation extends BulkOperationBase { + /* Excluded from this release type: __constructor */ + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface PkFactory { + createPk(): any; +} + +/* Excluded from this release type: PoolState */ + +/** @public */ +export declare const ProfilingLevel: Readonly<{ + readonly off: "off"; + readonly slowOnly: "slow_only"; + readonly all: "all"; +}>; + +/** @public */ +export declare type ProfilingLevel = (typeof ProfilingLevel)[keyof typeof ProfilingLevel]; + +/** @public */ +export declare type ProfilingLevelOptions = CommandOperationOptions; + +/** @public */ +export declare type PropertyType = string extends Property ? unknown : Property extends keyof Type ? Type[Property] : Property extends `${number}` ? Type extends ReadonlyArray ? ArrayType : unknown : Property extends `${infer Key}.${infer Rest}` ? Key extends `${number}` ? Type extends ReadonlyArray ? PropertyType : unknown : Key extends keyof Type ? Type[Key] extends Map ? MapType : PropertyType : unknown : unknown; + +/** @public */ +export declare interface ProxyOptions { + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; +} + +/** @public */ +export declare type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; + +/** @public */ +export declare type PullOperator = ({ + readonly [key in KeysOfAType>]?: Partial> | FilterOperations>; +} & NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; + +/** @public */ +export declare type PushOperator = ({ + readonly [key in KeysOfAType>]?: Flatten | ArrayOperator>>; +} & NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; + +/** + * @public + * RangeOptions specifies index options for a Queryable Encryption field supporting "rangePreview" queries. + * min, max, sparsity, and range must match the values set in the encryptedFields of the destination collection. + * For double and decimal128, min/max/precision must all be set, or all be unset. + */ +export declare interface RangeOptions { + min?: any; + max?: any; + sparsity: Long; + precision?: number; +} + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html + */ +export declare class ReadConcern { + level: ReadConcernLevel | string; + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel); + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined; + static get MAJORITY(): 'majority'; + static get AVAILABLE(): 'available'; + static get LINEARIZABLE(): 'linearizable'; + static get SNAPSHOT(): 'snapshot'; + toJSON(): Document; +} + +/** @public */ +export declare const ReadConcernLevel: Readonly<{ + readonly local: "local"; + readonly majority: "majority"; + readonly linearizable: "linearizable"; + readonly available: "available"; + readonly snapshot: "snapshot"; +}>; + +/** @public */ +export declare type ReadConcernLevel = (typeof ReadConcernLevel)[keyof typeof ReadConcernLevel]; + +/** @public */ +export declare type ReadConcernLike = ReadConcern | { + level: ReadConcernLevel; +} | ReadConcernLevel; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://www.mongodb.com/docs/manual/core/read-preference/ + */ +export declare class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + static PRIMARY: "primary"; + static PRIMARY_PREFERRED: "primaryPreferred"; + static SECONDARY: "secondary"; + static SECONDARY_PREFERRED: "secondaryPreferred"; + static NEAREST: "nearest"; + static primary: ReadPreference; + static primaryPreferred: ReadPreference; + static secondary: ReadPreference; + static secondaryPreferred: ReadPreference; + static nearest: ReadPreference; + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions); + get preference(): ReadPreferenceMode; + static fromString(mode: string): ReadPreference; + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined; + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean; + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean; + /** + * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire + * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query + */ + secondaryOk(): boolean; + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean; + /** Return JSON representation */ + toJSON(): Document; +} + +/** @public */ +export declare interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} + +/** @public */ +export declare type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; + +/** @public */ +export declare interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: ReadPreferenceLike | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} + +/** @public */ +export declare const ReadPreferenceMode: Readonly<{ + readonly primary: "primary"; + readonly primaryPreferred: "primaryPreferred"; + readonly secondary: "secondary"; + readonly secondaryPreferred: "secondaryPreferred"; + readonly nearest: "nearest"; +}>; + +/** @public */ +export declare type ReadPreferenceMode = (typeof ReadPreferenceMode)[keyof typeof ReadPreferenceMode]; + +/** @public */ +export declare interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} + +/** @public */ +export declare type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; + +/** @public */ +export declare type RemoveUserOptions = CommandOperationOptions; + +/** @public */ +export declare interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} + +/** @public */ +export declare interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: WithoutId; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * @public + * @deprecated Please use the ChangeStreamCursorOptions type instead. + */ +export declare interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; + resumeAfter?: ResumeToken; + startAfter?: ResumeToken; + fullDocument?: string; +} + +/** + * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server. + * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume + * @public + */ +export declare type ResumeToken = unknown; + +/** @public */ +export declare const ReturnDocument: Readonly<{ + readonly BEFORE: "before"; + readonly AFTER: "after"; +}>; + +/** @public */ +export declare type ReturnDocument = (typeof ReturnDocument)[keyof typeof ReturnDocument]; + +/** @public */ +export declare interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} + +/* Excluded from this release type: RTTPinger */ + +/* Excluded from this release type: RTTPingerOptions */ + +/** @public */ +export declare class RunCommandCursor extends AbstractCursor { + readonly command: Readonly>; + readonly getMoreOptions: { + comment?: any; + maxAwaitTimeMS?: number; + batchSize?: number; + }; + /** + * Controls the `getMore.comment` field + * @param comment - any BSON value + */ + setComment(comment: any): this; + /** + * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await + * @param maxTimeMS - the number of milliseconds to wait for new data + */ + setMaxTimeMS(maxTimeMS: number): this; + /** + * Controls the `getMore.batchSize` field + * @param maxTimeMS - the number documents to return in the `nextBatch` + */ + setBatchSize(batchSize: number): this; + /** Unsupported for RunCommandCursor */ + clone(): never; + /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */ + withReadConcern(_: ReadConcernLike): never; + /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */ + addCursorFlag(_: string, __: boolean): never; + /** Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document */ + maxTimeMS(_: number): never; + /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */ + batchSize(_: number): never; + /* Excluded from this release type: db */ + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: getMore */ +} + +/** @public */ +export declare type RunCommandOptions = { + /** Specify ClientSession for this command */ + session?: ClientSession; + /** The read preference */ + readPreference?: ReadPreferenceLike; +} & BSONSerializeOptions; + +/** @public */ +export declare type RunCursorCommandOptions = { + readPreference?: ReadPreferenceLike; + session?: ClientSession; +} & BSONSerializeOptions; + +/** @public */ +export declare type SchemaMember = { + [P in keyof T]?: V; +} | { + [key: string]: V; +}; + +/** + * @public + */ +export declare interface SearchIndexDescription { + /** The name of the index. */ + name?: string; + /** The index definition. */ + definition: Document; +} + +/** @public */ +export declare interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; + operationName: string; + previousServer?: ServerDescription; +} + +export { serialize } + +/* Excluded from this release type: Server */ + +/* Excluded from this release type: SERVER_CLOSED */ + +/* Excluded from this release type: SERVER_DESCRIPTION_CHANGED */ + +/* Excluded from this release type: SERVER_HEARTBEAT_FAILED */ + +/* Excluded from this release type: SERVER_HEARTBEAT_STARTED */ + +/* Excluded from this release type: SERVER_HEARTBEAT_SUCCEEDED */ + +/* Excluded from this release type: SERVER_OPENING */ + +/* Excluded from this release type: SERVER_SELECTION_FAILED */ + +/* Excluded from this release type: SERVER_SELECTION_STARTED */ + +/* Excluded from this release type: SERVER_SELECTION_SUCCEEDED */ + +/** @public */ +export declare interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} + +/** @public */ +export declare const ServerApiVersion: Readonly<{ + readonly v1: "1"; +}>; + +/** @public */ +export declare type ServerApiVersion = (typeof ServerApiVersion)[keyof typeof ServerApiVersion]; + +/** @public */ +export declare class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + constructor(hello: Document); + get hasAggregationCursor(): boolean; + get hasWriteCommands(): boolean; + get hasTextSearch(): boolean; + get hasAuthCommands(): boolean; + get hasListCollectionsCommand(): boolean; + get hasListIndexesCommand(): boolean; + get supportsSnapshotReads(): boolean; + get commandsTakeWriteConcern(): boolean; + get commandsTakeCollation(): boolean; +} + +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export declare class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * The client's view of a single server, based on the most recent hello outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export declare class ServerDescription { + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error: MongoError | null; + topologyVersion: TopologyVersion | null; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me: string | null; + primary: string | null; + setName: string | null; + setVersion: number | null; + electionId: ObjectId | null; + logicalSessionTimeoutMinutes: number | null; + $clusterTime?: ClusterTime; + /* Excluded from this release type: __constructor */ + get hostAddress(): HostAddress; + get allHosts(): string[]; + /** Is this server available for reads*/ + get isReadable(): boolean; + /** Is this server data bearing */ + get isDataBearing(): boolean; + /** Is this server available for writes */ + get isWritable(): boolean; + get host(): string; + get port(): number; + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other?: ServerDescription | null): boolean; +} + +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export declare class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; + name: "serverDescriptionChanged"; + /* Excluded from this release type: __constructor */ +} + +/* Excluded from this release type: ServerDescriptionOptions */ + +/** @public */ +export declare type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /* Excluded from this release type: connect */ + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & EventEmitterWithState; + +/** + * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export declare class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; + /** Is true when using the streaming protocol */ + awaited: boolean; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when the server monitor’s hello command is started - immediately before + * the hello command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export declare class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; + /** Is true when using the streaming protocol */ + awaited: boolean; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * Emitted when the server monitor’s hello succeeds. + * @public + * @category Event + */ +export declare class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; + /** Is true when using the streaming protocol */ + awaited: boolean; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare const ServerMonitoringMode: Readonly<{ + readonly auto: "auto"; + readonly poll: "poll"; + readonly stream: "stream"; +}>; + +/** @public */ +export declare type ServerMonitoringMode = (typeof ServerMonitoringMode)[keyof typeof ServerMonitoringMode]; + +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export declare class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/* Excluded from this release type: ServerOptions */ + +/* Excluded from this release type: ServerPrivate */ + +/* Excluded from this release type: ServerSelectionCallback */ + +/* Excluded from this release type: ServerSelectionEvent */ + +/* Excluded from this release type: ServerSelectionFailedEvent */ + +/* Excluded from this release type: ServerSelectionRequest */ + +/* Excluded from this release type: ServerSelectionStartedEvent */ + +/* Excluded from this release type: ServerSelectionSucceededEvent */ + +/* Excluded from this release type: ServerSelector */ + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export declare class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + /* Excluded from this release type: __constructor */ + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean; + /* Excluded from this release type: clone */ +} + +/** @public */ +export declare type ServerSessionId = { + id: Binary; +}; + +/* Excluded from this release type: ServerSessionPool */ + +/** + * An enumeration of server types we know about + * @public + */ +export declare const ServerType: Readonly<{ + readonly Standalone: "Standalone"; + readonly Mongos: "Mongos"; + readonly PossiblePrimary: "PossiblePrimary"; + readonly RSPrimary: "RSPrimary"; + readonly RSSecondary: "RSSecondary"; + readonly RSArbiter: "RSArbiter"; + readonly RSOther: "RSOther"; + readonly RSGhost: "RSGhost"; + readonly Unknown: "Unknown"; + readonly LoadBalancer: "LoadBalancer"; +}>; + +/** @public */ +export declare type ServerType = (typeof ServerType)[keyof typeof ServerType]; + +/** @public */ +export declare type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: OptionalId> | AddToSetOperators>>>; +} & IsAny | undefined>>) & { + readonly [key: string]: AddToSetOperators | any; +}; + +/** @public */ +export declare type SetProfilingLevelOptions = CommandOperationOptions; + +/* Excluded from this release type: SeverityLevel */ + +/** @public */ +export declare type Sort = string | Exclude | string[] | { + [key: string]: SortDirection; +} | Map | [string, SortDirection][] | [string, SortDirection]; + +/** @public */ +export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | { + $meta: string; +}; + +/* Excluded from this release type: SortDirectionForCmd */ + +/* Excluded from this release type: SortForCmd */ + +/* Excluded from this release type: SrvPoller */ + +/* Excluded from this release type: SrvPollerEvents */ + +/* Excluded from this release type: SrvPollerOptions */ + +/* Excluded from this release type: SrvPollingEvent */ + +/* Excluded from this release type: StateMachineExecutable */ + +/** @public */ +export declare type Stream = Socket | TLSSocket; + +/** @public */ +export declare class StreamDescription { + address: string; + type: ServerType; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + __nodejs_mock_server__?: boolean; + zlibCompressionLevel?: number; + serverConnectionId: bigint | null; + hello: Document | null; + constructor(address: string, options?: StreamDescriptionOptions); + receiveResponse(response: Document | null): void; + parseServerConnectionID(serverConnectionId: number | Double | bigint | Long): bigint; +} + +/** @public */ +export declare interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} + +/** + * @public + * @experimental + */ +export declare type StrictFilter = Partial | ({ + [Property in Join, []>, '.'>]?: Condition, Property>>; +} & RootFilterOperators>); + +/** + * @public + * @experimental + */ +export declare type StrictMatchKeysAndValues = Readonly<{ + [Property in Join, '.'>]?: PropertyType; +} & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement>; +} & { + [Property in `${NestedPathsOfType[]>}.$${`[${string}]` | ''}.${string}`]?: any; +} & Document>; + +/** + * @public + * @experimental + */ +export declare type StrictUpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: StrictMatchKeysAndValues; + $max?: StrictMatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: StrictMatchKeysAndValues; + $setOnInsert?: StrictMatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; + +/** @public */ +export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & SupportedTLSSocketOptions & SupportedSocketOptions; + +/** @public */ +export declare type SupportedSocketOptions = Pick; + +/** @public */ +export declare type SupportedTLSConnectionOptions = Pick>; + +/** @public */ +export declare type SupportedTLSSocketOptions = Pick>; + +/** @public */ +export declare type TagSet = { + [key: string]: string; +}; + +/* Excluded from this release type: TimeoutController */ + +/* Excluded from this release type: TimerQueue */ + +/** @public + * Configuration options for timeseries collections + * @see https://www.mongodb.com/docs/manual/core/timeseries-collections/ + */ +export declare interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: 'seconds' | 'minutes' | 'hours' | string; + bucketMaxSpanSeconds?: number; + bucketRoundingSeconds?: number; +} + +export { Timestamp } + +/* Excluded from this release type: Topology */ + +/* Excluded from this release type: TOPOLOGY_CLOSED */ + +/* Excluded from this release type: TOPOLOGY_DESCRIPTION_CHANGED */ + +/* Excluded from this release type: TOPOLOGY_OPENING */ + +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export declare class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** + * Representation of a deployment of servers + * @public + */ +export declare class TopologyDescription { + type: TopologyType; + setName: string | null; + maxSetVersion: number | null; + maxElectionId: ObjectId | null; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes: number | null; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion: number; + /** + * Create a TopologyDescription + */ + constructor(topologyType: TopologyType, serverDescriptions?: Map | null, setName?: string | null, maxSetVersion?: number | null, maxElectionId?: ObjectId | null, commonWireVersion?: number | null, options?: TopologyDescriptionOptions | null); + /* Excluded from this release type: updateFromSrvPollingEvent */ + /* Excluded from this release type: update */ + get error(): MongoServerError | null; + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers(): boolean; + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers(): boolean; + /* Excluded from this release type: hasServer */ +} + +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export declare class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/** @public */ +export declare interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} + +/** @public */ +export declare type TopologyEvents = { + /* Excluded from this release type: connect */ + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /* Excluded from this release type: open */ + close(): void; + timeout(): void; +} & Omit & ConnectionPoolEvents & ConnectionEvents & EventEmitterWithState; + +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export declare class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /* Excluded from this release type: name */ + /* Excluded from this release type: __constructor */ +} + +/* Excluded from this release type: TopologyOptions */ + +/* Excluded from this release type: TopologyPrivate */ + +/** + * An enumeration of topology types we know about + * @public + */ +export declare const TopologyType: Readonly<{ + readonly Single: "Single"; + readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary"; + readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary"; + readonly Sharded: "Sharded"; + readonly Unknown: "Unknown"; + readonly LoadBalanced: "LoadBalanced"; +}>; + +/** @public */ +export declare type TopologyType = (typeof TopologyType)[keyof typeof TopologyType]; + +/** @public */ +export declare interface TopologyVersion { + processId: ObjectId; + counter: Long; +} + +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export declare class Transaction { + /* Excluded from this release type: state */ + options: TransactionOptions; + /* Excluded from this release type: _pinnedServer */ + /* Excluded from this release type: _recoveryToken */ + /* Excluded from this release type: __constructor */ + /* Excluded from this release type: server */ + get recoveryToken(): Document | undefined; + get isPinned(): boolean; + /** @returns Whether the transaction has started */ + get isStarting(): boolean; + /** + * @returns Whether this session is presently in a transaction + */ + get isActive(): boolean; + get isCommitted(): boolean; + /* Excluded from this release type: transition */ + /* Excluded from this release type: pinServer */ + /* Excluded from this release type: unpinServer */ +} + +/** + * Configuration options for a transaction. + * @public + */ +export declare interface TransactionOptions extends CommandOperationOptions { + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcernLike; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreferenceLike; + /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */ + maxCommitTimeMS?: number; +} + +/* Excluded from this release type: TxnState */ + +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + addListener(event: string | symbol, listener: GenericListener): this; + on(event: EventKey, listener: Events[EventKey]): this; + on(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + on(event: string | symbol, listener: GenericListener): this; + once(event: EventKey, listener: Events[EventKey]): this; + once(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + once(event: string | symbol, listener: GenericListener): this; + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + removeListener(event: string | symbol, listener: GenericListener): this; + off(event: EventKey, listener: Events[EventKey]): this; + off(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + off(event: string | symbol, listener: GenericListener): this; + removeAllListeners(event?: EventKey | CommonEvents | symbol | string): this; + listeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + rawListeners(event: EventKey | CommonEvents | symbol | string): Events[EventKey][]; + emit(event: EventKey | symbol, ...args: Parameters): boolean; + listenerCount(type: EventKey | CommonEvents | symbol | string): number; + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependListener(event: string | symbol, listener: GenericListener): this; + prependOnceListener(event: EventKey, listener: Events[EventKey]): this; + prependOnceListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} + +/** + * Typescript type safe event emitter + * @public + */ +export declare class TypedEventEmitter extends EventEmitter { + /* Excluded from this release type: mongoLogger */ + /* Excluded from this release type: component */ + /* Excluded from this release type: emitAndLog */ + /* Excluded from this release type: emitAndLogHeartbeat */ + /* Excluded from this release type: emitAndLogCommand */ +} + +/** @public */ +export declare class UnorderedBulkOperation extends BulkOperationBase { + /* Excluded from this release type: __constructor */ + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean; + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields?: Partial; + /** + * An array of field names that were removed from the document. + */ + removedFields?: string[]; + /** + * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages: + * - $addFields + * - $set + * - $replaceRoot + * - $replaceWith + */ + truncatedArrays?: Array<{ + /** The name of the truncated field. */ + field: string; + /** The number of elements in the truncated array. */ + newSize: number; + }>; + /** + * A document containing additional information about any ambiguous update paths from the update event. The document + * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example, + * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like + * the following: + * + * ``` + * { + * 'a.0': ['a', '0'] + * } + * ``` + * + * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents` + * is enabled for the change stream. + * @sinceServerVersion 6.1.0 + */ + disambiguatedPaths?: Document; +} + +/** @public */ +export declare type UpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; + +/** @public */ +export declare interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** + * The modifications to apply. The value can be either: + * UpdateFilter - A document that contains update operator expressions, + * Document[] - an aggregation pipeline. + */ + update: UpdateFilter | Document[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** + * The modifications to apply. The value can be either: + * UpdateFilter - A document that contains update operator expressions, + * Document[] - an aggregation pipeline. + */ + update: UpdateFilter | Document[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export declare interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: Hint; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * @public + * `TSchema` is the schema of the collection + */ +export declare interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: InferIdType | null; +} + +/** @public */ +export declare interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +export { UUID } + +/** @public */ +export declare interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} + +/** @public */ +export declare type W = number | 'majority'; + +/* Excluded from this release type: WAITING_FOR_SUITABLE_SERVER */ + +/* Excluded from this release type: WaitingForSuitableServerEvent */ + +/* Excluded from this release type: WaitQueueMember */ + +/* Excluded from this release type: WithConnectionCallback */ + +/** Add an _id field to an object shaped type @public */ +export declare type WithId = EnhancedOmit & { + _id: InferIdType; +}; + +/** Remove the _id field from an object shaped type @public */ +export declare type WithoutId = Omit; + +/** @public */ +export declare type WithSessionCallback = (session: ClientSession) => Promise; + +/** @public */ +export declare type WithTransactionCallback = (session: ClientSession) => Promise; + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://www.mongodb.com/docs/manual/reference/write-concern/ + */ +export declare class WriteConcern { + /** Request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + readonly w?: W; + /** Request acknowledgment that the write operation has been written to the on-disk journal */ + readonly journal?: boolean; + /** Specify a time limit to prevent write operations from blocking indefinitely */ + readonly wtimeoutMS?: number; + /** + * Specify a time limit to prevent write operations from blocking indefinitely. + * @deprecated Will be removed in the next major version. Please use wtimeoutMS. + */ + wtimeout?: number; + /** + * Request acknowledgment that the write operation has been written to the on-disk journal. + * @deprecated Will be removed in the next major version. Please use journal. + */ + j?: boolean; + /** + * Equivalent to the j option. + * @deprecated Will be removed in the next major version. Please use journal. + */ + fsync?: boolean | 1; + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely + * @param journal - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version. + */ + constructor(w?: W, wtimeoutMS?: number, journal?: boolean, fsync?: boolean | 1); + /** + * Apply a write concern to a command document. Will modify and return the command. + */ + static apply(command: Document, writeConcern: WriteConcern): Document; + /** Construct a WriteConcern given an options object. */ + static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined; +} + +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export declare class WriteConcernError { + /* Excluded from this release type: [kServerError] */ + constructor(error: WriteConcernErrorData); + /** Write concern error code. */ + get code(): number | undefined; + /** Write concern error message. */ + get errmsg(): string | undefined; + /** Write concern error info. */ + get errInfo(): Document | undefined; + toJSON(): WriteConcernErrorData; + toString(): string; +} + +/** @public */ +export declare interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} + +/** @public */ +export declare interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} + +/** @public */ +export declare interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + /** + * The journal write concern. + * @deprecated Will be removed in the next major version. Please use the journal option. + */ + j?: boolean; + /** + * The write concern timeout. + * @deprecated Will be removed in the next major version. Please use the wtimeoutMS option. + */ + wtimeout?: number; + /** + * The file sync write concern. + * @deprecated Will be removed in the next major version. Please use the journal option. + */ + fsync?: boolean | 1; +} + +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export declare class WriteError { + err: BulkWriteOperationError; + constructor(err: BulkWriteOperationError); + /** WriteError code. */ + get code(): number; + /** WriteError original bulk operation index. */ + get index(): number; + /** WriteError message. */ + get errmsg(): string | undefined; + /** WriteError details. */ + get errInfo(): Document | undefined; + /** Returns the underlying operation that caused the error */ + getOperation(): Document; + toJSON(): { + code: number; + index: number; + errmsg?: string; + op: Document; + }; + toString(): string; +} + +/* Excluded from this release type: WriteProtocolMessageType */ + +export { } diff --git a/nodejs/node_modules/mongodb/package.json b/nodejs/node_modules/mongodb/package.json new file mode 100644 index 00000000..b7f04b8e --- /dev/null +++ b/nodejs/node_modules/mongodb/package.json @@ -0,0 +1,175 @@ +{ + "name": "mongodb", + "version": "6.5.0", + "description": "The official MongoDB driver for Node.js", + "main": "lib/index.js", + "files": [ + "lib", + "src", + "etc/prepare.js", + "mongodb.d.ts", + "tsconfig.json" + ], + "types": "mongodb.d.ts", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "official" + ], + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.4.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "snappy": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "socks": { + "optional": true + } + }, + "devDependencies": { + "@aws-sdk/credential-providers": "^3.515.0", + "@iarna/toml": "^2.2.5", + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.40.6", + "@microsoft/tsdoc-config": "^0.16.2", + "@mongodb-js/zstd": "^1.2.0", + "@octokit/core": "^5.1.0", + "@types/chai": "^4.3.11", + "@types/chai-subset": "^1.3.5", + "@types/express": "^4.17.21", + "@types/kerberos": "^1.1.5", + "@types/mocha": "^10.0.6", + "@types/node": "^20.11.20", + "@types/saslprep": "^1.0.3", + "@types/semver": "^7.5.7", + "@types/sinon": "^10.0.20", + "@types/sinon-chai": "^3.2.12", + "@types/whatwg-url": "^11.0.4", + "@typescript-eslint/eslint-plugin": "^5.62.0", + "@typescript-eslint/parser": "^5.62.0", + "chai": "^4.4.1", + "chai-subset": "^1.6.0", + "chalk": "^4.1.2", + "eslint": "^8.56.0", + "eslint-config-prettier": "^8.10.0", + "eslint-plugin-import": "^2.29.1", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-simple-import-sort": "^10.0.0", + "eslint-plugin-tsdoc": "^0.2.17", + "eslint-plugin-unused-imports": "^2.0.0", + "express": "^4.18.2", + "gcp-metadata": "^5.3.0", + "js-yaml": "^4.1.0", + "mocha": "^10.3.0", + "mocha-sinon": "^2.1.2", + "mongodb-client-encryption": "^6.0.0", + "mongodb-legacy": "^6.0.1", + "nyc": "^15.1.0", + "prettier": "^2.8.8", + "semver": "^7.6.0", + "sinon": "^15.2.0", + "sinon-chai": "^3.7.0", + "snappy": "^7.2.2", + "socks": "^2.8.1", + "source-map-support": "^0.5.21", + "ts-node": "^10.9.2", + "tsd": "^0.30.6", + "typescript": "5.0", + "typescript-cached-transpile": "^0.0.6", + "v8-heapsnapshot": "^1.3.1", + "yargs": "^17.7.2" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + }, + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "scripts": { + "build:evergreen": "node .evergreen/generate_evergreen_tasks.js", + "build:ts": "node ./node_modules/typescript/bin/tsc", + "build:dts": "npm run build:ts && api-extractor run && node etc/clean_definition_files.cjs && eslint mongodb.d.ts --fix", + "build:docs": "./etc/docs/build.ts", + "build:typedoc": "typedoc", + "build:nightly": "node ./.github/scripts/nightly.mjs", + "check:bench": "node test/benchmarks/driverBench", + "check:coverage": "nyc npm run test:all", + "check:integration-coverage": "nyc npm run check:test", + "check:lambda": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/handler.test.js", + "check:lambda:aws": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/aws_handler.test.js", + "check:lint": "npm run build:dts && npm run check:dts && npm run check:eslint && npm run check:tsd", + "check:eslint": "eslint -v && eslint --max-warnings=0 --ext '.js,.ts' src test", + "check:tsd": "tsd --version && tsd", + "check:dependencies": "mocha test/action/dependency.test.ts", + "check:dts": "node ./node_modules/typescript/bin/tsc --noEmit mongodb.d.ts && tsd", + "check:search-indexes": "nyc mocha --config test/mocha_mongodb.json test/manual/search-index-management.prose.test.ts", + "check:test": "mocha --config test/mocha_mongodb.json test/integration", + "check:unit": "mocha test/unit", + "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit", + "check:atlas": "mocha --config test/manual/mocharc.json test/manual/atlas_connectivity.test.js", + "check:drivers-atlas-testing": "mocha --config test/mocha_mongodb.json test/atlas/drivers_atlas_testing.test.ts", + "check:adl": "mocha --config test/mocha_mongodb.json test/manual/atlas-data-lake-testing", + "check:aws": "nyc mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_aws.test.ts", + "check:oidc": "mocha --config test/mocha_mongodb.json test/manual/mongodb_oidc.prose.test.ts", + "check:oidc-azure": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc_azure.prose.test.ts", + "check:ocsp": "mocha --config test/manual/mocharc.json test/manual/ocsp_support.test.js", + "check:kerberos": "nyc mocha --config test/manual/mocharc.json test/manual/kerberos.test.ts", + "check:tls": "mocha --config test/manual/mocharc.json test/manual/tls_support.test.ts", + "check:ldap": "nyc mocha --config test/manual/mocharc.json test/manual/ldap.test.js", + "check:socks5": "mocha --config test/manual/mocharc.json test/manual/socks5.test.ts", + "check:csfle": "mocha --config test/mocha_mongodb.json test/integration/client-side-encryption", + "check:snappy": "mocha test/unit/assorted/snappy.test.js", + "fix:eslint": "npm run check:eslint -- --fix", + "prepare": "node etc/prepare.js", + "preview:docs": "ts-node etc/docs/preview.ts", + "test": "npm run check:lint && npm run test:all", + "test:all": "npm run check:unit && npm run check:test", + "update:docs": "npm run build:docs -- --yes" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + } +} diff --git a/nodejs/node_modules/mongodb/src/admin.ts b/nodejs/node_modules/mongodb/src/admin.ts new file mode 100644 index 00000000..28efb5cd --- /dev/null +++ b/nodejs/node_modules/mongodb/src/admin.ts @@ -0,0 +1,168 @@ +import { type Document, resolveBSONOptions } from './bson'; +import type { Db } from './db'; +import type { CommandOperationOptions } from './operations/command'; +import { executeOperation } from './operations/execute_operation'; +import { + ListDatabasesOperation, + type ListDatabasesOptions, + type ListDatabasesResult +} from './operations/list_databases'; +import { RemoveUserOperation, type RemoveUserOptions } from './operations/remove_user'; +import { RunAdminCommandOperation, type RunCommandOptions } from './operations/run_command'; +import { + ValidateCollectionOperation, + type ValidateCollectionOptions +} from './operations/validate_collection'; + +/** @internal */ +export interface AdminPrivate { + db: Db; +} + +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +export class Admin { + /** @internal */ + s: AdminPrivate; + + /** + * Create a new Admin instance + * @internal + */ + constructor(db: Db) { + this.s = { db }; + } + + /** + * Execute a command + * + * The driver will ensure the following fields are attached to the command sent to the server: + * - `lsid` - sourced from an implicit session or options.session + * - `$readPreference` - defaults to primary or can be configured by options.readPreference + * - `$db` - sourced from the name of this database + * + * If the client has a serverApi setting: + * - `apiVersion` + * - `apiStrict` + * - `apiDeprecationErrors` + * + * When in a transaction: + * - `readConcern` - sourced from readConcern set on the TransactionOptions + * - `writeConcern` - sourced from writeConcern set on the TransactionOptions + * + * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. + * + * @param command - The command to execute + * @param options - Optional settings for the command + */ + async command(command: Document, options?: RunCommandOptions): Promise { + return executeOperation( + this.s.db.client, + new RunAdminCommandOperation(command, { + ...resolveBSONOptions(options), + session: options?.session, + readPreference: options?.readPreference + }) + ); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async buildInfo(options?: CommandOperationOptions): Promise { + return this.command({ buildinfo: 1 }, options); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async serverInfo(options?: CommandOperationOptions): Promise { + return this.command({ buildinfo: 1 }, options); + } + + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + async serverStatus(options?: CommandOperationOptions): Promise { + return this.command({ serverStatus: 1 }, options); + } + + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + async ping(options?: CommandOperationOptions): Promise { + return this.command({ ping: 1 }, options); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username: string, options?: RemoveUserOptions): Promise { + return executeOperation( + this.s.db.client, + new RemoveUserOperation(this.s.db, username, { dbName: 'admin', ...options }) + ); + } + + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + async validateCollection( + collectionName: string, + options: ValidateCollectionOptions = {} + ): Promise { + return executeOperation( + this.s.db.client, + new ValidateCollectionOperation(this, collectionName, options) + ); + } + + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + async listDatabases(options?: ListDatabasesOptions): Promise { + return executeOperation(this.s.db.client, new ListDatabasesOperation(this.s.db, options)); + } + + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + async replSetGetStatus(options?: CommandOperationOptions): Promise { + return this.command({ replSetGetStatus: 1 }, options); + } +} diff --git a/nodejs/node_modules/mongodb/src/bson.ts b/nodejs/node_modules/mongodb/src/bson.ts new file mode 100644 index 00000000..2c0b43df --- /dev/null +++ b/nodejs/node_modules/mongodb/src/bson.ts @@ -0,0 +1,120 @@ +import type { DeserializeOptions, SerializeOptions } from 'bson'; + +export { + Binary, + BSON, + BSONRegExp, + BSONSymbol, + BSONType, + calculateObjectSize, + Code, + DBRef, + Decimal128, + deserialize, + Document, + Double, + EJSON, + EJSONOptions, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + serialize, + Timestamp, + UUID +} from 'bson'; + +/** + * BSON Serialization options. + * @public + */ +export interface BSONSerializeOptions + extends Omit, + Omit< + DeserializeOptions, + | 'evalFunctions' + | 'cacheFunctions' + | 'cacheFunctionsCrc32' + | 'allowObjectSmallerThanBufferSize' + | 'index' + | 'validation' + > { + /** + * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html) + * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize). + * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe) + * for more detail about what "unsafe" refers to in this context. + * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate + * your own buffer and clone the contents: + * + * @example + * ```ts + * const raw = await collection.findOne({}, { raw: true }); + * const myBuffer = Buffer.alloc(raw.byteLength); + * myBuffer.set(raw, 0); + * // Only save and use `myBuffer` beyond this point + * ``` + * + * @remarks + * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)). + * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work. + */ + raw?: boolean; + + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export function pluckBSONSerializeOptions(options: BSONSerializeOptions): BSONSerializeOptions { + const { + fieldsAsRaw, + useBigInt64, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + } = options; + return { + fieldsAsRaw, + useBigInt64, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + }; +} + +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +export function resolveBSONOptions( + options?: BSONSerializeOptions, + parent?: { bsonOptions?: BSONSerializeOptions } +): BSONSerializeOptions { + const parentOptions = parent?.bsonOptions; + return { + raw: options?.raw ?? parentOptions?.raw ?? false, + useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? false, + promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, + promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, + promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, + ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, + bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, + serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, + fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {}, + enableUtf8Validation: + options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true + }; +} diff --git a/nodejs/node_modules/mongodb/src/bulk/common.ts b/nodejs/node_modules/mongodb/src/bulk/common.ts new file mode 100644 index 00000000..5de00544 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/bulk/common.ts @@ -0,0 +1,1300 @@ +import { promisify } from 'util'; + +import { type BSONSerializeOptions, type Document, resolveBSONOptions } from '../bson'; +import type { Collection } from '../collection'; +import { + type AnyError, + MongoBatchReExecutionError, + MONGODB_ERROR_CODES, + MongoInvalidArgumentError, + MongoServerError, + MongoWriteConcernError +} from '../error'; +import type { Filter, OneOrMore, OptionalId, UpdateFilter, WithoutId } from '../mongo_types'; +import type { CollationOptions, CommandOperationOptions } from '../operations/command'; +import { maybeAddIdToDocuments } from '../operations/common_functions'; +import { DeleteOperation, type DeleteStatement, makeDeleteStatement } from '../operations/delete'; +import { executeOperation } from '../operations/execute_operation'; +import { InsertOperation } from '../operations/insert'; +import { AbstractOperation, type Hint } from '../operations/operation'; +import { makeUpdateStatement, UpdateOperation, type UpdateStatement } from '../operations/update'; +import type { Server } from '../sdam/server'; +import type { Topology } from '../sdam/topology'; +import type { ClientSession } from '../sessions'; +import { + applyRetryableWrites, + type Callback, + getTopology, + hasAtomicOperators, + type MongoDBNamespace, + resolveOptions +} from '../utils'; +import { WriteConcern } from '../write_concern'; + +/** @internal */ +const kServerError = Symbol('serverError'); + +/** @public */ +export const BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +} as const); + +/** @public */ +export type BatchType = (typeof BatchType)[keyof typeof BatchType]; + +/** @public */ +export interface InsertOneModel { + /** The document to insert. */ + document: OptionalId; +} + +/** @public */ +export interface DeleteOneModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export interface DeleteManyModel { + /** The filter to limit the deleted documents. */ + filter: Filter; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; +} + +/** @public */ +export interface ReplaceOneModel { + /** The filter to limit the replaced document. */ + filter: Filter; + /** The document with which to replace the matched document. */ + replacement: WithoutId; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export interface UpdateOneModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** + * The modifications to apply. The value can be either: + * UpdateFilter - A document that contains update operator expressions, + * Document[] - an aggregation pipeline. + */ + update: UpdateFilter | Document[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export interface UpdateManyModel { + /** The filter to limit the updated documents. */ + filter: Filter; + /** + * The modifications to apply. The value can be either: + * UpdateFilter - A document that contains update operator expressions, + * Document[] - an aggregation pipeline. + */ + update: UpdateFilter | Document[]; + /** A set of filters specifying to which array elements an update should apply. */ + arrayFilters?: Document[]; + /** Specifies a collation. */ + collation?: CollationOptions; + /** The index to use. If specified, then the query system will only consider plans using the hinted index. */ + hint?: Hint; + /** When true, creates a new document if no document matches the query. */ + upsert?: boolean; +} + +/** @public */ +export type AnyBulkWriteOperation = + | { insertOne: InsertOneModel } + | { replaceOne: ReplaceOneModel } + | { updateOne: UpdateOneModel } + | { updateMany: UpdateManyModel } + | { deleteOne: DeleteOneModel } + | { deleteMany: DeleteManyModel }; + +/** @internal */ +export interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: Document[]; +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +export class Batch { + originalZeroIndex: number; + currentIndex: number; + originalIndexes: number[]; + batchType: BatchType; + operations: T[]; + size: number; + sizeBytes: number; + + constructor(batchType: BatchType, originalZeroIndex: number) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * @public + * The result of a bulk write. + */ +export class BulkWriteResult { + private readonly result: BulkResult; + /** Number of documents inserted. */ + readonly insertedCount: number; + /** Number of documents matched for update. */ + readonly matchedCount: number; + /** Number of documents modified. */ + readonly modifiedCount: number; + /** Number of documents deleted. */ + readonly deletedCount: number; + /** Number of documents upserted. */ + readonly upsertedCount: number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { [key: number]: any }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { [key: number]: any }; + + private static generateIdMap(ids: Document[]): { [key: number]: any } { + const idMap: { [index: number]: any } = {}; + for (const doc of ids) { + idMap[doc.index] = doc._id; + } + return idMap; + } + + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult: BulkResult, isOrdered: boolean) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap( + this.getSuccessfullyInsertedIds(bulkResult, isOrdered) + ); + Object.defineProperty(this, 'result', { value: this.result, enumerable: false }); + } + + /** Evaluates to true if the bulk operation correctly executes */ + get ok(): number { + return this.result.ok; + } + + /** + * Returns document_ids that were actually inserted + * @internal + */ + private getSuccessfullyInsertedIds(bulkResult: BulkResult, isOrdered: boolean): Document[] { + if (bulkResult.writeErrors.length === 0) return bulkResult.insertedIds; + + if (isOrdered) { + return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index); + } + + return bulkResult.insertedIds.filter( + ({ index }) => !bulkResult.writeErrors.some(writeError => index === writeError.index) + ); + } + + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index: number): Document | undefined { + return this.result.upserted[index]; + } + + /** Returns raw internal result */ + getRawResponse(): Document { + return this.result; + } + + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors(): boolean { + return this.result.writeErrors.length > 0; + } + + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount(): number { + return this.result.writeErrors.length; + } + + /** Returns a specific write error object */ + getWriteErrorAt(index: number): WriteError | undefined { + return index < this.result.writeErrors.length ? this.result.writeErrors[index] : undefined; + } + + /** Retrieve all write errors */ + getWriteErrors(): WriteError[] { + return this.result.writeErrors; + } + + /** Retrieve the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined { + if (this.result.writeConcernErrors.length === 0) { + return; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg, code: MONGODB_ERROR_CODES.WriteConcernFailed }); + } + } + + toString(): string { + return `BulkWriteResult(${this.result})`; + } + + isOk(): boolean { + return this.result.ok === 1; + } +} + +/** @public */ +export interface WriteConcernErrorData { + code: number; + errmsg: string; + errInfo?: Document; +} + +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +export class WriteConcernError { + /** @internal */ + [kServerError]: WriteConcernErrorData; + + constructor(error: WriteConcernErrorData) { + this[kServerError] = error; + } + + /** Write concern error code. */ + get code(): number | undefined { + return this[kServerError].code; + } + + /** Write concern error message. */ + get errmsg(): string | undefined { + return this[kServerError].errmsg; + } + + /** Write concern error info. */ + get errInfo(): Document | undefined { + return this[kServerError].errInfo; + } + + toJSON(): WriteConcernErrorData { + return this[kServerError]; + } + + toString(): string { + return `WriteConcernError(${this.errmsg})`; + } +} + +/** @public */ +export interface BulkWriteOperationError { + index: number; + code: number; + errmsg: string; + errInfo: Document; + op: Document | UpdateStatement | DeleteStatement; +} + +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +export class WriteError { + err: BulkWriteOperationError; + + constructor(err: BulkWriteOperationError) { + this.err = err; + } + + /** WriteError code. */ + get code(): number { + return this.err.code; + } + + /** WriteError original bulk operation index. */ + get index(): number { + return this.err.index; + } + + /** WriteError message. */ + get errmsg(): string | undefined { + return this.err.errmsg; + } + + /** WriteError details. */ + get errInfo(): Document | undefined { + return this.err.errInfo; + } + + /** Returns the underlying operation that caused the error */ + getOperation(): Document { + return this.err.op; + } + + toJSON(): { code: number; index: number; errmsg?: string; op: Document } { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + toString(): string { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** Merges results into shared data structure */ +export function mergeBatchResults( + batch: Batch, + bulkResult: BulkResult, + err?: AnyError, + result?: Document +): void { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } + + if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = 0; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i].index], + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +function executeCommands( + bulkOperation: BulkOperationBase, + options: BulkWriteOptions, + callback: Callback +) { + if (bulkOperation.s.batches.length === 0) { + return callback( + undefined, + new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered) + ); + } + + const batch = bulkOperation.s.batches.shift() as Batch; + + function resultHandler(err?: AnyError, result?: Document) { + // Error is a driver related error not a bulk op error, return early + if (err && 'message' in err && !(err instanceof MongoWriteConcernError)) { + return callback( + new MongoBulkWriteError( + err, + new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered) + ) + ); + } + + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError( + batch, + bulkOperation.s.bulkResult, + bulkOperation.isOrdered, + err, + callback + ); + } + + // Merge the results together + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + const finalOptions = resolveOptions(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); + } + + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); + } + } + + try { + const operation = isInsertBatch(batch) + ? new InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions) + : isUpdateBatch(batch) + ? new UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions) + : isDeleteBatch(batch) + ? new DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions) + : null; + + if (operation != null) { + executeOperation(bulkOperation.s.collection.client, operation).then( + result => resultHandler(undefined, result), + error => resultHandler(error) + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} + +function handleMongoWriteConcernError( + batch: Batch, + bulkResult: BulkResult, + isOrdered: boolean, + err: MongoWriteConcernError, + callback: Callback +) { + mergeBatchResults(batch, bulkResult, undefined, err.result); + + callback( + new MongoBulkWriteError( + { + message: err.result?.writeConcernError.errmsg, + code: err.result?.writeConcernError.result + }, + new BulkWriteResult(bulkResult, isOrdered) + ) + ); +} + +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +export class MongoBulkWriteError extends MongoServerError { + result: BulkWriteResult; + writeErrors: OneOrMore = []; + err?: WriteConcernError; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor( + error: + | { message: string; code: number; writeErrors?: WriteError[] } + | WriteConcernError + | AnyError, + result: BulkWriteResult + ) { + super(error); + + if (error instanceof WriteConcernError) this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = error.writeErrors ?? []; + } + + this.result = result; + Object.assign(this, error); + } + + override get name(): string { + return 'MongoBulkWriteError'; + } + + /** Number of documents inserted. */ + get insertedCount(): number { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount(): number { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount(): number { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount(): number { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount(): number { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds(): { [key: number]: any } { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds(): { [key: number]: any } { + return this.result.upsertedIds; + } +} + +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +export class FindOperators { + bulkOperation: BulkOperationBase; + + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation: BulkOperationBase) { + this.bulkOperation = bulkOperation; + } + + /** Add a multiple update operation to the bulk operation */ + update(updateDocument: Document | Document[]): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + }) + ); + } + + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document | Document[]): BulkOperationBase { + if (!hasAtomicOperators(updateDocument)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, updateDocument, { ...currentOp, multi: false }) + ); + } + + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement: Document): BulkOperationBase { + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.UPDATE, + makeUpdateStatement(currentOp.selector, replacement, { ...currentOp, multi: false }) + ); + } + + /** Add a delete one operation to the bulk operation */ + deleteOne(): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 1 }) + ); + } + + /** Add a delete many operation to the bulk operation */ + delete(): BulkOperationBase { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 0 }) + ); + } + + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert(): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + + /** Specifies the collation for the query condition. */ + collation(collation: CollationOptions): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters: Document[]): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } + + /** Specifies hint for the bulk operation. */ + hint(hint: Hint): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.hint = hint; + return this; + } +} + +/** @internal */ +export interface BulkOperationPrivate { + bulkResult: BulkResult; + currentBatch?: Batch; + currentIndex: number; + // ordered specific + currentBatchSize: number; + currentBatchSizeBytes: number; + // unordered specific + currentInsertBatch?: Batch; + currentUpdateBatch?: Batch; + currentRemoveBatch?: Batch; + batches: Batch[]; + // Write concern + writeConcern?: WriteConcern; + // Max batch size options + maxBsonObjectSize: number; + maxBatchSizeBytes: number; + maxWriteBatchSize: number; + maxKeySize: number; + // Namespace + namespace: MongoDBNamespace; + // Topology + topology: Topology; + // Options + options: BulkWriteOptions; + // BSON options + bsonOptions: BSONSerializeOptions; + // Document used to build a bulk operation + currentOp?: Document; + // Executed + executed: boolean; + // Collection + collection: Collection; + // Fundamental error + err?: AnyError; + // check keys + checkKeys: boolean; + bypassDocumentValidation?: boolean; +} + +/** @public */ +export interface BulkWriteOptions extends CommandOperationOptions { + /** + * Allow driver to bypass schema validation. + * @defaultValue `false` - documents will be validated by default + **/ + bypassDocumentValidation?: boolean; + /** + * If true, when an insert fails, don't execute the remaining writes. + * If false, continue with remaining inserts when one fails. + * @defaultValue `true` - inserts are ordered by default + */ + ordered?: boolean; + /** + * Force server to assign _id values instead of driver. + * @defaultValue `false` - the driver generates `_id` fields by default + **/ + forceServerObjectId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +const executeCommandsAsync = promisify(executeCommands); + +/** + * TODO(NODE-4063) + * BulkWrites merge complexity is implemented in executeCommands + * This provides a vehicle to treat bulkOperations like any other operation (hence "shim") + * We would like this logic to simply live inside the BulkWriteOperation class + * @internal + */ +export class BulkWriteShimOperation extends AbstractOperation { + bulkOperation: BulkOperationBase; + constructor(bulkOperation: BulkOperationBase, options: BulkWriteOptions) { + super(options); + this.bulkOperation = bulkOperation; + } + + get commandName(): string { + return 'bulkWrite' as const; + } + + execute(_server: Server, session: ClientSession | undefined): Promise { + if (this.options.session == null) { + // An implicit session could have been created by 'executeOperation' + // So if we stick it on finalOptions here, each bulk operation + // will use this same session, it'll be passed in the same way + // an explicit session would be + this.options.session = session; + } + return executeCommandsAsync(this.bulkOperation, this.options); + } +} + +/** @public */ +export abstract class BulkOperationBase { + isOrdered: boolean; + /** @internal */ + s: BulkOperationPrivate; + operationId?: number; + + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(private collection: Collection, options: BulkWriteOptions, isOrdered: boolean) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + const topology = getTopology(collection); + options = options == null ? {} : options; + // TODO Bring from driver information in hello + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = undefined; + + // Set max byte size + const hello = topology.lastHello(); + + // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents + // over 2mb are still allowed + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = + hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + + // Final results + const bulkResult: BulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: resolveBSONOptions(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @example + * ```ts + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + * ``` + */ + insert(document: Document): BulkOperationBase { + maybeAddIdToDocuments(this.collection, document, { + forceServerObjectId: this.shouldForceServerObjectId() + }); + + return this.addToOperationsList(BatchType.INSERT, document); + } + + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @example + * ```ts + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }}); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + * ``` + */ + find(selector: Document): FindOperators { + if (!selector) { + throw new MongoInvalidArgumentError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** Specifies a raw operation to perform in the bulk write. */ + raw(op: AnyBulkWriteOperation): this { + if (op == null || typeof op !== 'object') { + throw new MongoInvalidArgumentError('Operation must be an object with an operation key'); + } + if ('insertOne' in op) { + const forceServerObjectId = this.shouldForceServerObjectId(); + const document = + op.insertOne && op.insertOne.document == null + ? // TODO(NODE-6003): remove support for omitting the `documents` subdocument in bulk inserts + (op.insertOne as Document) + : op.insertOne.document; + + maybeAddIdToDocuments(this.collection, document, { forceServerObjectId }); + + return this.addToOperationsList(BatchType.INSERT, document); + } + + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement( + op.replaceOne.filter, + op.replaceOne.replacement, + { ...op.replaceOne, multi: false } + ); + if (hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = makeUpdateStatement(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!hasAtomicOperators(updateStatement.u)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(BatchType.UPDATE, updateStatement); + } + } + + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(op.deleteOne.filter, { ...op.deleteOne, limit: 1 }) + ); + } + + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList( + BatchType.DELETE, + makeDeleteStatement(op.deleteMany.filter, { ...op.deleteMany, limit: 0 }) + ); + } + + // otherwise an unknown operation was provided + throw new MongoInvalidArgumentError( + 'bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany' + ); + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get batches(): Batch[] { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) batches.push(this.s.currentRemoveBatch); + } + return batches; + } + + async execute(options: BulkWriteOptions = {}): Promise { + if (this.s.executed) { + throw new MongoBatchReExecutionError(); + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + throw new MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + } + + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + const operation = new BulkWriteShimOperation(this, finalOptions); + + return executeOperation(this.s.collection.client, operation); + } + + /** + * Handles the write error before executing commands + * @internal + */ + handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + + callback( + new MongoBulkWriteError( + { + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, + writeResult + ) + ); + + return true; + } + + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; + } + + return false; + } + + abstract addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this; + + private shouldForceServerObjectId(): boolean { + return ( + this.s.options.forceServerObjectId === true || + this.s.collection.s.db.options?.forceServerObjectId === true + ); + } +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); + +function isInsertBatch(batch: Batch): boolean { + return batch.batchType === BatchType.INSERT; +} + +function isUpdateBatch(batch: Batch): batch is Batch { + return batch.batchType === BatchType.UPDATE; +} + +function isDeleteBatch(batch: Batch): batch is Batch { + return batch.batchType === BatchType.DELETE; +} + +function buildCurrentOp(bulkOp: BulkOperationBase): Document { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) currentOp = {}; + return currentOp; +} diff --git a/nodejs/node_modules/mongodb/src/bulk/ordered.ts b/nodejs/node_modules/mongodb/src/bulk/ordered.ts new file mode 100644 index 00000000..2a9e9ece --- /dev/null +++ b/nodejs/node_modules/mongodb/src/bulk/ordered.ts @@ -0,0 +1,83 @@ +import type { Document } from '../bson'; +import * as BSON from '../bson'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError } from '../error'; +import type { DeleteStatement } from '../operations/delete'; +import type { UpdateStatement } from '../operations/update'; +import { Batch, BatchType, BulkOperationBase, type BulkWriteOptions } from './common'; + +/** @public */ +export class OrderedBulkOperation extends BulkOperationBase { + /** @internal */ + constructor(collection: Collection, options: BulkWriteOptions) { + super(collection, options, true); + } + + addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + } as any); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new MongoInvalidArgumentError( + `Document is larger than the maximum size ${this.s.maxBsonObjectSize}` + ); + + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + const maxKeySize = this.s.maxKeySize; + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType + ) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + + // Create a new batch + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + + if (batchType === BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: (document as Document)._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw new MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; + } +} diff --git a/nodejs/node_modules/mongodb/src/bulk/unordered.ts b/nodejs/node_modules/mongodb/src/bulk/unordered.ts new file mode 100644 index 00000000..3b7e7f2f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/bulk/unordered.ts @@ -0,0 +1,116 @@ +import type { Document } from '../bson'; +import * as BSON from '../bson'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError } from '../error'; +import type { DeleteStatement } from '../operations/delete'; +import type { UpdateStatement } from '../operations/update'; +import { type Callback } from '../utils'; +import { + Batch, + BatchType, + BulkOperationBase, + type BulkWriteOptions, + type BulkWriteResult +} from './common'; + +/** @public */ +export class UnorderedBulkOperation extends BulkOperationBase { + /** @internal */ + constructor(collection: Collection, options: BulkWriteOptions) { + super(collection, options, false); + } + + override handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean { + if (this.s.batches.length) { + return false; + } + + return super.handleWriteError(callback, writeResult); + } + + addToOperationsList( + batchType: BatchType, + document: Document | UpdateStatement | DeleteStatement + ): this { + // Get the bsonSize + const bsonSize = BSON.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + } as any); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new MongoInvalidArgumentError( + `Document is larger than the maximum size ${this.s.maxBsonObjectSize}` + ); + } + + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } else if (batchType === BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } else if (batchType === BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + + const maxKeySize = this.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || + // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, + // since we can't sent an empty batch + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType + ) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + + // Create a new batch + this.s.currentBatch = new Batch(batchType, this.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw new MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (batchType === BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: (document as Document)._id + }); + } else if (batchType === BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } else if (batchType === BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + return this; + } +} diff --git a/nodejs/node_modules/mongodb/src/change_stream.ts b/nodejs/node_modules/mongodb/src/change_stream.ts new file mode 100644 index 00000000..d8e4ad8a --- /dev/null +++ b/nodejs/node_modules/mongodb/src/change_stream.ts @@ -0,0 +1,979 @@ +import type { Readable } from 'stream'; + +import type { Binary, Document, Timestamp } from './bson'; +import { Collection } from './collection'; +import { CHANGE, CLOSE, END, ERROR, INIT, MORE, RESPONSE, RESUME_TOKEN_CHANGED } from './constants'; +import type { AbstractCursorEvents, CursorStreamOptions } from './cursor/abstract_cursor'; +import { ChangeStreamCursor, type ChangeStreamCursorOptions } from './cursor/change_stream_cursor'; +import { Db } from './db'; +import { + type AnyError, + isResumableError, + MongoAPIError, + MongoChangeStreamError, + MongoRuntimeError +} from './error'; +import { MongoClient } from './mongo_client'; +import { type InferIdType, TypedEventEmitter } from './mongo_types'; +import type { AggregateOptions } from './operations/aggregate'; +import type { CollationOptions, OperationParent } from './operations/command'; +import type { ReadPreference } from './read_preference'; +import type { ServerSessionId } from './sessions'; +import { filterOptions, getTopology, type MongoDBNamespace } from './utils'; + +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); + +const CHANGE_STREAM_OPTIONS = [ + 'resumeAfter', + 'startAfter', + 'startAtOperationTime', + 'fullDocument', + 'fullDocumentBeforeChange', + 'showExpandedEvents' +] as const; + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +const CHANGE_STREAM_EVENTS = [RESUME_TOKEN_CHANGED, END, CLOSE]; + +const NO_RESUME_TOKEN_ERROR = + 'A change stream document has been received that lacks a resume token (_id).'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; + +/** + * @public + * @deprecated Please use the ChangeStreamCursorOptions type instead. + */ +export interface ResumeOptions { + startAtOperationTime?: Timestamp; + batchSize?: number; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + readPreference?: ReadPreference; + resumeAfter?: ResumeToken; + startAfter?: ResumeToken; + fullDocument?: string; +} + +/** + * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server. + * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume + * @public + */ +export type ResumeToken = unknown; + +/** + * Represents a specific point in time on a server. Can be retrieved by using `db.command()` + * @public + * @see https://www.mongodb.com/docs/manual/reference/method/db.runCommand/#response + */ +export type OperationTime = Timestamp; + +/** + * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @public + */ +export interface ChangeStreamOptions extends Omit { + /** + * Allowed values: 'updateLookup', 'whenAvailable', 'required'. + * + * When set to 'updateLookup', the change notification for partial updates + * will include both a delta describing the changes to the document as well + * as a copy of the entire document that was changed from some time after + * the change occurred. + * + * When set to 'whenAvailable', configures the change stream to return the + * post-image of the modified document for replace and update change events + * if the post-image for this event is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the post-image is not available. + */ + fullDocument?: string; + + /** + * Allowed values: 'whenAvailable', 'required', 'off'. + * + * The default is to not send a value, which is equivalent to 'off'. + * + * When set to 'whenAvailable', configures the change stream to return the + * pre-image of the modified document for replace, update, and delete change + * events if it is available. + * + * When set to 'required', the same behavior as 'whenAvailable' except that + * an error is raised if the pre-image is not available. + */ + fullDocumentBeforeChange?: string; + /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */ + maxAwaitTimeMS?: number; + /** + * Allows you to start a changeStream after a specified event. + * @see https://www.mongodb.com/docs/manual/changeStreams/#resumeafter-for-change-streams + */ + resumeAfter?: ResumeToken; + /** + * Similar to resumeAfter, but will allow you to start after an invalidated event. + * @see https://www.mongodb.com/docs/manual/changeStreams/#startafter-for-change-streams + */ + startAfter?: ResumeToken; + /** Will start the changeStream after the specified operationTime. */ + startAtOperationTime?: OperationTime; + /** + * The number of documents to return per batch. + * @see https://www.mongodb.com/docs/manual/reference/command/aggregate + */ + batchSize?: number; + + /** + * When enabled, configures the change stream to include extra change events. + * + * - createIndexes + * - dropIndexes + * - modify + * - create + * - shardCollection + * - reshardCollection + * - refineCollectionShardKey + */ + showExpandedEvents?: boolean; +} + +/** @public */ +export interface ChangeStreamNameSpace { + db: string; + coll: string; +} + +/** @public */ +export interface ChangeStreamDocumentKey { + /** + * For unsharded collections this contains a single field `_id`. + * For sharded collections, this will contain all the components of the shard key + */ + documentKey: { _id: InferIdType; [shardKey: string]: any }; +} + +/** @public */ +export interface ChangeStreamSplitEvent { + /** Which fragment of the change this is. */ + fragment: number; + /** The total number of fragments. */ + of: number; +} + +/** @public */ +export interface ChangeStreamDocumentCommon { + /** + * The id functions as an opaque token for use when resuming an interrupted + * change stream. + */ + _id: ResumeToken; + /** + * The timestamp from the oplog entry associated with the event. + * For events that happened as part of a multi-document transaction, the associated change stream + * notifications will have the same clusterTime value, namely the time when the transaction was committed. + * On a sharded cluster, events that occur on different shards can have the same clusterTime but be + * associated with different transactions or even not be associated with any transaction. + * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document. + */ + clusterTime?: Timestamp; + + /** + * The transaction number. + * Only present if the operation is part of a multi-document transaction. + * + * **NOTE:** txnNumber can be a Long if promoteLongs is set to false + */ + txnNumber?: number; + + /** + * The identifier for the session associated with the transaction. + * Only present if the operation is part of a multi-document transaction. + */ + lsid?: ServerSessionId; + + /** + * When the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent + * stage, events larger than 16MB will be split into multiple events and contain the + * following information about which fragment the current event is. + */ + splitEvent?: ChangeStreamSplitEvent; +} + +/** @public */ +export interface ChangeStreamDocumentCollectionUUID { + /** + * The UUID (Binary subtype 4) of the collection that the operation was performed on. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers + * flag is enabled. + * + * @sinceServerVersion 6.1.0 + */ + collectionUUID: Binary; +} + +/** @public */ +export interface ChangeStreamDocumentOperationDescription { + /** + * An description of the operation. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * @sinceServerVersion 6.1.0 + */ + operationDescription?: Document; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event + */ +export interface ChangeStreamInsertDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'insert'; + /** This key will contain the document being inserted */ + fullDocument: TSchema; + /** Namespace the insert event occurred on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event + */ +export interface ChangeStreamUpdateDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'update'; + /** + * This is only set if `fullDocument` is set to `'updateLookup'` + * Contains the point-in-time post-image of the modified document if the + * post-image is available and either 'required' or 'whenAvailable' was + * specified for the 'fullDocument' option when creating the change stream. + */ + fullDocument?: TSchema; + /** Contains a description of updated and removed fields in this operation */ + updateDescription: UpdateDescription; + /** Namespace the update event occurred on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event + */ +export interface ChangeStreamReplaceDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey { + /** Describes the type of operation represented in this change notification */ + operationType: 'replace'; + /** The fullDocument of a replace event represents the document after the insert of the replacement document */ + fullDocument: TSchema; + /** Namespace the replace event occurred on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event + */ +export interface ChangeStreamDeleteDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'delete'; + /** Namespace the delete event occurred on */ + ns: ChangeStreamNameSpace; + /** + * Contains the pre-image of the modified or deleted document if the + * pre-image is available for the change event and either 'required' or + * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option + * when creating the change stream. If 'whenAvailable' was specified but the + * pre-image is unavailable, this will be explicitly set to null. + */ + fullDocumentBeforeChange?: TSchema; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event + */ +export interface ChangeStreamDropDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'drop'; + /** Namespace the drop event occurred on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event + */ +export interface ChangeStreamRenameDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'rename'; + /** The new name for the `ns.coll` collection */ + to: { db: string; coll: string }; + /** The "from" namespace that the rename occurred on */ + ns: ChangeStreamNameSpace; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event + */ +export interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropDatabase'; + /** The database dropped */ + ns: { db: string }; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event + */ +export interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon { + /** Describes the type of operation represented in this change notification */ + operationType: 'invalidate'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamCreateIndexDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'createIndexes'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamDropIndexDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'dropIndexes'; +} + +/** + * Only present when the `showExpandedEvents` flag is enabled. + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamCollModDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'modify'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamCreateDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID { + /** Describes the type of operation represented in this change notification */ + operationType: 'create'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamShardCollectionDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'shardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamReshardCollectionDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'reshardCollection'; +} + +/** + * @public + * @see https://www.mongodb.com/docs/manual/reference/change-events/ + */ +export interface ChangeStreamRefineCollectionShardKeyDocument + extends ChangeStreamDocumentCommon, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentOperationDescription { + /** Describes the type of operation represented in this change notification */ + operationType: 'refineCollectionShardKey'; +} + +/** @public */ +export type ChangeStreamDocument = + | ChangeStreamInsertDocument + | ChangeStreamUpdateDocument + | ChangeStreamReplaceDocument + | ChangeStreamDeleteDocument + | ChangeStreamDropDocument + | ChangeStreamRenameDocument + | ChangeStreamDropDatabaseDocument + | ChangeStreamInvalidateDocument + | ChangeStreamCreateIndexDocument + | ChangeStreamCreateDocument + | ChangeStreamCollModDocument + | ChangeStreamDropIndexDocument + | ChangeStreamShardCollectionDocument + | ChangeStreamReshardCollectionDocument + | ChangeStreamRefineCollectionShardKeyDocument; + +/** @public */ +export interface UpdateDescription { + /** + * A document containing key:value pairs of names of the fields that were + * changed, and the new value for those fields. + */ + updatedFields?: Partial; + + /** + * An array of field names that were removed from the document. + */ + removedFields?: string[]; + + /** + * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages: + * - $addFields + * - $set + * - $replaceRoot + * - $replaceWith + */ + truncatedArrays?: Array<{ + /** The name of the truncated field. */ + field: string; + /** The number of elements in the truncated array. */ + newSize: number; + }>; + + /** + * A document containing additional information about any ambiguous update paths from the update event. The document + * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example, + * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like + * the following: + * + * ``` + * { + * 'a.0': ['a', '0'] + * } + * ``` + * + * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents` + * is enabled for the change stream. + * @sinceServerVersion 6.1.0 + */ + disambiguatedPaths?: Document; +} + +/** @public */ +export type ChangeStreamEvents< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument +> = { + resumeTokenChanged(token: ResumeToken): void; + init(response: any): void; + more(response?: any): void; + response(): void; + end(): void; + error(error: Error): void; + change(change: TChange): void; +} & AbstractCursorEvents; + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +export class ChangeStream< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument +> extends TypedEventEmitter> { + pipeline: Document[]; + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + options: ChangeStreamOptions & { writeConcern?: never }; + parent: MongoClient | Db | Collection; + namespace: MongoDBNamespace; + type: symbol; + /** @internal */ + cursor: ChangeStreamCursor; + streamOptions?: CursorStreamOptions; + /** @internal */ + [kCursorStream]?: Readable & AsyncIterable; + /** @internal */ + [kClosed]: boolean; + /** @internal */ + [kMode]: false | 'iterator' | 'emitter'; + + /** @event */ + static readonly RESPONSE = RESPONSE; + /** @event */ + static readonly MORE = MORE; + /** @event */ + static readonly INIT = INIT; + /** @event */ + static readonly CLOSE = CLOSE; + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * @event + */ + static readonly CHANGE = CHANGE; + /** @event */ + static readonly END = END; + /** @event */ + static readonly ERROR = ERROR; + /** + * Emitted each time the change stream stores a new resume token. + * @event + */ + static readonly RESUME_TOKEN_CHANGED = RESUME_TOKEN_CHANGED; + + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor( + parent: OperationParent, + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ) { + super(); + + this.pipeline = pipeline; + this.options = { ...options }; + delete this.options.writeConcern; + + if (parent instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } else if (parent instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } else if (parent instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } else { + throw new MongoChangeStreamError( + 'Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient' + ); + } + + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + + // Create contained Change Stream cursor + this.cursor = this._createChangeStreamCursor(options); + + this[kClosed] = false; + this[kMode] = false; + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this._streamEvents(this.cursor); + } + }); + + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this[kCursorStream]?.removeAllListeners('data'); + } + }); + } + + /** @internal */ + get cursorStream(): (Readable & AsyncIterable) | undefined { + return this[kCursorStream]; + } + + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken(): ResumeToken { + return this.cursor?.resumeToken; + } + + /** Check if there is any document still available in the Change Stream */ + async hasNext(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + /** Get the next available document from the Change Stream. */ + async next(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + async tryNext(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + if (this.closed) { + return; + } + + try { + // Change streams run indefinitely as long as errors are resumable + // So the only loop breaking condition is if `next()` throws + while (true) { + yield await this.next(); + } + } finally { + try { + await this.close(); + } catch { + // we're not concerned with errors from close() + } + } + } + + /** Is the cursor closed */ + get closed(): boolean { + return this[kClosed] || this.cursor.closed; + } + + /** Close the Change Stream */ + async close(): Promise { + this[kClosed] = true; + + const cursor = this.cursor; + try { + await cursor.close(); + } finally { + this._endStream(); + } + } + + /** + * Return a modified Readable stream including a possible transform method. + * + * NOTE: When using a Stream to process change stream events, the stream will + * NOT automatically resume in the case a resumable error is encountered. + * + * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed + */ + stream(options?: CursorStreamOptions): Readable & AsyncIterable { + if (this.closed) { + throw new MongoChangeStreamError(CHANGESTREAM_CLOSED_ERROR); + } + + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** @internal */ + private _setIsEmitter(): void { + if (this[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new MongoAPIError( + 'ChangeStream cannot be used as an EventEmitter after being used as an iterator' + ); + } + this[kMode] = 'emitter'; + } + + /** @internal */ + private _setIsIterator(): void { + if (this[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new MongoAPIError( + 'ChangeStream cannot be used as an iterator after being used as an EventEmitter' + ); + } + this[kMode] = 'iterator'; + } + + /** + * Create a new change stream cursor based on self's configuration + * @internal + */ + private _createChangeStreamCursor( + options: ChangeStreamOptions | ChangeStreamCursorOptions + ): ChangeStreamCursor { + const changeStreamStageOptions = filterOptions(options, CHANGE_STREAM_OPTIONS); + if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; + + const client: MongoClient | null = + this.type === CHANGE_DOMAIN_TYPES.CLUSTER + ? (this.parent as MongoClient) + : this.type === CHANGE_DOMAIN_TYPES.DATABASE + ? (this.parent as Db).client + : this.type === CHANGE_DOMAIN_TYPES.COLLECTION + ? (this.parent as Collection).client + : null; + + if (client == null) { + // This should never happen because of the assertion in the constructor + throw new MongoRuntimeError( + `Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}` + ); + } + + const changeStreamCursor = new ChangeStreamCursor( + client, + this.namespace, + pipeline, + options + ); + + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => this.emit(event, e)); + } + + if (this.listenerCount(ChangeStream.CHANGE) > 0) { + this._streamEvents(changeStreamCursor); + } + + return changeStreamCursor; + } + + /** @internal */ + private _closeEmitterModeWithError(error: AnyError): void { + this.emit(ChangeStream.ERROR, error); + + this.close().catch(() => null); + } + + /** @internal */ + private _streamEvents(cursor: ChangeStreamCursor): void { + this._setIsEmitter(); + const stream = this[kCursorStream] ?? cursor.stream(); + this[kCursorStream] = stream; + stream.on('data', change => { + try { + const processedChange = this._processChange(change); + this.emit(ChangeStream.CHANGE, processedChange); + } catch (error) { + this.emit(ChangeStream.ERROR, error); + } + }); + stream.on('error', error => this._processErrorStreamMode(error)); + } + + /** @internal */ + private _endStream(): void { + const cursorStream = this[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + + this[kCursorStream] = undefined; + } + + /** @internal */ + private _processChange(change: TChange | null): TChange { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR); + } + + if (change && !change._id) { + throw new MongoChangeStreamError(NO_RESUME_TOKEN_ERROR); + } + + // cache the resume token + this.cursor.cacheResumeToken(change._id); + + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + this.options.startAtOperationTime = undefined; + + return change; + } + + /** @internal */ + private _processErrorStreamMode(changeStreamError: AnyError) { + // If the change stream has been closed explicitly, do not process error. + if (this[kClosed]) return; + + if (isResumableError(changeStreamError, this.cursor.maxWireVersion)) { + this._endStream(); + this.cursor.close().catch(() => null); + + const topology = getTopology(this.parent); + topology.selectServer( + this.cursor.readPreference, + { operationName: 'reconnect topology in change stream' }, + serverSelectionError => { + if (serverSelectionError) return this._closeEmitterModeWithError(changeStreamError); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } + ); + } else { + this._closeEmitterModeWithError(changeStreamError); + } + } + + /** @internal */ + private async _processErrorIteratorMode(changeStreamError: AnyError) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + + if (!isResumableError(changeStreamError, this.cursor.maxWireVersion)) { + try { + await this.close(); + } catch { + // ignore errors from close + } + throw changeStreamError; + } + + await this.cursor.close().catch(() => null); + const topology = getTopology(this.parent); + try { + await topology.selectServerAsync(this.cursor.readPreference, { + operationName: 'reconnect topology in change stream' + }); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } catch { + // if the topology can't reconnect, close the stream + await this.close(); + throw changeStreamError; + } + } +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/auto_encrypter.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/auto_encrypter.ts new file mode 100644 index 00000000..981a6988 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/auto_encrypter.ts @@ -0,0 +1,570 @@ +import { + type MongoCrypt, + type MongoCryptConstructor, + type MongoCryptOptions +} from 'mongodb-client-encryption'; + +import { deserialize, type Document, serialize } from '../bson'; +import { type CommandOptions, type ProxyOptions } from '../cmap/connection'; +import { getMongoDBClientEncryption } from '../deps'; +import { MongoRuntimeError } from '../error'; +import { MongoClient, type MongoClientOptions } from '../mongo_client'; +import { MongoDBCollectionNamespace } from '../utils'; +import * as cryptoCallbacks from './crypto_callbacks'; +import { MongoCryptInvalidArgumentError } from './errors'; +import { MongocryptdManager } from './mongocryptd_manager'; +import { type KMSProviders, refreshKMSCredentials } from './providers'; +import { type CSFLEKMSTlsOptions, StateMachine } from './state_machine'; + +/** @public */ +export interface AutoEncryptionOptions { + /** @internal client for metadata lookups */ + metadataClient?: MongoClient; + /** A `MongoClient` used to fetch keys from a key vault */ + keyVaultClient?: MongoClient; + /** The namespace where keys are stored in the key vault */ + keyVaultNamespace?: string; + /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */ + kmsProviders?: { + /** Configuration options for using 'aws' as your KMS provider */ + aws?: + | { + /** The access key used for the AWS KMS provider */ + accessKeyId: string; + /** The secret access key used for the AWS KMS provider */ + secretAccessKey: string; + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + } + | Record; + /** Configuration options for using 'local' as your KMS provider */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + /** Configuration options for using 'azure' as your KMS provider */ + azure?: + | { + /** The tenant ID identifies the organization for the account */ + tenantId: string; + /** The client ID to authenticate a registered application */ + clientId: string; + /** The client secret to authenticate a registered application */ + clientSecret: string; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + } + | { + /** + * If present, an access token to authenticate with Azure. + */ + accessToken: string; + } + | Record; + /** Configuration options for using 'gcp' as your KMS provider */ + gcp?: + | { + /** The service account email to authenticate */ + email: string; + /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */ + privateKey: string | Buffer; + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + } + | { + /** + * If present, an access token to authenticate with GCP. + */ + accessToken: string; + } + | Record; + /** + * Configuration options for using 'kmip' as your KMS provider + */ + kmip?: { + /** + * The output endpoint string. + * The endpoint consists of a hostname and port separated by a colon. + * E.g. "example.com:123". A port is always present. + */ + endpoint?: string; + }; + }; + /** + * A map of namespaces to a local JSON schema for encryption + * + * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + */ + schemaMap?: Document; + /** Supply a schema for the encrypted fields in the document */ + encryptedFieldsMap?: Document; + /** Allows the user to bypass auto encryption, maintaining implicit decryption */ + bypassAutoEncryption?: boolean; + /** Allows users to bypass query analysis */ + bypassQueryAnalysis?: boolean; + options?: { + /** An optional hook to catch logging messages from the underlying encryption engine */ + logger?: (level: AutoEncryptionLoggerLevel, message: string) => void; + }; + extraOptions?: { + /** + * A local process the driver communicates with to determine how to encrypt values in a command. + * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + */ + mongocryptdURI?: string; + /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */ + mongocryptdBypassSpawn?: boolean; + /** The path to the mongocryptd executable on the system */ + mongocryptdSpawnPath?: string; + /** Command line arguments to use when auto-spawning a mongocryptd */ + mongocryptdSpawnArgs?: string[]; + /** + * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd). + * + * This needs to be the path to the file itself, not a directory. + * It can be an absolute or relative path. If the path is relative and + * its first component is `$ORIGIN`, it will be replaced by the directory + * containing the mongodb-client-encryption native addon file. Otherwise, + * the path will be interpreted relative to the current working directory. + * + * Currently, loading different MongoDB Crypt shared library files from different + * MongoClients in the same process is not supported. + * + * If this option is provided and no MongoDB Crypt shared library could be loaded + * from the specified location, creating the MongoClient will fail. + * + * If this option is not provided and `cryptSharedLibRequired` is not specified, + * the AutoEncrypter will attempt to spawn and/or use mongocryptd according + * to the mongocryptd-specific `extraOptions` options. + * + * Specifying a path prevents mongocryptd from being used as a fallback. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibPath?: string; + /** + * If specified, never use mongocryptd and instead fail when the MongoDB Crypt + * shared library could not be loaded. + * + * This is always true when `cryptSharedLibPath` is specified. + * + * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher. + */ + cryptSharedLibRequired?: boolean; + /** + * Search paths for a MongoDB Crypt shared library to be used (instead of mongocryptd) + * Only for driver testing! + * @internal + */ + cryptSharedLibSearchPaths?: string[]; + }; + proxyOptions?: ProxyOptions; + /** The TLS options to use connecting to the KMS provider */ + tlsOptions?: CSFLEKMSTlsOptions; +} + +/** + * @public + * + * Extra options related to the mongocryptd process + * \* _Available in MongoDB 6.0 or higher._ + */ +export type AutoEncryptionExtraOptions = NonNullable; + +/** @public */ +export const AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +} as const); + +/** + * @public + * The level of severity of the log message + * + * | Value | Level | + * |-------|-------| + * | 0 | Fatal Error | + * | 1 | Error | + * | 2 | Warning | + * | 3 | Info | + * | 4 | Trace | + */ +export type AutoEncryptionLoggerLevel = + (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel]; + +// Typescript errors if we index objects with `Symbol.for(...)`, so +// to avoid TS errors we pull them out into variables. Then we can type +// the objects (and class) that we expect to see them on and prevent TS +// errors. +/** @internal */ +const kDecorateResult = Symbol.for('@@mdb.decorateDecryptionResult'); +/** @internal */ +const kDecoratedKeys = Symbol.for('@@mdb.decryptedKeys'); + +/** + * @internal An internal class to be used by the driver for auto encryption + * **NOTE**: Not meant to be instantiated directly, this is for internal use only. + */ +export class AutoEncrypter { + _client: MongoClient; + _bypassEncryption: boolean; + _keyVaultNamespace: string; + _keyVaultClient: MongoClient; + _metaDataClient: MongoClient; + _proxyOptions: ProxyOptions; + _tlsOptions: CSFLEKMSTlsOptions; + _kmsProviders: KMSProviders; + _bypassMongocryptdAndCryptShared: boolean; + _contextCounter: number; + + _mongocryptdManager?: MongocryptdManager; + _mongocryptdClient?: MongoClient; + + /** @internal */ + _mongocrypt: MongoCrypt; + + /** + * Used by devtools to enable decorating decryption results. + * + * When set and enabled, `decrypt` will automatically recursively + * traverse a decrypted document and if a field has been decrypted, + * it will mark it as decrypted. Compass uses this to determine which + * fields were decrypted. + */ + [kDecorateResult] = false; + + /** @internal */ + static getMongoCrypt(): MongoCryptConstructor { + const encryption = getMongoDBClientEncryption(); + if ('kModuleError' in encryption) { + throw encryption.kModuleError; + } + return encryption.MongoCrypt; + } + + /** + * Create an AutoEncrypter + * + * **Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient + * + * **Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server. + * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted. + * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption. + * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. + * + * @example Create an AutoEncrypter that makes use of mongocryptd + * ```ts + * // Enabling autoEncryption via a MongoClient using mongocryptd + * const { MongoClient } = require('mongodb'); + * const client = new MongoClient(URL, { + * autoEncryption: { + * kmsProviders: { + * aws: { + * accessKeyId: AWS_ACCESS_KEY, + * secretAccessKey: AWS_SECRET_KEY + * } + * } + * } + * }); + * ``` + * + * await client.connect(); + * // From here on, the client will be encrypting / decrypting automatically + * @example Create an AutoEncrypter that makes use of libmongocrypt's CSFLE shared library + * ```ts + * // Enabling autoEncryption via a MongoClient using CSFLE shared library + * const { MongoClient } = require('mongodb'); + * const client = new MongoClient(URL, { + * autoEncryption: { + * kmsProviders: { + * aws: {} + * }, + * extraOptions: { + * cryptSharedLibPath: '/path/to/local/crypt/shared/lib', + * cryptSharedLibRequired: true + * } + * } + * }); + * ``` + * + * await client.connect(); + * // From here on, the client will be encrypting / decrypting automatically + */ + constructor(client: MongoClient, options: AutoEncryptionOptions) { + this._client = client; + this._bypassEncryption = options.bypassAutoEncryption === true; + + this._keyVaultNamespace = options.keyVaultNamespace || 'admin.datakeys'; + this._keyVaultClient = options.keyVaultClient || client; + this._metaDataClient = options.metadataClient || client; + this._proxyOptions = options.proxyOptions || {}; + this._tlsOptions = options.tlsOptions || {}; + this._kmsProviders = options.kmsProviders || {}; + + const mongoCryptOptions: MongoCryptOptions = { + cryptoCallbacks + }; + if (options.schemaMap) { + mongoCryptOptions.schemaMap = Buffer.isBuffer(options.schemaMap) + ? options.schemaMap + : (serialize(options.schemaMap) as Buffer); + } + + if (options.encryptedFieldsMap) { + mongoCryptOptions.encryptedFieldsMap = Buffer.isBuffer(options.encryptedFieldsMap) + ? options.encryptedFieldsMap + : (serialize(options.encryptedFieldsMap) as Buffer); + } + + mongoCryptOptions.kmsProviders = !Buffer.isBuffer(this._kmsProviders) + ? (serialize(this._kmsProviders) as Buffer) + : this._kmsProviders; + + if (options.options?.logger) { + mongoCryptOptions.logger = options.options.logger; + } + + if (options.extraOptions && options.extraOptions.cryptSharedLibPath) { + mongoCryptOptions.cryptSharedLibPath = options.extraOptions.cryptSharedLibPath; + } + + if (options.bypassQueryAnalysis) { + mongoCryptOptions.bypassQueryAnalysis = options.bypassQueryAnalysis; + } + + this._bypassMongocryptdAndCryptShared = this._bypassEncryption || !!options.bypassQueryAnalysis; + + if (options.extraOptions && options.extraOptions.cryptSharedLibSearchPaths) { + // Only for driver testing + mongoCryptOptions.cryptSharedLibSearchPaths = options.extraOptions.cryptSharedLibSearchPaths; + } else if (!this._bypassMongocryptdAndCryptShared) { + mongoCryptOptions.cryptSharedLibSearchPaths = ['$SYSTEM']; + } + + const MongoCrypt = AutoEncrypter.getMongoCrypt(); + this._mongocrypt = new MongoCrypt(mongoCryptOptions); + this._contextCounter = 0; + + if ( + options.extraOptions && + options.extraOptions.cryptSharedLibRequired && + !this.cryptSharedLibVersionInfo + ) { + throw new MongoCryptInvalidArgumentError( + '`cryptSharedLibRequired` set but no crypt_shared library loaded' + ); + } + + // Only instantiate mongocryptd manager/client once we know for sure + // that we are not using the CSFLE shared library. + if (!this._bypassMongocryptdAndCryptShared && !this.cryptSharedLibVersionInfo) { + this._mongocryptdManager = new MongocryptdManager(options.extraOptions); + const clientOptions: MongoClientOptions = { + serverSelectionTimeoutMS: 10000 + }; + + if (options.extraOptions == null || typeof options.extraOptions.mongocryptdURI !== 'string') { + clientOptions.family = 4; + } + + this._mongocryptdClient = new MongoClient(this._mongocryptdManager.uri, clientOptions); + } + } + + /** + * Initializes the auto encrypter by spawning a mongocryptd and connecting to it. + * + * This function is a no-op when bypassSpawn is set or the crypt shared library is used. + */ + async init(): Promise { + if (this._bypassMongocryptdAndCryptShared || this.cryptSharedLibVersionInfo) { + return; + } + if (!this._mongocryptdManager) { + throw new MongoRuntimeError( + 'Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified.' + ); + } + if (!this._mongocryptdClient) { + throw new MongoRuntimeError( + 'Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified.' + ); + } + + if (!this._mongocryptdManager.bypassSpawn) { + await this._mongocryptdManager.spawn(); + } + + try { + const client = await this._mongocryptdClient.connect(); + return client; + } catch (error) { + const { message } = error; + if (message && (message.match(/timed out after/) || message.match(/ENOTFOUND/))) { + throw new MongoRuntimeError( + 'Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn', + { cause: error } + ); + } + throw error; + } + } + + /** + * Cleans up the `_mongocryptdClient`, if present. + */ + async teardown(force: boolean): Promise { + await this._mongocryptdClient?.close(force); + } + + /** + * Encrypt a command for a given namespace. + */ + async encrypt( + ns: string, + cmd: Document, + options: CommandOptions = {} + ): Promise { + if (this._bypassEncryption) { + // If `bypassAutoEncryption` has been specified, don't encrypt + return cmd; + } + + const commandBuffer = Buffer.isBuffer(cmd) ? cmd : serialize(cmd, options); + + const context = this._mongocrypt.makeEncryptionContext( + MongoDBCollectionNamespace.fromString(ns).db, + commandBuffer + ); + + context.id = this._contextCounter++; + context.ns = ns; + context.document = cmd; + + const stateMachine = new StateMachine({ + promoteValues: false, + promoteLongs: false, + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + return stateMachine.execute(this, context); + } + + /** + * Decrypt a command response + */ + async decrypt(response: Uint8Array | Document, options: CommandOptions = {}): Promise { + const buffer = Buffer.isBuffer(response) ? response : serialize(response, options); + + const context = this._mongocrypt.makeDecryptionContext(buffer); + + context.id = this._contextCounter++; + + const stateMachine = new StateMachine({ + ...options, + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + + const decorateResult = this[kDecorateResult]; + const result = await stateMachine.execute(this, context); + if (decorateResult) { + decorateDecryptionResult(result, response); + } + return result; + } + + /** + * Ask the user for KMS credentials. + * + * This returns anything that looks like the kmsProviders original input + * option. It can be empty, and any provider specified here will override + * the original ones. + */ + async askForKMSCredentials(): Promise { + return refreshKMSCredentials(this._kmsProviders); + } + + /** + * Return the current libmongocrypt's CSFLE shared library version + * as `{ version: bigint, versionStr: string }`, or `null` if no CSFLE + * shared library was loaded. + */ + get cryptSharedLibVersionInfo(): { version: bigint; versionStr: string } | null { + return this._mongocrypt.cryptSharedLibVersionInfo; + } + + static get libmongocryptVersion(): string { + return AutoEncrypter.getMongoCrypt().libmongocryptVersion; + } +} + +/** + * Recurse through the (identically-shaped) `decrypted` and `original` + * objects and attach a `decryptedKeys` property on each sub-object that + * contained encrypted fields. Because we only call this on BSON responses, + * we do not need to worry about circular references. + * + * @internal + */ +function decorateDecryptionResult( + decrypted: Document & { [kDecoratedKeys]?: Array }, + original: Document, + isTopLevelDecorateCall = true +): void { + if (isTopLevelDecorateCall) { + // The original value could have been either a JS object or a BSON buffer + if (Buffer.isBuffer(original)) { + original = deserialize(original); + } + if (Buffer.isBuffer(decrypted)) { + throw new MongoRuntimeError('Expected result of decryption to be deserialized BSON object'); + } + } + + if (!decrypted || typeof decrypted !== 'object') return; + for (const k of Object.keys(decrypted)) { + const originalValue = original[k]; + + // An object was decrypted by libmongocrypt if and only if it was + // a BSON Binary object with subtype 6. + if (originalValue && originalValue._bsontype === 'Binary' && originalValue.sub_type === 6) { + if (!decrypted[kDecoratedKeys]) { + Object.defineProperty(decrypted, kDecoratedKeys, { + value: [], + configurable: true, + enumerable: false, + writable: false + }); + } + // this is defined in the preceding if-statement + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + decrypted[kDecoratedKeys]!.push(k); + // Do not recurse into this decrypted value. It could be a sub-document/array, + // in which case there is no original value associated with its subfields. + continue; + } + + decorateDecryptionResult(decrypted[k], originalValue, false); + } +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/client_encryption.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/client_encryption.ts new file mode 100644 index 00000000..dbd946ed --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/client_encryption.ts @@ -0,0 +1,984 @@ +import type { + ExplicitEncryptionContextOptions, + MongoCrypt, + MongoCryptConstructor, + MongoCryptOptions +} from 'mongodb-client-encryption'; + +import { type Binary, type Document, type Long, serialize, type UUID } from '../bson'; +import { type AnyBulkWriteOperation, type BulkWriteResult } from '../bulk/common'; +import { type ProxyOptions } from '../cmap/connection'; +import { type Collection } from '../collection'; +import { type FindCursor } from '../cursor/find_cursor'; +import { type Db } from '../db'; +import { getMongoDBClientEncryption } from '../deps'; +import { type MongoClient } from '../mongo_client'; +import { type Filter, type WithId } from '../mongo_types'; +import { type CreateCollectionOptions } from '../operations/create_collection'; +import { type DeleteResult } from '../operations/delete'; +import { MongoDBCollectionNamespace } from '../utils'; +import * as cryptoCallbacks from './crypto_callbacks'; +import { + MongoCryptCreateDataKeyError, + MongoCryptCreateEncryptedCollectionError, + MongoCryptInvalidArgumentError +} from './errors'; +import { + type ClientEncryptionDataKeyProvider, + type KMSProviders, + refreshKMSCredentials +} from './providers/index'; +import { type CSFLEKMSTlsOptions, StateMachine } from './state_machine'; + +/** + * @public + * The schema for a DataKey in the key vault collection. + */ +export interface DataKey { + _id: UUID; + version?: number; + keyAltNames?: string[]; + keyMaterial: Binary; + creationDate: Date; + updateDate: Date; + status: number; + masterKey: Document; +} + +/** + * @public + * The public interface for explicit in-use encryption + */ +export class ClientEncryption { + /** @internal */ + _client: MongoClient; + /** @internal */ + _keyVaultNamespace: string; + /** @internal */ + _keyVaultClient: MongoClient; + /** @internal */ + _proxyOptions: ProxyOptions; + /** @internal */ + _tlsOptions: CSFLEKMSTlsOptions; + /** @internal */ + _kmsProviders: KMSProviders; + + /** @internal */ + _mongoCrypt: MongoCrypt; + + /** @internal */ + static getMongoCrypt(): MongoCryptConstructor { + const encryption = getMongoDBClientEncryption(); + if ('kModuleError' in encryption) { + throw encryption.kModuleError; + } + return encryption.MongoCrypt; + } + + /** + * Create a new encryption instance + * + * @example + * ```ts + * new ClientEncryption(mongoClient, { + * keyVaultNamespace: 'client.encryption', + * kmsProviders: { + * local: { + * key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer + * } + * } + * }); + * ``` + * + * @example + * ```ts + * new ClientEncryption(mongoClient, { + * keyVaultNamespace: 'client.encryption', + * kmsProviders: { + * aws: { + * accessKeyId: AWS_ACCESS_KEY, + * secretAccessKey: AWS_SECRET_KEY + * } + * } + * }); + * ``` + */ + constructor(client: MongoClient, options: ClientEncryptionOptions) { + this._client = client; + this._proxyOptions = options.proxyOptions ?? {}; + this._tlsOptions = options.tlsOptions ?? {}; + this._kmsProviders = options.kmsProviders || {}; + + if (options.keyVaultNamespace == null) { + throw new MongoCryptInvalidArgumentError('Missing required option `keyVaultNamespace`'); + } + + const mongoCryptOptions: MongoCryptOptions = { + ...options, + cryptoCallbacks, + kmsProviders: !Buffer.isBuffer(this._kmsProviders) + ? (serialize(this._kmsProviders) as Buffer) + : this._kmsProviders + }; + + this._keyVaultNamespace = options.keyVaultNamespace; + this._keyVaultClient = options.keyVaultClient || client; + const MongoCrypt = ClientEncryption.getMongoCrypt(); + this._mongoCrypt = new MongoCrypt(mongoCryptOptions); + } + + /** + * Creates a data key used for explicit encryption and inserts it into the key vault namespace + * + * @example + * ```ts + * // Using async/await to create a local key + * const dataKeyId = await clientEncryption.createDataKey('local'); + * ``` + * + * @example + * ```ts + * // Using async/await to create an aws key + * const dataKeyId = await clientEncryption.createDataKey('aws', { + * masterKey: { + * region: 'us-east-1', + * key: 'xxxxxxxxxxxxxx' // CMK ARN here + * } + * }); + * ``` + * + * @example + * ```ts + * // Using async/await to create an aws key with a keyAltName + * const dataKeyId = await clientEncryption.createDataKey('aws', { + * masterKey: { + * region: 'us-east-1', + * key: 'xxxxxxxxxxxxxx' // CMK ARN here + * }, + * keyAltNames: [ 'mySpecialKey' ] + * }); + * ``` + */ + async createDataKey( + provider: ClientEncryptionDataKeyProvider, + options: ClientEncryptionCreateDataKeyProviderOptions = {} + ): Promise { + if (options.keyAltNames && !Array.isArray(options.keyAltNames)) { + throw new MongoCryptInvalidArgumentError( + `Option "keyAltNames" must be an array of strings, but was of type ${typeof options.keyAltNames}.` + ); + } + + let keyAltNames = undefined; + if (options.keyAltNames && options.keyAltNames.length > 0) { + keyAltNames = options.keyAltNames.map((keyAltName, i) => { + if (typeof keyAltName !== 'string') { + throw new MongoCryptInvalidArgumentError( + `Option "keyAltNames" must be an array of strings, but item at index ${i} was of type ${typeof keyAltName}` + ); + } + + return serialize({ keyAltName }); + }); + } + + let keyMaterial = undefined; + if (options.keyMaterial) { + keyMaterial = serialize({ keyMaterial: options.keyMaterial }); + } + + const dataKeyBson = serialize({ + provider, + ...options.masterKey + }); + + const context = this._mongoCrypt.makeDataKeyContext(dataKeyBson, { + keyAltNames, + keyMaterial + }); + + const stateMachine = new StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + + const dataKey = await stateMachine.execute(this, context); + + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + const { insertedId } = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .insertOne(dataKey, { writeConcern: { w: 'majority' } }); + + return insertedId; + } + + /** + * Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options. + * + * If no matches are found, then no bulk write is performed. + * + * @example + * ```ts + * // rewrapping all data data keys (using a filter that matches all documents) + * const filter = {}; + * + * const result = await clientEncryption.rewrapManyDataKey(filter); + * if (result.bulkWriteResult != null) { + * // keys were re-wrapped, results will be available in the bulkWrite object. + * } + * ``` + * + * @example + * ```ts + * // attempting to rewrap all data keys with no matches + * const filter = { _id: new Binary() } // assume _id matches no documents in the database + * const result = await clientEncryption.rewrapManyDataKey(filter); + * + * if (result.bulkWriteResult == null) { + * // no keys matched, `bulkWriteResult` does not exist on the result object + * } + * ``` + */ + async rewrapManyDataKey( + filter: Filter, + options: ClientEncryptionRewrapManyDataKeyProviderOptions + ): Promise<{ bulkWriteResult?: BulkWriteResult }> { + let keyEncryptionKeyBson = undefined; + if (options) { + const keyEncryptionKey = Object.assign({ provider: options.provider }, options.masterKey); + keyEncryptionKeyBson = serialize(keyEncryptionKey); + } + const filterBson = serialize(filter); + const context = this._mongoCrypt.makeRewrapManyDataKeyContext(filterBson, keyEncryptionKeyBson); + const stateMachine = new StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + + const { v: dataKeys } = await stateMachine.execute<{ v: DataKey[] }>(this, context); + if (dataKeys.length === 0) { + return {}; + } + + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + const replacements = dataKeys.map( + (key: DataKey): AnyBulkWriteOperation => ({ + updateOne: { + filter: { _id: key._id }, + update: { + $set: { + masterKey: key.masterKey, + keyMaterial: key.keyMaterial + }, + $currentDate: { + updateDate: true + } + } + } + }) + ); + + const result = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .bulkWrite(replacements, { + writeConcern: { w: 'majority' } + }); + + return { bulkWriteResult: result }; + } + + /** + * Deletes the key with the provided id from the keyvault, if it exists. + * + * @example + * ```ts + * // delete a key by _id + * const id = new Binary(); // id is a bson binary subtype 4 object + * const { deletedCount } = await clientEncryption.deleteKey(id); + * + * if (deletedCount != null && deletedCount > 0) { + * // successful deletion + * } + * ``` + * + */ + async deleteKey(_id: Binary): Promise { + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .deleteOne({ _id }, { writeConcern: { w: 'majority' } }); + } + + /** + * Finds all the keys currently stored in the keyvault. + * + * This method will not throw. + * + * @returns a FindCursor over all keys in the keyvault. + * @example + * ```ts + * // fetching all keys + * const keys = await clientEncryption.getKeys().toArray(); + * ``` + */ + getKeys(): FindCursor { + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .find({}, { readConcern: { level: 'majority' } }); + } + + /** + * Finds a key in the keyvault with the specified _id. + * + * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // getting a key by id + * const id = new Binary(); // id is a bson binary subtype 4 object + * const key = await clientEncryption.getKey(id); + * if (!key) { + * // key is null if there was no matching key + * } + * ``` + */ + async getKey(_id: Binary): Promise { + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOne({ _id }, { readConcern: { level: 'majority' } }); + } + + /** + * Finds a key in the keyvault which has the specified keyAltName. + * + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the keyAltName. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // get a key by alt name + * const keyAltName = 'keyAltName'; + * const key = await clientEncryption.getKeyByAltName(keyAltName); + * if (!key) { + * // key is null if there is no matching key + * } + * ``` + */ + async getKeyByAltName(keyAltName: string): Promise | null> { + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + return this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOne({ keyAltNames: keyAltName }, { readConcern: { level: 'majority' } }); + } + + /** + * Adds a keyAltName to a key identified by the provided _id. + * + * This method resolves to/returns the *old* key value (prior to adding the new altKeyName). + * + * @param _id - The id of the document to update. + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // adding an keyAltName to a data key + * const id = new Binary(); // id is a bson binary subtype 4 object + * const keyAltName = 'keyAltName'; + * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName); + * if (!oldKey) { + * // null is returned if there is no matching document with an id matching the supplied id + * } + * ``` + */ + async addKeyAltName(_id: Binary, keyAltName: string): Promise | null> { + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + const value = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOneAndUpdate( + { _id }, + { $addToSet: { keyAltNames: keyAltName } }, + { writeConcern: { w: 'majority' }, returnDocument: 'before' } + ); + + return value; + } + + /** + * Adds a keyAltName to a key identified by the provided _id. + * + * This method resolves to/returns the *old* key value (prior to removing the new altKeyName). + * + * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document. + * + * @param _id - The id of the document to update. + * @param keyAltName - a keyAltName to search for a key + * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents + * match the id. The promise rejects with an error if an error is thrown. + * @example + * ```ts + * // removing a key alt name from a data key + * const id = new Binary(); // id is a bson binary subtype 4 object + * const keyAltName = 'keyAltName'; + * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName); + * + * if (!oldKey) { + * // null is returned if there is no matching document with an id matching the supplied id + * } + * ``` + */ + async removeKeyAltName(_id: Binary, keyAltName: string): Promise | null> { + const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString( + this._keyVaultNamespace + ); + + const pipeline = [ + { + $set: { + keyAltNames: { + $cond: [ + { + $eq: ['$keyAltNames', [keyAltName]] + }, + '$$REMOVE', + { + $filter: { + input: '$keyAltNames', + cond: { + $ne: ['$$this', keyAltName] + } + } + } + ] + } + } + } + ]; + const value = await this._keyVaultClient + .db(dbName) + .collection(collectionName) + .findOneAndUpdate({ _id }, pipeline, { + writeConcern: { w: 'majority' }, + returnDocument: 'before' + }); + + return value; + } + + /** + * A convenience method for creating an encrypted collection. + * This method will create data keys for any encryptedFields that do not have a `keyId` defined + * and then create a new collection with the full set of encryptedFields. + * + * @param db - A Node.js driver Db object with which to create the collection + * @param name - The name of the collection to be created + * @param options - Options for createDataKey and for createCollection + * @returns created collection and generated encryptedFields + * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created. + * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created. + */ + async createEncryptedCollection( + db: Db, + name: string, + options: { + provider: ClientEncryptionDataKeyProvider; + createCollectionOptions: Omit & { + encryptedFields: Document; + }; + masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions; + } + ): Promise<{ collection: Collection; encryptedFields: Document }> { + const { + provider, + masterKey, + createCollectionOptions: { + encryptedFields: { ...encryptedFields }, + ...createCollectionOptions + } + } = options; + + if (Array.isArray(encryptedFields.fields)) { + const createDataKeyPromises = encryptedFields.fields.map(async field => + field == null || typeof field !== 'object' || field.keyId != null + ? field + : { + ...field, + keyId: await this.createDataKey(provider, { masterKey }) + } + ); + + const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises); + + encryptedFields.fields = createDataKeyResolutions.map((resolution, index) => + resolution.status === 'fulfilled' ? resolution.value : encryptedFields.fields[index] + ); + + const rejection = createDataKeyResolutions.find( + (result): result is PromiseRejectedResult => result.status === 'rejected' + ); + if (rejection != null) { + throw new MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason }); + } + } + + try { + const collection = await db.createCollection(name, { + ...createCollectionOptions, + encryptedFields + }); + return { collection, encryptedFields }; + } catch (cause) { + throw new MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause }); + } + } + + /** + * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must + * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. + * + * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON + * @param options - + * @returns a Promise that either resolves with the encrypted value, or rejects with an error. + * + * @example + * ```ts + * // Encryption with async/await api + * async function encryptMyData(value) { + * const keyId = await clientEncryption.createDataKey('local'); + * return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); + * } + * ``` + * + * @example + * ```ts + * // Encryption using a keyAltName + * async function encryptMyData(value) { + * await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' }); + * return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }); + * } + * ``` + */ + async encrypt(value: unknown, options: ClientEncryptionEncryptOptions): Promise { + return this._encrypt(value, false, options); + } + + /** + * Encrypts a Match Expression or Aggregate Expression to query a range index. + * + * Only supported when queryType is "rangePreview" and algorithm is "RangePreview". + * + * @experimental The Range algorithm is experimental only. It is not intended for production use. It is subject to breaking changes. + * + * @param expression - a BSON document of one of the following forms: + * 1. A Match Expression of this form: + * `{$and: [{: {$gt: }}, {: {$lt: }}]}` + * 2. An Aggregate Expression of this form: + * `{$and: [{$gt: [, ]}, {$lt: [, ]}]}` + * + * `$gt` may also be `$gte`. `$lt` may also be `$lte`. + * + * @param options - + * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error. + */ + async encryptExpression( + expression: Document, + options: ClientEncryptionEncryptOptions + ): Promise { + return this._encrypt(expression, true, options); + } + + /** + * Explicitly decrypt a provided encrypted value + * + * @param value - An encrypted value + * @returns a Promise that either resolves with the decrypted value, or rejects with an error + * + * @example + * ```ts + * // Decrypting value with async/await API + * async function decryptMyValue(value) { + * return clientEncryption.decrypt(value); + * } + * ``` + */ + async decrypt(value: Binary): Promise { + const valueBuffer = serialize({ v: value }); + const context = this._mongoCrypt.makeExplicitDecryptionContext(valueBuffer); + + const stateMachine = new StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + + const { v } = await stateMachine.execute<{ v: T }>(this, context); + + return v; + } + + /** + * @internal + * Ask the user for KMS credentials. + * + * This returns anything that looks like the kmsProviders original input + * option. It can be empty, and any provider specified here will override + * the original ones. + */ + async askForKMSCredentials(): Promise { + return refreshKMSCredentials(this._kmsProviders); + } + + static get libmongocryptVersion() { + return ClientEncryption.getMongoCrypt().libmongocryptVersion; + } + + /** + * @internal + * A helper that perform explicit encryption of values and expressions. + * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must + * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error. + * + * @param value - The value that you wish to encrypt. Must be of a type that can be serialized into BSON + * @param expressionMode - a boolean that indicates whether or not to encrypt the value as an expression + * @param options - options to pass to encrypt + * @returns the raw result of the call to stateMachine.execute(). When expressionMode is set to true, the return + * value will be a bson document. When false, the value will be a BSON Binary. + * + */ + private async _encrypt( + value: unknown, + expressionMode: boolean, + options: ClientEncryptionEncryptOptions + ): Promise { + const { algorithm, keyId, keyAltName, contentionFactor, queryType, rangeOptions } = options; + const contextOptions: ExplicitEncryptionContextOptions = { + expressionMode, + algorithm + }; + if (keyId) { + contextOptions.keyId = keyId.buffer; + } + if (keyAltName) { + if (keyId) { + throw new MongoCryptInvalidArgumentError( + `"options" cannot contain both "keyId" and "keyAltName"` + ); + } + if (typeof keyAltName !== 'string') { + throw new MongoCryptInvalidArgumentError( + `"options.keyAltName" must be of type string, but was of type ${typeof keyAltName}` + ); + } + + contextOptions.keyAltName = serialize({ keyAltName }); + } + if (typeof contentionFactor === 'number' || typeof contentionFactor === 'bigint') { + contextOptions.contentionFactor = contentionFactor; + } + if (typeof queryType === 'string') { + contextOptions.queryType = queryType; + } + + if (typeof rangeOptions === 'object') { + contextOptions.rangeOptions = serialize(rangeOptions); + } + + const valueBuffer = serialize({ v: value }); + const stateMachine = new StateMachine({ + proxyOptions: this._proxyOptions, + tlsOptions: this._tlsOptions + }); + const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions); + + const result = await stateMachine.execute<{ v: Binary }>(this, context); + return result.v; + } +} + +/** + * @public + * Options to provide when encrypting data. + */ +export interface ClientEncryptionEncryptOptions { + /** + * The algorithm to use for encryption. + */ + algorithm: + | 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' + | 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' + | 'Indexed' + | 'Unindexed' + | 'RangePreview'; + + /** + * The id of the Binary dataKey to use for encryption + */ + keyId?: Binary; + + /** + * A unique string name corresponding to an already existing dataKey. + */ + keyAltName?: string; + + /** The contention factor. */ + contentionFactor?: bigint | number; + + /** + * The query type supported. Only the queryType `equality` is stable. + * + * @experimental Public Technical Preview: The queryType `rangePreview` is experimental. + */ + queryType?: 'equality' | 'rangePreview'; + + /** @experimental Public Technical Preview: The index options for a Queryable Encryption field supporting "rangePreview" queries.*/ + rangeOptions?: RangeOptions; +} + +/** + * @public + * @experimental + */ +export interface ClientEncryptionRewrapManyDataKeyProviderOptions { + provider: ClientEncryptionDataKeyProvider; + masterKey?: + | AWSEncryptionKeyOptions + | AzureEncryptionKeyOptions + | GCPEncryptionKeyOptions + | undefined; +} + +/** + * @public + * Additional settings to provide when creating a new `ClientEncryption` instance. + */ +export interface ClientEncryptionOptions { + /** + * The namespace of the key vault, used to store encryption keys + */ + keyVaultNamespace: string; + + /** + * A MongoClient used to fetch keys from a key vault. Defaults to client. + */ + keyVaultClient?: MongoClient | undefined; + + /** + * Options for specific KMS providers to use + */ + kmsProviders?: KMSProviders; + + /** + * Options for specifying a Socks5 proxy to use for connecting to the KMS. + */ + proxyOptions?: ProxyOptions; + + /** + * TLS options for kms providers to use. + */ + tlsOptions?: CSFLEKMSTlsOptions; +} + +/** + * @public + * Configuration options for making an AWS encryption key + */ +export interface AWSEncryptionKeyOptions { + /** + * The AWS region of the KMS + */ + region: string; + + /** + * The Amazon Resource Name (ARN) to the AWS customer master key (CMK) + */ + key: string; + + /** + * An alternate host to send KMS requests to. May include port number. + */ + endpoint?: string | undefined; +} + +/** + * @public + * Configuration options for making an AWS encryption key + */ +export interface GCPEncryptionKeyOptions { + /** + * GCP project ID + */ + projectId: string; + + /** + * Location name (e.g. "global") + */ + location: string; + + /** + * Key ring name + */ + keyRing: string; + + /** + * Key name + */ + keyName: string; + + /** + * Key version + */ + keyVersion?: string | undefined; + + /** + * KMS URL, defaults to `https://www.googleapis.com/auth/cloudkms` + */ + endpoint?: string | undefined; +} + +/** + * @public + * Configuration options for making an Azure encryption key + */ +export interface AzureEncryptionKeyOptions { + /** + * Key name + */ + keyName: string; + + /** + * Key vault URL, typically `.vault.azure.net` + */ + keyVaultEndpoint: string; + + /** + * Key version + */ + keyVersion?: string | undefined; +} + +/** + * @public + * Options to provide when creating a new data key. + */ +export interface ClientEncryptionCreateDataKeyProviderOptions { + /** + * Identifies a new KMS-specific key used to encrypt the new data key + */ + masterKey?: + | AWSEncryptionKeyOptions + | AzureEncryptionKeyOptions + | GCPEncryptionKeyOptions + | undefined; + + /** + * An optional list of string alternate names used to reference a key. + * If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id. + */ + keyAltNames?: string[] | undefined; + + /** @experimental */ + keyMaterial?: Buffer | Binary; +} + +/** + * @public + * @experimental + */ +export interface ClientEncryptionRewrapManyDataKeyProviderOptions { + provider: ClientEncryptionDataKeyProvider; + masterKey?: + | AWSEncryptionKeyOptions + | AzureEncryptionKeyOptions + | GCPEncryptionKeyOptions + | undefined; +} + +/** + * @public + * @experimental + */ +export interface ClientEncryptionRewrapManyDataKeyResult { + /** The result of rewrapping data keys. If unset, no keys matched the filter. */ + bulkWriteResult?: BulkWriteResult; +} + +/** + * @public + * RangeOptions specifies index options for a Queryable Encryption field supporting "rangePreview" queries. + * min, max, sparsity, and range must match the values set in the encryptedFields of the destination collection. + * For double and decimal128, min/max/precision must all be set, or all be unset. + */ +export interface RangeOptions { + min?: any; + max?: any; + sparsity: Long; + precision?: number; +} + +/** + * @public + * Options to provide when encrypting data. + */ +export interface ClientEncryptionEncryptOptions { + /** + * The algorithm to use for encryption. + */ + algorithm: + | 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' + | 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' + | 'Indexed' + | 'Unindexed' + | 'RangePreview'; + + /** + * The id of the Binary dataKey to use for encryption + */ + keyId?: Binary; + + /** + * A unique string name corresponding to an already existing dataKey. + */ + keyAltName?: string; + + /** The contention factor. */ + contentionFactor?: bigint | number; + + /** + * The query type supported. Only the queryType `equality` is stable. + * + * @experimental Public Technical Preview: The queryType `rangePreview` is experimental. + */ + queryType?: 'equality' | 'rangePreview'; + + /** @experimental Public Technical Preview: The index options for a Queryable Encryption field supporting "rangePreview" queries.*/ + rangeOptions?: RangeOptions; +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/crypto_callbacks.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/crypto_callbacks.ts new file mode 100644 index 00000000..1e2f1f7f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/crypto_callbacks.ts @@ -0,0 +1,87 @@ +import * as crypto from 'crypto'; + +type AES256Callback = (key: Buffer, iv: Buffer, input: Buffer, output: Buffer) => number | Error; + +export function makeAES256Hook( + method: 'createCipheriv' | 'createDecipheriv', + mode: 'aes-256-cbc' | 'aes-256-ctr' +): AES256Callback { + return function (key: Buffer, iv: Buffer, input: Buffer, output: Buffer): number | Error { + let result; + + try { + const cipher = crypto[method](mode, key, iv); + cipher.setAutoPadding(false); + result = cipher.update(input); + const final = cipher.final(); + if (final.length > 0) { + result = Buffer.concat([result, final]); + } + } catch (e) { + return e; + } + + result.copy(output); + return result.length; + }; +} + +export function randomHook(buffer: Buffer, count: number): number | Error { + try { + crypto.randomFillSync(buffer, 0, count); + } catch (e) { + return e; + } + return count; +} + +export function sha256Hook(input: Buffer, output: Buffer): number | Error { + let result; + try { + result = crypto.createHash('sha256').update(input).digest(); + } catch (e) { + return e; + } + + result.copy(output); + return result.length; +} + +type HMACHook = (key: Buffer, input: Buffer, output: Buffer) => number | Error; +export function makeHmacHook(algorithm: 'sha512' | 'sha256'): HMACHook { + return (key: Buffer, input: Buffer, output: Buffer): number | Error => { + let result; + try { + result = crypto.createHmac(algorithm, key).update(input).digest(); + } catch (e) { + return e; + } + + result.copy(output); + return result.length; + }; +} + +export function signRsaSha256Hook(key: Buffer, input: Buffer, output: Buffer): number | Error { + let result; + try { + const signer = crypto.createSign('sha256WithRSAEncryption'); + const privateKey = Buffer.from( + `-----BEGIN PRIVATE KEY-----\n${key.toString('base64')}\n-----END PRIVATE KEY-----\n` + ); + + result = signer.update(input).end().sign(privateKey); + } catch (e) { + return e; + } + + result.copy(output); + return result.length; +} + +export const aes256CbcEncryptHook = makeAES256Hook('createCipheriv', 'aes-256-cbc'); +export const aes256CbcDecryptHook = makeAES256Hook('createDecipheriv', 'aes-256-cbc'); +export const aes256CtrEncryptHook = makeAES256Hook('createCipheriv', 'aes-256-ctr'); +export const aes256CtrDecryptHook = makeAES256Hook('createDecipheriv', 'aes-256-ctr'); +export const hmacSha512Hook = makeHmacHook('sha512'); +export const hmacSha256Hook = makeHmacHook('sha256'); diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/errors.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/errors.ts new file mode 100644 index 00000000..7ab70748 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/errors.ts @@ -0,0 +1,141 @@ +import { type Document } from '../bson'; +import { MongoError } from '../error'; + +/** + * @public + * An error indicating that something went wrong specifically with MongoDB Client Encryption + */ +export class MongoCryptError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options: { cause?: Error } = {}) { + super(message, options); + } + + override get name() { + return 'MongoCryptError'; + } +} + +/** + * @public + * + * An error indicating an invalid argument was provided to an encryption API. + */ +export class MongoCryptInvalidArgumentError extends MongoCryptError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name() { + return 'MongoCryptInvalidArgumentError'; + } +} +/** + * @public + * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create data keys + */ +export class MongoCryptCreateDataKeyError extends MongoCryptError { + encryptedFields: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(encryptedFields: Document, { cause }: { cause: Error }) { + super(`Unable to complete creating data keys: ${cause.message}`, { cause }); + this.encryptedFields = encryptedFields; + } + + override get name() { + return 'MongoCryptCreateDataKeyError'; + } +} + +/** + * @public + * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create a collection + */ +export class MongoCryptCreateEncryptedCollectionError extends MongoCryptError { + encryptedFields: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(encryptedFields: Document, { cause }: { cause: Error }) { + super(`Unable to create collection: ${cause.message}`, { cause }); + this.encryptedFields = encryptedFields; + } + + override get name() { + return 'MongoCryptCreateEncryptedCollectionError'; + } +} + +/** + * @public + * An error indicating that mongodb-client-encryption failed to auto-refresh Azure KMS credentials. + */ +export class MongoCryptAzureKMSRequestError extends MongoCryptError { + /** The body of the http response that failed, if present. */ + body?: Document; + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, body?: Document) { + super(message); + this.body = body; + } + + override get name(): string { + return 'MongoCryptAzureKMSRequestError'; + } +} + +/** @public */ +export class MongoCryptKMSRequestNetworkTimeoutError extends MongoCryptError { + override get name(): string { + return 'MongoCryptKMSRequestNetworkTimeoutError'; + } +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/mongocryptd_manager.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/mongocryptd_manager.ts new file mode 100644 index 00000000..499f2aab --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/mongocryptd_manager.ts @@ -0,0 +1,96 @@ +import type { ChildProcess } from 'child_process'; + +import { MongoNetworkTimeoutError } from '../error'; +import { type AutoEncryptionExtraOptions } from './auto_encrypter'; + +/** + * @internal + * An internal class that handles spawning a mongocryptd. + */ +export class MongocryptdManager { + static DEFAULT_MONGOCRYPTD_URI = 'mongodb://localhost:27020'; + + uri: string; + bypassSpawn: boolean; + spawnPath: string; + spawnArgs: Array; + _child?: ChildProcess; + + constructor(extraOptions: AutoEncryptionExtraOptions = {}) { + this.uri = + typeof extraOptions.mongocryptdURI === 'string' && extraOptions.mongocryptdURI.length > 0 + ? extraOptions.mongocryptdURI + : MongocryptdManager.DEFAULT_MONGOCRYPTD_URI; + + this.bypassSpawn = !!extraOptions.mongocryptdBypassSpawn; + + this.spawnPath = extraOptions.mongocryptdSpawnPath || ''; + this.spawnArgs = []; + if (Array.isArray(extraOptions.mongocryptdSpawnArgs)) { + this.spawnArgs = this.spawnArgs.concat(extraOptions.mongocryptdSpawnArgs); + } + if ( + this.spawnArgs + .filter(arg => typeof arg === 'string') + .every(arg => arg.indexOf('--idleShutdownTimeoutSecs') < 0) + ) { + this.spawnArgs.push('--idleShutdownTimeoutSecs', '60'); + } + } + + /** + * Will check to see if a mongocryptd is up. If it is not up, it will attempt + * to spawn a mongocryptd in a detached process, and then wait for it to be up. + */ + async spawn(): Promise { + const cmdName = this.spawnPath || 'mongocryptd'; + + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { spawn } = require('child_process') as typeof import('child_process'); + + // Spawned with stdio: ignore and detached: true + // to ensure child can outlive parent. + this._child = spawn(cmdName, this.spawnArgs, { + stdio: 'ignore', + detached: true + }); + + this._child.on('error', () => { + // From the FLE spec: + // "The stdout and stderr of the spawned process MUST not be exposed in the driver + // (e.g. redirect to /dev/null). Users can pass the argument --logpath to + // extraOptions.mongocryptdSpawnArgs if they need to inspect mongocryptd logs. + // If spawning is necessary, the driver MUST spawn mongocryptd whenever server + // selection on the MongoClient to mongocryptd fails. If the MongoClient fails to + // connect after spawning, the server selection error is propagated to the user." + // The AutoEncrypter and MongoCryptdManager should work together to spawn + // mongocryptd whenever necessary. Additionally, the `mongocryptd` intentionally + // shuts down after 60s and gets respawned when necessary. We rely on server + // selection timeouts when connecting to the `mongocryptd` to inform users that something + // has been configured incorrectly. For those reasons, we suppress stderr from + // the `mongocryptd` process and immediately unref the process. + }); + + // unref child to remove handle from event loop + this._child.unref(); + } + + /** + * @returns the result of `fn` or rejects with an error. + */ + async withRespawn(fn: () => Promise): ReturnType { + try { + const result = await fn(); + return result; + } catch (err) { + // If we are not bypassing spawning, then we should retry once on a MongoTimeoutError (server selection error) + const shouldSpawn = err instanceof MongoNetworkTimeoutError && !this.bypassSpawn; + if (!shouldSpawn) { + throw err; + } + } + await this.spawn(); + const result = await fn(); + return result; + } +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/providers/aws.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/aws.ts new file mode 100644 index 00000000..64aa9f0a --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/aws.ts @@ -0,0 +1,20 @@ +import { getAwsCredentialProvider } from '../../deps'; +import { type KMSProviders } from '.'; + +/** + * @internal + */ +export async function loadAWSCredentials(kmsProviders: KMSProviders): Promise { + const credentialProvider = getAwsCredentialProvider(); + + if ('kModuleError' in credentialProvider) { + return kmsProviders; + } + + const { fromNodeProviderChain } = credentialProvider; + const provider = fromNodeProviderChain(); + // The state machine is the only place calling this so it will + // catch if there is a rejection here. + const aws = await provider(); + return { ...kmsProviders, aws }; +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/providers/azure.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/azure.ts new file mode 100644 index 00000000..53536902 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/azure.ts @@ -0,0 +1,168 @@ +import { type Document } from '../../bson'; +import { MongoCryptAzureKMSRequestError, MongoCryptKMSRequestNetworkTimeoutError } from '../errors'; +import { type KMSProviders } from './index'; +import { get } from './utils'; + +const MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS = 6000; + +/** + * The access token that libmongocrypt expects for Azure kms. + */ +interface AccessToken { + accessToken: string; +} + +/** + * The response from the azure idms endpoint, including the `expiresOnTimestamp`. + * `expiresOnTimestamp` is needed for caching. + */ +interface AzureTokenCacheEntry extends AccessToken { + accessToken: string; + expiresOnTimestamp: number; +} + +/** + * @internal + */ +export class AzureCredentialCache { + cachedToken: AzureTokenCacheEntry | null = null; + + async getToken(): Promise { + if (this.cachedToken == null || this.needsRefresh(this.cachedToken)) { + this.cachedToken = await this._getToken(); + } + + return { accessToken: this.cachedToken.accessToken }; + } + + needsRefresh(token: AzureTokenCacheEntry): boolean { + const timeUntilExpirationMS = token.expiresOnTimestamp - Date.now(); + return timeUntilExpirationMS <= MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS; + } + + /** + * exposed for testing + */ + resetCache() { + this.cachedToken = null; + } + + /** + * exposed for testing + */ + _getToken(): Promise { + return fetchAzureKMSToken(); + } +} + +/** @internal */ +export const tokenCache = new AzureCredentialCache(); + +/** @internal */ +async function parseResponse(response: { + body: string; + status?: number; +}): Promise { + const { status, body: rawBody } = response; + + const body: { expires_in?: number; access_token?: string } = (() => { + try { + return JSON.parse(rawBody); + } catch { + throw new MongoCryptAzureKMSRequestError('Malformed JSON body in GET request.'); + } + })(); + + if (status !== 200) { + throw new MongoCryptAzureKMSRequestError('Unable to complete request.', body); + } + + if (!body.access_token) { + throw new MongoCryptAzureKMSRequestError( + 'Malformed response body - missing field `access_token`.' + ); + } + + if (!body.expires_in) { + throw new MongoCryptAzureKMSRequestError( + 'Malformed response body - missing field `expires_in`.' + ); + } + + const expiresInMS = Number(body.expires_in) * 1000; + if (Number.isNaN(expiresInMS)) { + throw new MongoCryptAzureKMSRequestError( + 'Malformed response body - unable to parse int from `expires_in` field.' + ); + } + + return { + accessToken: body.access_token, + expiresOnTimestamp: Date.now() + expiresInMS + }; +} + +/** + * @internal + * + * exposed for CSFLE + * [prose test 18](https://github.com/mongodb/specifications/tree/master/source/client-side-encryption/tests#azure-imds-credentials) + */ +export interface AzureKMSRequestOptions { + headers?: Document; + url?: URL | string; +} + +/** + * @internal + * + * parses any options provided by prose tests to `fetchAzureKMSToken` and merges them with + * the default values for headers and the request url. + */ +export function prepareRequest(options: AzureKMSRequestOptions): { + headers: Document; + url: URL; +} { + const url = new URL( + options.url?.toString() ?? 'http://169.254.169.254/metadata/identity/oauth2/token' + ); + + url.searchParams.append('api-version', '2018-02-01'); + url.searchParams.append('resource', 'https://vault.azure.net'); + + const headers = { ...options.headers, 'Content-Type': 'application/json', Metadata: true }; + return { headers, url }; +} + +/** + * @internal + * + * `AzureKMSRequestOptions` allows prose tests to modify the http request sent to the idms + * servers. This is required to simulate different server conditions. No options are expected to + * be set outside of tests. + * + * exposed for CSFLE + * [prose test 18](https://github.com/mongodb/specifications/tree/master/source/client-side-encryption/tests#azure-imds-credentials) + */ +export async function fetchAzureKMSToken( + options: AzureKMSRequestOptions = {} +): Promise { + const { headers, url } = prepareRequest(options); + const response = await get(url, { headers }).catch(error => { + if (error instanceof MongoCryptKMSRequestNetworkTimeoutError) { + throw new MongoCryptAzureKMSRequestError(`[Azure KMS] ${error.message}`); + } + throw error; + }); + return parseResponse(response); +} + +/** + * @internal + * + * @throws Will reject with a `MongoCryptError` if the http request fails or the http response is malformed. + */ +export async function loadAzureCredentials(kmsProviders: KMSProviders): Promise { + const azure = await tokenCache.getToken(); + return { ...kmsProviders, azure }; +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/providers/gcp.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/gcp.ts new file mode 100644 index 00000000..1415d216 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/gcp.ts @@ -0,0 +1,16 @@ +import { getGcpMetadata } from '../../deps'; +import { type KMSProviders } from '.'; + +/** @internal */ +export async function loadGCPCredentials(kmsProviders: KMSProviders): Promise { + const gcpMetadata = getGcpMetadata(); + + if ('kModuleError' in gcpMetadata) { + return kmsProviders; + } + + const { access_token: accessToken } = await gcpMetadata.instance<{ access_token: string }>({ + property: 'service-accounts/default/token' + }); + return { ...kmsProviders, gcp: { accessToken } }; +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/providers/index.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/index.ts new file mode 100644 index 00000000..fb83e7b9 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/index.ts @@ -0,0 +1,168 @@ +import { loadAWSCredentials } from './aws'; +import { loadAzureCredentials } from './azure'; +import { loadGCPCredentials } from './gcp'; + +/** + * @public + */ +export type ClientEncryptionDataKeyProvider = 'aws' | 'azure' | 'gcp' | 'local' | 'kmip'; + +/** + * @public + * Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. + */ +export interface KMSProviders { + /** + * Configuration options for using 'aws' as your KMS provider + */ + aws?: + | { + /** + * The access key used for the AWS KMS provider + */ + accessKeyId: string; + + /** + * The secret access key used for the AWS KMS provider + */ + secretAccessKey: string; + + /** + * An optional AWS session token that will be used as the + * X-Amz-Security-Token header for AWS requests. + */ + sessionToken?: string; + } + | Record; + + /** + * Configuration options for using 'local' as your KMS provider + */ + local?: { + /** + * The master key used to encrypt/decrypt data keys. + * A 96-byte long Buffer or base64 encoded string. + */ + key: Buffer | string; + }; + + /** + * Configuration options for using 'kmip' as your KMS provider + */ + kmip?: { + /** + * The output endpoint string. + * The endpoint consists of a hostname and port separated by a colon. + * E.g. "example.com:123". A port is always present. + */ + endpoint?: string; + }; + + /** + * Configuration options for using 'azure' as your KMS provider + */ + azure?: + | { + /** + * The tenant ID identifies the organization for the account + */ + tenantId: string; + + /** + * The client ID to authenticate a registered application + */ + clientId: string; + + /** + * The client secret to authenticate a registered application + */ + clientSecret: string; + + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * This is optional, and only needed if customer is using a non-commercial Azure instance + * (e.g. a government or China account, which use different URLs). + * Defaults to "login.microsoftonline.com" + */ + identityPlatformEndpoint?: string | undefined; + } + | { + /** + * If present, an access token to authenticate with Azure. + */ + accessToken: string; + } + | Record; + + /** + * Configuration options for using 'gcp' as your KMS provider + */ + gcp?: + | { + /** + * The service account email to authenticate + */ + email: string; + + /** + * A PKCS#8 encrypted key. This can either be a base64 string or a binary representation + */ + privateKey: string | Buffer; + + /** + * If present, a host with optional port. E.g. "example.com" or "example.com:443". + * Defaults to "oauth2.googleapis.com" + */ + endpoint?: string | undefined; + } + | { + /** + * If present, an access token to authenticate with GCP. + */ + accessToken: string; + } + | Record; +} + +/** + * Auto credential fetching should only occur when the provider is defined on the kmsProviders map + * and the settings are an empty object. + * + * This is distinct from a nullish provider key. + * + * @internal - exposed for testing purposes only + */ +export function isEmptyCredentials( + providerName: ClientEncryptionDataKeyProvider, + kmsProviders: KMSProviders +): boolean { + const provider = kmsProviders[providerName]; + if (provider == null) { + return false; + } + return typeof provider === 'object' && Object.keys(provider).length === 0; +} + +/** + * Load cloud provider credentials for the user provided KMS providers. + * Credentials will only attempt to get loaded if they do not exist + * and no existing credentials will get overwritten. + * + * @internal + */ +export async function refreshKMSCredentials(kmsProviders: KMSProviders): Promise { + let finalKMSProviders = kmsProviders; + + if (isEmptyCredentials('aws', kmsProviders)) { + finalKMSProviders = await loadAWSCredentials(finalKMSProviders); + } + + if (isEmptyCredentials('gcp', kmsProviders)) { + finalKMSProviders = await loadGCPCredentials(finalKMSProviders); + } + + if (isEmptyCredentials('azure', kmsProviders)) { + finalKMSProviders = await loadAzureCredentials(finalKMSProviders); + } + return finalKMSProviders; +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/providers/utils.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/utils.ts new file mode 100644 index 00000000..8d5362c6 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/providers/utils.ts @@ -0,0 +1,37 @@ +import * as http from 'http'; +import { clearTimeout, setTimeout } from 'timers'; + +import { MongoCryptKMSRequestNetworkTimeoutError } from '../errors'; + +/** + * @internal + */ +export function get( + url: URL | string, + options: http.RequestOptions = {} +): Promise<{ body: string; status: number | undefined }> { + return new Promise((resolve, reject) => { + /* eslint-disable prefer-const */ + let timeoutId: NodeJS.Timeout; + const request = http + .get(url, options, response => { + response.setEncoding('utf8'); + let body = ''; + response.on('data', chunk => (body += chunk)); + response.on('end', () => { + clearTimeout(timeoutId); + resolve({ status: response.statusCode, body }); + }); + }) + .on('error', error => { + clearTimeout(timeoutId); + reject(error); + }) + .end(); + timeoutId = setTimeout(() => { + request.destroy( + new MongoCryptKMSRequestNetworkTimeoutError(`request timed out after 10 seconds`) + ); + }, 10000); + }); +} diff --git a/nodejs/node_modules/mongodb/src/client-side-encryption/state_machine.ts b/nodejs/node_modules/mongodb/src/client-side-encryption/state_machine.ts new file mode 100644 index 00000000..a4b2379f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/client-side-encryption/state_machine.ts @@ -0,0 +1,531 @@ +import * as fs from 'fs/promises'; +import { type MongoCryptContext, type MongoCryptKMSRequest } from 'mongodb-client-encryption'; +import * as net from 'net'; +import * as tls from 'tls'; + +import { + type BSONSerializeOptions, + deserialize, + type Document, + pluckBSONSerializeOptions, + serialize +} from '../bson'; +import { type ProxyOptions } from '../cmap/connection'; +import { getSocks, type SocksLib } from '../deps'; +import { type MongoClient, type MongoClientOptions } from '../mongo_client'; +import { BufferPool, MongoDBCollectionNamespace, promiseWithResolvers } from '../utils'; +import { type DataKey } from './client_encryption'; +import { MongoCryptError } from './errors'; +import { type MongocryptdManager } from './mongocryptd_manager'; +import { type ClientEncryptionDataKeyProvider, type KMSProviders } from './providers'; + +let socks: SocksLib | null = null; +function loadSocks(): SocksLib { + if (socks == null) { + const socksImport = getSocks(); + if ('kModuleError' in socksImport) { + throw socksImport.kModuleError; + } + socks = socksImport; + } + return socks; +} + +// libmongocrypt states +const MONGOCRYPT_CTX_ERROR = 0; +const MONGOCRYPT_CTX_NEED_MONGO_COLLINFO = 1; +const MONGOCRYPT_CTX_NEED_MONGO_MARKINGS = 2; +const MONGOCRYPT_CTX_NEED_MONGO_KEYS = 3; +const MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS = 7; +const MONGOCRYPT_CTX_NEED_KMS = 4; +const MONGOCRYPT_CTX_READY = 5; +const MONGOCRYPT_CTX_DONE = 6; + +const HTTPS_PORT = 443; + +const stateToString = new Map([ + [MONGOCRYPT_CTX_ERROR, 'MONGOCRYPT_CTX_ERROR'], + [MONGOCRYPT_CTX_NEED_MONGO_COLLINFO, 'MONGOCRYPT_CTX_NEED_MONGO_COLLINFO'], + [MONGOCRYPT_CTX_NEED_MONGO_MARKINGS, 'MONGOCRYPT_CTX_NEED_MONGO_MARKINGS'], + [MONGOCRYPT_CTX_NEED_MONGO_KEYS, 'MONGOCRYPT_CTX_NEED_MONGO_KEYS'], + [MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS, 'MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS'], + [MONGOCRYPT_CTX_NEED_KMS, 'MONGOCRYPT_CTX_NEED_KMS'], + [MONGOCRYPT_CTX_READY, 'MONGOCRYPT_CTX_READY'], + [MONGOCRYPT_CTX_DONE, 'MONGOCRYPT_CTX_DONE'] +]); + +const INSECURE_TLS_OPTIONS = [ + 'tlsInsecure', + 'tlsAllowInvalidCertificates', + 'tlsAllowInvalidHostnames', + + // These options are disallowed by the spec, so we explicitly filter them out if provided, even + // though the StateMachine does not declare support for these options. + 'tlsDisableOCSPEndpointCheck', + 'tlsDisableCertificateRevocationCheck' +]; + +/** + * Helper function for logging. Enabled by setting the environment flag MONGODB_CRYPT_DEBUG. + * @param msg - Anything you want to be logged. + */ +function debug(msg: unknown) { + if (process.env.MONGODB_CRYPT_DEBUG) { + // eslint-disable-next-line no-console + console.error(msg); + } +} + +declare module 'mongodb-client-encryption' { + // the properties added to `MongoCryptContext` here are only used for the `StateMachine`'s + // execute method and are not part of the C++ bindings. + interface MongoCryptContext { + id: number; + document: Document; + ns: string; + } +} + +/** + * @public + * + * TLS options to use when connecting. The spec specifically calls out which insecure + * tls options are not allowed: + * + * - tlsAllowInvalidCertificates + * - tlsAllowInvalidHostnames + * - tlsInsecure + * + * These options are not included in the type, and are ignored if provided. + */ +export type ClientEncryptionTlsOptions = Pick< + MongoClientOptions, + 'tlsCAFile' | 'tlsCertificateKeyFile' | 'tlsCertificateKeyFilePassword' +>; + +/** @public */ +export type CSFLEKMSTlsOptions = { + aws?: ClientEncryptionTlsOptions; + gcp?: ClientEncryptionTlsOptions; + kmip?: ClientEncryptionTlsOptions; + local?: ClientEncryptionTlsOptions; + azure?: ClientEncryptionTlsOptions; +}; + +/** + * @internal + * + * An interface representing an object that can be passed to the `StateMachine.execute` method. + * + * Not all properties are required for all operations. + */ +export interface StateMachineExecutable { + _keyVaultNamespace: string; + _keyVaultClient: MongoClient; + askForKMSCredentials: () => Promise; + + /** only used for auto encryption */ + _metaDataClient?: MongoClient; + /** only used for auto encryption */ + _mongocryptdClient?: MongoClient; + /** only used for auto encryption */ + _mongocryptdManager?: MongocryptdManager; +} + +export type StateMachineOptions = { + /** socks5 proxy options, if set. */ + proxyOptions: ProxyOptions; + + /** TLS options for KMS requests, if set. */ + tlsOptions: CSFLEKMSTlsOptions; +} & Pick; + +/** + * @internal + * An internal class that executes across a MongoCryptContext until either + * a finishing state or an error is reached. Do not instantiate directly. + */ +export class StateMachine { + constructor( + private options: StateMachineOptions, + private bsonOptions = pluckBSONSerializeOptions(options) + ) {} + + /** + * Executes the state machine according to the specification + */ + async execute( + executor: StateMachineExecutable, + context: MongoCryptContext + ): Promise { + const keyVaultNamespace = executor._keyVaultNamespace; + const keyVaultClient = executor._keyVaultClient; + const metaDataClient = executor._metaDataClient; + const mongocryptdClient = executor._mongocryptdClient; + const mongocryptdManager = executor._mongocryptdManager; + let result: T | null = null; + + while (context.state !== MONGOCRYPT_CTX_DONE && context.state !== MONGOCRYPT_CTX_ERROR) { + debug(`[context#${context.id}] ${stateToString.get(context.state) || context.state}`); + + switch (context.state) { + case MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: { + const filter = deserialize(context.nextMongoOperation()); + if (!metaDataClient) { + throw new MongoCryptError( + 'unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_COLLINFO but metadata client is undefined' + ); + } + const collInfo = await this.fetchCollectionInfo(metaDataClient, context.ns, filter); + + if (collInfo) { + context.addMongoOperationResponse(collInfo); + } + + context.finishMongoOperation(); + break; + } + + case MONGOCRYPT_CTX_NEED_MONGO_MARKINGS: { + const command = context.nextMongoOperation(); + if (!mongocryptdClient) { + throw new MongoCryptError( + 'unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined' + ); + } + + // When we are using the shared library, we don't have a mongocryptd manager. + const markedCommand: Uint8Array = mongocryptdManager + ? await mongocryptdManager.withRespawn( + this.markCommand.bind(this, mongocryptdClient, context.ns, command) + ) + : await this.markCommand(mongocryptdClient, context.ns, command); + + context.addMongoOperationResponse(markedCommand); + context.finishMongoOperation(); + break; + } + + case MONGOCRYPT_CTX_NEED_MONGO_KEYS: { + const filter = context.nextMongoOperation(); + const keys = await this.fetchKeys(keyVaultClient, keyVaultNamespace, filter); + + if (keys.length === 0) { + // This is kind of a hack. For `rewrapManyDataKey`, we have tests that + // guarantee that when there are no matching keys, `rewrapManyDataKey` returns + // nothing. We also have tests for auto encryption that guarantee for `encrypt` + // we return an error when there are no matching keys. This error is generated in + // subsequent iterations of the state machine. + // Some apis (`encrypt`) throw if there are no filter matches and others (`rewrapManyDataKey`) + // do not. We set the result manually here, and let the state machine continue. `libmongocrypt` + // will inform us if we need to error by setting the state to `MONGOCRYPT_CTX_ERROR` but + // otherwise we'll return `{ v: [] }`. + result = { v: [] } as any as T; + } + for await (const key of keys) { + context.addMongoOperationResponse(serialize(key)); + } + + context.finishMongoOperation(); + + break; + } + + case MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS: { + const kmsProviders = await executor.askForKMSCredentials(); + context.provideKMSProviders(serialize(kmsProviders)); + break; + } + + case MONGOCRYPT_CTX_NEED_KMS: { + const requests = Array.from(this.requests(context)); + await Promise.all(requests); + + context.finishKMSRequests(); + break; + } + + case MONGOCRYPT_CTX_READY: { + const finalizedContext = context.finalize(); + // @ts-expect-error finalize can change the state, check for error + if (context.state === MONGOCRYPT_CTX_ERROR) { + const message = context.status.message || 'Finalization error'; + throw new MongoCryptError(message); + } + result = deserialize(finalizedContext, this.options) as T; + break; + } + + default: + throw new MongoCryptError(`Unknown state: ${context.state}`); + } + } + + if (context.state === MONGOCRYPT_CTX_ERROR || result == null) { + const message = context.status.message; + if (!message) { + debug( + `unidentifiable error in MongoCrypt - received an error status from \`libmongocrypt\` but received no error message.` + ); + } + throw new MongoCryptError( + message ?? + 'unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message.' + ); + } + + return result; + } + + /** + * Handles the request to the KMS service. Exposed for testing purposes. Do not directly invoke. + * @param kmsContext - A C++ KMS context returned from the bindings + * @returns A promise that resolves when the KMS reply has be fully parsed + */ + async kmsRequest(request: MongoCryptKMSRequest): Promise { + const parsedUrl = request.endpoint.split(':'); + const port = parsedUrl[1] != null ? Number.parseInt(parsedUrl[1], 10) : HTTPS_PORT; + const options: tls.ConnectionOptions & { host: string; port: number } = { + host: parsedUrl[0], + servername: parsedUrl[0], + port + }; + const message = request.message; + const buffer = new BufferPool(); + + const netSocket: net.Socket = new net.Socket(); + let socket: tls.TLSSocket; + + function destroySockets() { + for (const sock of [socket, netSocket]) { + if (sock) { + sock.removeAllListeners(); + sock.destroy(); + } + } + } + + function ontimeout() { + return new MongoCryptError('KMS request timed out'); + } + + function onerror(cause: Error) { + return new MongoCryptError('KMS request failed', { cause }); + } + + function onclose() { + return new MongoCryptError('KMS request closed'); + } + + const tlsOptions = this.options.tlsOptions; + if (tlsOptions) { + const kmsProvider = request.kmsProvider as ClientEncryptionDataKeyProvider; + const providerTlsOptions = tlsOptions[kmsProvider]; + if (providerTlsOptions) { + const error = this.validateTlsOptions(kmsProvider, providerTlsOptions); + if (error) { + throw error; + } + try { + await this.setTlsOptions(providerTlsOptions, options); + } catch (err) { + throw onerror(err); + } + } + } + + const { + promise: willConnect, + reject: rejectOnNetSocketError, + resolve: resolveOnNetSocketConnect + } = promiseWithResolvers(); + netSocket + .once('timeout', () => rejectOnNetSocketError(ontimeout())) + .once('error', err => rejectOnNetSocketError(onerror(err))) + .once('close', () => rejectOnNetSocketError(onclose())) + .once('connect', () => resolveOnNetSocketConnect()); + + try { + if (this.options.proxyOptions && this.options.proxyOptions.proxyHost) { + netSocket.connect({ + host: this.options.proxyOptions.proxyHost, + port: this.options.proxyOptions.proxyPort || 1080 + }); + await willConnect; + + try { + socks ??= loadSocks(); + options.socket = ( + await socks.SocksClient.createConnection({ + existing_socket: netSocket, + command: 'connect', + destination: { host: options.host, port: options.port }, + proxy: { + // host and port are ignored because we pass existing_socket + host: 'iLoveJavaScript', + port: 0, + type: 5, + userId: this.options.proxyOptions.proxyUsername, + password: this.options.proxyOptions.proxyPassword + } + }) + ).socket; + } catch (err) { + throw onerror(err); + } + } + + socket = tls.connect(options, () => { + socket.write(message); + }); + + const { + promise: willResolveKmsRequest, + reject: rejectOnTlsSocketError, + resolve + } = promiseWithResolvers(); + socket + .once('timeout', () => rejectOnTlsSocketError(ontimeout())) + .once('error', err => rejectOnTlsSocketError(onerror(err))) + .once('close', () => rejectOnTlsSocketError(onclose())) + .on('data', data => { + buffer.append(data); + while (request.bytesNeeded > 0 && buffer.length) { + const bytesNeeded = Math.min(request.bytesNeeded, buffer.length); + request.addResponse(buffer.read(bytesNeeded)); + } + + if (request.bytesNeeded <= 0) { + resolve(); + } + }); + await willResolveKmsRequest; + } finally { + // There's no need for any more activity on this socket at this point. + destroySockets(); + } + } + + *requests(context: MongoCryptContext) { + for ( + let request = context.nextKMSRequest(); + request != null; + request = context.nextKMSRequest() + ) { + yield this.kmsRequest(request); + } + } + + /** + * Validates the provided TLS options are secure. + * + * @param kmsProvider - The KMS provider name. + * @param tlsOptions - The client TLS options for the provider. + * + * @returns An error if any option is invalid. + */ + validateTlsOptions( + kmsProvider: string, + tlsOptions: ClientEncryptionTlsOptions + ): MongoCryptError | void { + const tlsOptionNames = Object.keys(tlsOptions); + for (const option of INSECURE_TLS_OPTIONS) { + if (tlsOptionNames.includes(option)) { + return new MongoCryptError(`Insecure TLS options prohibited for ${kmsProvider}: ${option}`); + } + } + } + + /** + * Sets only the valid secure TLS options. + * + * @param tlsOptions - The client TLS options for the provider. + * @param options - The existing connection options. + */ + async setTlsOptions( + tlsOptions: ClientEncryptionTlsOptions, + options: tls.ConnectionOptions + ): Promise { + if (tlsOptions.tlsCertificateKeyFile) { + const cert = await fs.readFile(tlsOptions.tlsCertificateKeyFile); + options.cert = options.key = cert; + } + if (tlsOptions.tlsCAFile) { + options.ca = await fs.readFile(tlsOptions.tlsCAFile); + } + if (tlsOptions.tlsCertificateKeyFilePassword) { + options.passphrase = tlsOptions.tlsCertificateKeyFilePassword; + } + } + + /** + * Fetches collection info for a provided namespace, when libmongocrypt + * enters the `MONGOCRYPT_CTX_NEED_MONGO_COLLINFO` state. The result is + * used to inform libmongocrypt of the schema associated with this + * namespace. Exposed for testing purposes. Do not directly invoke. + * + * @param client - A MongoClient connected to the topology + * @param ns - The namespace to list collections from + * @param filter - A filter for the listCollections command + * @param callback - Invoked with the info of the requested collection, or with an error + */ + async fetchCollectionInfo( + client: MongoClient, + ns: string, + filter: Document + ): Promise { + const { db } = MongoDBCollectionNamespace.fromString(ns); + + const collections = await client + .db(db) + .listCollections(filter, { + promoteLongs: false, + promoteValues: false + }) + .toArray(); + + const info = collections.length > 0 ? serialize(collections[0]) : null; + return info; + } + + /** + * Calls to the mongocryptd to provide markings for a command. + * Exposed for testing purposes. Do not directly invoke. + * @param client - A MongoClient connected to a mongocryptd + * @param ns - The namespace (database.collection) the command is being executed on + * @param command - The command to execute. + * @param callback - Invoked with the serialized and marked bson command, or with an error + */ + async markCommand(client: MongoClient, ns: string, command: Uint8Array): Promise { + const options = { promoteLongs: false, promoteValues: false }; + const { db } = MongoDBCollectionNamespace.fromString(ns); + const rawCommand = deserialize(command, options); + + const response = await client.db(db).command(rawCommand, options); + + return serialize(response, this.bsonOptions); + } + + /** + * Requests keys from the keyVault collection on the topology. + * Exposed for testing purposes. Do not directly invoke. + * @param client - A MongoClient connected to the topology + * @param keyVaultNamespace - The namespace (database.collection) of the keyVault Collection + * @param filter - The filter for the find query against the keyVault Collection + * @param callback - Invoked with the found keys, or with an error + */ + fetchKeys( + client: MongoClient, + keyVaultNamespace: string, + filter: Uint8Array + ): Promise> { + const { db: dbName, collection: collectionName } = + MongoDBCollectionNamespace.fromString(keyVaultNamespace); + + return client + .db(dbName) + .collection(collectionName, { readConcern: { level: 'majority' } }) + .find(deserialize(filter)) + .toArray(); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/auth_provider.ts b/nodejs/node_modules/mongodb/src/cmap/auth/auth_provider.ts new file mode 100644 index 00000000..e40c791e --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/auth_provider.ts @@ -0,0 +1,77 @@ +import type { Document } from '../../bson'; +import { MongoRuntimeError } from '../../error'; +import type { HandshakeDocument } from '../connect'; +import type { Connection, ConnectionOptions } from '../connection'; +import type { MongoCredentials } from './mongo_credentials'; + +/** + * Context used during authentication + * @internal + */ +export class AuthContext { + /** The connection to authenticate */ + connection: Connection; + /** The credentials to use for authentication */ + credentials?: MongoCredentials; + /** If the context is for reauthentication. */ + reauthenticating = false; + /** The options passed to the `connect` method */ + options: ConnectionOptions; + + /** A response from an initial auth attempt, only some mechanisms use this (e.g, SCRAM) */ + response?: Document; + /** A random nonce generated for use in an authentication conversation */ + nonce?: Buffer; + + constructor( + connection: Connection, + credentials: MongoCredentials | undefined, + options: ConnectionOptions + ) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} + +/** + * Provider used during authentication. + * @internal + */ +export abstract class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + async prepare( + handshakeDoc: HandshakeDocument, + _authContext: AuthContext + ): Promise { + return handshakeDoc; + } + + /** + * Authenticate + * + * @param context - A shared context for authentication flow + */ + abstract auth(context: AuthContext): Promise; + + /** + * Reauthenticate. + * @param context - The shared auth context. + */ + async reauth(context: AuthContext): Promise { + if (context.reauthenticating) { + throw new MongoRuntimeError('Reauthentication already in progress.'); + } + try { + context.reauthenticating = true; + await this.auth(context); + } finally { + context.reauthenticating = false; + } + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/gssapi.ts b/nodejs/node_modules/mongodb/src/cmap/auth/gssapi.ts new file mode 100644 index 00000000..d1473c6c --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/gssapi.ts @@ -0,0 +1,204 @@ +import * as dns from 'dns'; + +import { getKerberos, type Kerberos, type KerberosClient } from '../../deps'; +import { MongoInvalidArgumentError, MongoMissingCredentialsError } from '../../error'; +import { ns } from '../../utils'; +import type { Connection } from '../connection'; +import { type AuthContext, AuthProvider } from './auth_provider'; + +/** @public */ +export const GSSAPICanonicalizationValue = Object.freeze({ + on: true, + off: false, + none: 'none', + forward: 'forward', + forwardAndReverse: 'forwardAndReverse' +} as const); + +/** @public */ +export type GSSAPICanonicalizationValue = + (typeof GSSAPICanonicalizationValue)[keyof typeof GSSAPICanonicalizationValue]; + +type MechanismProperties = { + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; +}; + +async function externalCommand( + connection: Connection, + command: ReturnType | ReturnType +): Promise<{ payload: string; conversationId: any }> { + return connection.command(ns('$external.$cmd'), command, undefined) as Promise<{ + payload: string; + conversationId: any; + }>; +} + +let krb: typeof Kerberos; + +export class GSSAPI extends AuthProvider { + override async auth(authContext: AuthContext): Promise { + const { connection, credentials } = authContext; + if (credentials == null) { + throw new MongoMissingCredentialsError('Credentials required for GSSAPI authentication'); + } + + const { username } = credentials; + + const client = await makeKerberosClient(authContext); + + const payload = await client.step(''); + + const saslStartResponse = await externalCommand(connection, saslStart(payload)); + + const negotiatedPayload = await negotiate(client, 10, saslStartResponse.payload); + + const saslContinueResponse = await externalCommand( + connection, + saslContinue(negotiatedPayload, saslStartResponse.conversationId) + ); + + const finalizePayload = await finalize(client, username, saslContinueResponse.payload); + + await externalCommand(connection, { + saslContinue: 1, + conversationId: saslContinueResponse.conversationId, + payload: finalizePayload + }); + } +} + +async function makeKerberosClient(authContext: AuthContext): Promise { + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + throw new MongoInvalidArgumentError( + 'Connection must have host and port and credentials defined.' + ); + } + + loadKrb(); + if ('kModuleError' in krb) { + throw krb['kModuleError']; + } + const { initializeClient } = krb; + + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties as MechanismProperties; + + const serviceName = mechanismProperties.SERVICE_NAME ?? 'mongodb'; + + const host = await performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties); + + const initOptions = {}; + if (password != null) { + // TODO(NODE-5139): These do not match the typescript options in initializeClient + Object.assign(initOptions, { user: username, password: password }); + } + + const spnHost = mechanismProperties.SERVICE_HOST ?? host; + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${spnHost}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + + return initializeClient(spn, initOptions); +} + +function saslStart(payload: string) { + return { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + } as const; +} + +function saslContinue(payload: string, conversationId: number) { + return { + saslContinue: 1, + conversationId, + payload + } as const; +} + +async function negotiate( + client: KerberosClient, + retries: number, + payload: string +): Promise { + try { + const response = await client.step(payload); + return response || ''; + } catch (error) { + if (retries === 0) { + // Retries exhausted, raise error + throw error; + } + // Adjust number of retries and call step again + return negotiate(client, retries - 1, payload); + } +} + +async function finalize(client: KerberosClient, user: string, payload: string): Promise { + // GSS Client Unwrap + const response = await client.unwrap(payload); + return client.wrap(response || '', { user }); +} + +export async function performGSSAPICanonicalizeHostName( + host: string, + mechanismProperties: MechanismProperties +): Promise { + const mode = mechanismProperties.CANONICALIZE_HOST_NAME; + if (!mode || mode === GSSAPICanonicalizationValue.none) { + return host; + } + + // If forward and reverse or true + if ( + mode === GSSAPICanonicalizationValue.on || + mode === GSSAPICanonicalizationValue.forwardAndReverse + ) { + // Perform the lookup of the ip address. + const { address } = await dns.promises.lookup(host); + + try { + // Perform a reverse ptr lookup on the ip address. + const results = await dns.promises.resolvePtr(address); + // If the ptr did not error but had no results, return the host. + return results.length > 0 ? results[0] : host; + } catch (error) { + // This can error as ptr records may not exist for all ips. In this case + // fallback to a cname lookup as dns.lookup() does not return the + // cname. + return resolveCname(host); + } + } else { + // The case for forward is just to resolve the cname as dns.lookup() + // will not return it. + return resolveCname(host); + } +} + +export async function resolveCname(host: string): Promise { + // Attempt to resolve the host name + try { + const results = await dns.promises.resolveCname(host); + // Get the first resolved host id + return results.length > 0 ? results[0] : host; + } catch { + return host; + } +} + +/** + * Load the Kerberos library. + */ +function loadKrb() { + if (!krb) { + krb = getKerberos(); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts new file mode 100644 index 00000000..c086afb4 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts @@ -0,0 +1,278 @@ +// Resolves the default auth mechanism according to +// Resolves the default auth mechanism according to +import type { Document } from '../../bson'; +import { + MongoAPIError, + MongoAzureError, + MongoInvalidArgumentError, + MongoMissingCredentialsError +} from '../../error'; +import { GSSAPICanonicalizationValue } from './gssapi'; +import type { OIDCRefreshFunction, OIDCRequestFunction } from './mongodb_oidc'; +import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from './providers'; + +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(hello: Document | null): AuthMechanism { + if (hello) { + // If hello contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(hello.saslSupportedMechs)) { + return hello.saslSupportedMechs.includes(AuthMechanism.MONGODB_SCRAM_SHA256) + ? AuthMechanism.MONGODB_SCRAM_SHA256 + : AuthMechanism.MONGODB_SCRAM_SHA1; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (hello.maxWireVersion >= 3) { + return AuthMechanism.MONGODB_SCRAM_SHA1; + } + } + + // Default for wireprotocol < 3 + return AuthMechanism.MONGODB_CR; +} + +const ALLOWED_PROVIDER_NAMES: AuthMechanismProperties['PROVIDER_NAME'][] = ['aws', 'azure']; +const ALLOWED_HOSTS_ERROR = 'Auth mechanism property ALLOWED_HOSTS must be an array of strings.'; + +/** @internal */ +export const DEFAULT_ALLOWED_HOSTS = [ + '*.mongodb.net', + '*.mongodb-dev.net', + '*.mongodbgov.net', + 'localhost', + '127.0.0.1', + '::1' +]; + +/** Error for when the token audience is missing in the environment. */ +const TOKEN_AUDIENCE_MISSING_ERROR = + 'TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.'; + +/** @public */ +export interface AuthMechanismProperties extends Document { + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + AWS_SESSION_TOKEN?: string; + /** @experimental */ + REQUEST_TOKEN_CALLBACK?: OIDCRequestFunction; + /** @experimental */ + REFRESH_TOKEN_CALLBACK?: OIDCRefreshFunction; + /** @experimental */ + PROVIDER_NAME?: 'aws' | 'azure'; + /** @experimental */ + ALLOWED_HOSTS?: string[]; + /** @experimental */ + TOKEN_AUDIENCE?: string; +} + +/** @public */ +export interface MongoCredentialsOptions { + username?: string; + password: string; + source: string; + db?: string; + mechanism?: AuthMechanism; + mechanismProperties: AuthMechanismProperties; +} + +/** + * A representation of the credentials used by MongoDB + * @public + */ +export class MongoCredentials { + /** The username used for authentication */ + readonly username: string; + /** The password used for authentication */ + readonly password: string; + /** The database that the user should authenticate against */ + readonly source: string; + /** The method used to authenticate */ + readonly mechanism: AuthMechanism; + /** Special properties used by some types of auth mechanisms */ + readonly mechanismProperties: AuthMechanismProperties; + + constructor(options: MongoCredentialsOptions) { + this.username = options.username ?? ''; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + + if (this.mechanism.match(/MONGODB-AWS/i)) { + 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 = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } + } + + if (this.mechanism === AuthMechanism.MONGODB_OIDC && !this.mechanismProperties.ALLOWED_HOSTS) { + this.mechanismProperties = { + ...this.mechanismProperties, + ALLOWED_HOSTS: DEFAULT_ALLOWED_HOSTS + }; + } + + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + + /** Determines if two MongoCredentials objects are equivalent */ + equals(other: MongoCredentials): boolean { + return ( + this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source + ); + } + + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param hello - A hello response from the server + */ + resolveAuthMechanism(hello: Document | null): MongoCredentials { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.match(/DEFAULT/i)) { + return new MongoCredentials({ + username: this.username, + password: this.password, + source: this.source, + mechanism: getDefaultAuthMechanism(hello), + mechanismProperties: this.mechanismProperties + }); + } + + return this; + } + + validate(): void { + if ( + (this.mechanism === AuthMechanism.MONGODB_GSSAPI || + this.mechanism === AuthMechanism.MONGODB_CR || + this.mechanism === AuthMechanism.MONGODB_PLAIN || + this.mechanism === AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username + ) { + throw new MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + + if (this.mechanism === AuthMechanism.MONGODB_OIDC) { + if (this.username && this.mechanismProperties.PROVIDER_NAME) { + throw new MongoInvalidArgumentError( + `username and PROVIDER_NAME may not be used together for mechanism '${this.mechanism}'.` + ); + } + + if ( + this.mechanismProperties.PROVIDER_NAME === 'azure' && + !this.mechanismProperties.TOKEN_AUDIENCE + ) { + throw new MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR); + } + + if ( + this.mechanismProperties.PROVIDER_NAME && + !ALLOWED_PROVIDER_NAMES.includes(this.mechanismProperties.PROVIDER_NAME) + ) { + throw new MongoInvalidArgumentError( + `Currently only a PROVIDER_NAME in ${ALLOWED_PROVIDER_NAMES.join( + ',' + )} is supported for mechanism '${this.mechanism}'.` + ); + } + + if ( + this.mechanismProperties.REFRESH_TOKEN_CALLBACK && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK + ) { + throw new MongoInvalidArgumentError( + `A REQUEST_TOKEN_CALLBACK must be provided when using a REFRESH_TOKEN_CALLBACK for mechanism '${this.mechanism}'` + ); + } + + if ( + !this.mechanismProperties.PROVIDER_NAME && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK + ) { + throw new MongoInvalidArgumentError( + `Either a PROVIDER_NAME or a REQUEST_TOKEN_CALLBACK must be specified for mechanism '${this.mechanism}'.` + ); + } + + if (this.mechanismProperties.ALLOWED_HOSTS) { + const hosts = this.mechanismProperties.ALLOWED_HOSTS; + if (!Array.isArray(hosts)) { + throw new MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR); + } + for (const host of hosts) { + if (typeof host !== 'string') { + throw new MongoInvalidArgumentError(ALLOWED_HOSTS_ERROR); + } + } + } + } + + if (AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError( + `Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.` + ); + } + } + + if (this.mechanism === AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + + if (this.mechanism === AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); + } + + const canonicalization = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false; + if (!Object.values(GSSAPICanonicalizationValue).includes(canonicalization)) { + throw new MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); + } + } + + static merge( + creds: MongoCredentials | undefined, + options: Partial + ): MongoCredentials { + return new MongoCredentials({ + username: options.username ?? creds?.username ?? '', + password: options.password ?? creds?.password ?? '', + mechanism: options.mechanism ?? creds?.mechanism ?? AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, + source: options.source ?? options.db ?? creds?.source ?? 'admin' + }); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongocr.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongocr.ts new file mode 100644 index 00000000..acaab721 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongocr.ts @@ -0,0 +1,38 @@ +import * as crypto from 'crypto'; + +import { MongoMissingCredentialsError } from '../../error'; +import { ns } from '../../utils'; +import { type AuthContext, AuthProvider } from './auth_provider'; + +export class MongoCR extends AuthProvider { + override async auth(authContext: AuthContext): Promise { + const { connection, credentials } = authContext; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + + const { username, password, source } = credentials; + + const { nonce } = await connection.command(ns(`${source}.$cmd`), { getnonce: 1 }, undefined); + + const hashPassword = crypto + .createHash('md5') + .update(`${username}:mongo:${password}`, 'utf8') + .digest('hex'); + + // Final key + const key = crypto + .createHash('md5') + .update(`${nonce}${username}${hashPassword}`, 'utf8') + .digest('hex'); + + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + + await connection.command(ns(`${source}.$cmd`), authenticateCommand, undefined); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts new file mode 100644 index 00000000..213d2b05 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts @@ -0,0 +1,298 @@ +import * as process from 'process'; + +import type { Binary, BSONSerializeOptions } from '../../bson'; +import * as BSON from '../../bson'; +import { aws4, type AWSCredentials, getAwsCredentialProvider } from '../../deps'; +import { + MongoAWSError, + MongoCompatibilityError, + MongoMissingCredentialsError, + MongoRuntimeError +} from '../../error'; +import { ByteUtils, maxWireVersion, ns, randomBytes, request } from '../../utils'; +import { type AuthContext, AuthProvider } from './auth_provider'; +import { MongoCredentials } from './mongo_credentials'; +import { AuthMechanism } from './providers'; + +/** + * The following regions use the global AWS STS endpoint, sts.amazonaws.com, by default + * https://docs.aws.amazon.com/sdkref/latest/guide/feature-sts-regionalized-endpoints.html + */ +const LEGACY_REGIONS = new Set([ + 'ap-northeast-1', + 'ap-south-1', + 'ap-southeast-1', + 'ap-southeast-2', + 'aws-global', + 'ca-central-1', + 'eu-central-1', + 'eu-north-1', + 'eu-west-1', + 'eu-west-2', + 'eu-west-3', + 'sa-east-1', + 'us-east-1', + 'us-east-2', + 'us-west-1', + 'us-west-2' +]); +const ASCII_N = 110; +const AWS_RELATIVE_URI = 'http://169.254.170.2'; +const AWS_EC2_URI = 'http://169.254.169.254'; +const AWS_EC2_PATH = '/latest/meta-data/iam/security-credentials'; +const bsonOptions: BSONSerializeOptions = { + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; + +interface AWSSaslContinuePayload { + a: string; + d: string; + t?: string; +} + +export class MongoDBAWS extends AuthProvider { + static credentialProvider: ReturnType; + provider?: () => Promise; + + constructor() { + super(); + MongoDBAWS.credentialProvider ??= getAwsCredentialProvider(); + + let { AWS_STS_REGIONAL_ENDPOINTS = '', AWS_REGION = '' } = process.env; + AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase(); + AWS_REGION = AWS_REGION.toLowerCase(); + + /** The option setting should work only for users who have explicit settings in their environment, the driver should not encode "defaults" */ + const awsRegionSettingsExist = + AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0; + + /** + * If AWS_STS_REGIONAL_ENDPOINTS is set to regional, users are opting into the new behavior of respecting the region settings + * + * If AWS_STS_REGIONAL_ENDPOINTS is set to legacy, then "old" regions need to keep using the global setting. + * Technically the SDK gets this wrong, it reaches out to 'sts.us-east-1.amazonaws.com' when it should be 'sts.amazonaws.com'. + * That is not our bug to fix here. We leave that up to the SDK. + */ + const useRegionalSts = + AWS_STS_REGIONAL_ENDPOINTS === 'regional' || + (AWS_STS_REGIONAL_ENDPOINTS === 'legacy' && !LEGACY_REGIONS.has(AWS_REGION)); + + if ('fromNodeProviderChain' in MongoDBAWS.credentialProvider) { + this.provider = + awsRegionSettingsExist && useRegionalSts + ? MongoDBAWS.credentialProvider.fromNodeProviderChain({ + clientConfig: { region: AWS_REGION } + }) + : MongoDBAWS.credentialProvider.fromNodeProviderChain(); + } + } + + override async auth(authContext: AuthContext): Promise { + const { connection } = authContext; + if (!authContext.credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + + if ('kModuleError' in aws4) { + throw aws4['kModuleError']; + } + const { sign } = aws4; + + if (maxWireVersion(connection) < 9) { + throw new MongoCompatibilityError( + 'MONGODB-AWS authentication requires MongoDB version 4.4 or later' + ); + } + + if (!authContext.credentials.username) { + authContext.credentials = await makeTempCredentials(authContext.credentials, this.provider); + } + + const { credentials } = authContext; + + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + // Allow the user to specify an AWS session token for authentication with temporary credentials. + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = + accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + + const db = credentials.source; + const nonce = await randomBytes(32); + + // All messages between MongoDB clients and servers are sent as BSON objects + // in the payload field of saslStart and saslContinue. + const saslStart = { + saslStart: 1, + mechanism: 'MONGODB-AWS', + payload: BSON.serialize({ r: nonce, p: ASCII_N }, bsonOptions) + }; + + const saslStartResponse = await connection.command(ns(`${db}.$cmd`), saslStart, undefined); + + const serverResponse = BSON.deserialize(saslStartResponse.payload.buffer, bsonOptions) as { + s: Binary; + h: string; + }; + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + // TODO(NODE-3483) + throw new MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`); + } + + if (!ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { + // throw because the serverNonce's leading 32 bytes must equal the client nonce's 32 bytes + // https://github.com/mongodb/specifications/blob/875446db44aade414011731840831f38a6c668df/source/auth/auth.rst#id11 + + // TODO(NODE-3483) + throw new MongoRuntimeError('Server nonce does not begin with client nonce'); + } + + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + throw new MongoRuntimeError(`Server returned an invalid host: "${host}"`); + } + + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = sign( + { + method: 'POST', + host, + region: deriveRegion(serverResponse.h), + service: 'sts', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': body.length, + 'X-MongoDB-Server-Nonce': ByteUtils.toBase64(serverNonce), + 'X-MongoDB-GS2-CB-Flag': 'n' + }, + path: '/', + body + }, + awsCredentials + ); + + const payload: AWSSaslContinuePayload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + + if (sessionToken) { + payload.t = sessionToken; + } + + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + + await connection.command(ns(`${db}.$cmd`), saslContinue, undefined); + } +} + +interface AWSTempCredentials { + AccessKeyId?: string; + SecretAccessKey?: string; + Token?: string; + RoleArn?: string; + Expiration?: Date; +} + +async function makeTempCredentials( + credentials: MongoCredentials, + provider?: () => Promise +): Promise { + function makeMongoCredentialsFromAWSTemp(creds: AWSTempCredentials) { + // The AWS session token (creds.Token) may or may not be set. + if (!creds.AccessKeyId || !creds.SecretAccessKey) { + throw new MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials'); + } + + return new MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: AuthMechanism.MONGODB_AWS, + mechanismProperties: { + AWS_SESSION_TOKEN: creds.Token + } + }); + } + + // Check if the AWS credential provider from the SDK is present. If not, + // use the old method. + if (provider && !('kModuleError' in MongoDBAWS.credentialProvider)) { + /* + * Creates a credential provider that will attempt to find credentials from the + * following sources (listed in order of precedence): + * + * - Environment variables exposed via process.env + * - SSO credentials from token cache + * - Web identity token credentials + * - Shared credentials and config ini files + * - The EC2/ECS Instance Metadata Service + */ + try { + const creds = await provider(); + return makeMongoCredentialsFromAWSTemp({ + AccessKeyId: creds.accessKeyId, + SecretAccessKey: creds.secretAccessKey, + Token: creds.sessionToken, + Expiration: creds.expiration + }); + } catch (error) { + throw new MongoAWSError(error.message); + } + } else { + // If the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI + // is set then drivers MUST assume that it was set by an AWS ECS agent + if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) { + return makeMongoCredentialsFromAWSTemp( + await request(`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`) + ); + } + + // Otherwise assume we are on an EC2 instance + + // get a token + const token = await request(`${AWS_EC2_URI}/latest/api/token`, { + method: 'PUT', + json: false, + headers: { 'X-aws-ec2-metadata-token-ttl-seconds': 30 } + }); + + // get role name + const roleName = await request(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, { + json: false, + headers: { 'X-aws-ec2-metadata-token': token } + }); + + // get temp credentials + const creds = await request(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, { + headers: { 'X-aws-ec2-metadata-token': token } + }); + + return makeMongoCredentialsFromAWSTemp(creds); + } +} + +function deriveRegion(host: string) { + const parts = host.split('.'); + if (parts.length === 1 || parts[1] === 'amazonaws') { + return 'us-east-1'; + } + + return parts[1]; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts new file mode 100644 index 00000000..f3584c48 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts @@ -0,0 +1,149 @@ +import type { Document } from 'bson'; + +import { MongoInvalidArgumentError, MongoMissingCredentialsError } from '../../error'; +import type { HandshakeDocument } from '../connect'; +import type { Connection } from '../connection'; +import { type AuthContext, AuthProvider } from './auth_provider'; +import type { MongoCredentials } from './mongo_credentials'; +import { AwsServiceWorkflow } from './mongodb_oidc/aws_service_workflow'; +import { AzureServiceWorkflow } from './mongodb_oidc/azure_service_workflow'; +import { CallbackWorkflow } from './mongodb_oidc/callback_workflow'; + +/** Error when credentials are missing. */ +const MISSING_CREDENTIALS_ERROR = 'AuthContext must provide credentials.'; + +/** + * @public + * @experimental + */ +export interface IdPServerInfo { + issuer: string; + clientId: string; + requestScopes?: string[]; +} + +/** + * @public + * @experimental + */ +export interface IdPServerResponse { + accessToken: string; + expiresInSeconds?: number; + refreshToken?: string; +} + +/** + * @public + * @experimental + */ +export interface OIDCCallbackContext { + refreshToken?: string; + timeoutSeconds?: number; + timeoutContext?: AbortSignal; + version: number; +} + +/** + * @public + * @experimental + */ +export type OIDCRequestFunction = ( + info: IdPServerInfo, + context: OIDCCallbackContext +) => Promise; + +/** + * @public + * @experimental + */ +export type OIDCRefreshFunction = ( + info: IdPServerInfo, + context: OIDCCallbackContext +) => Promise; + +type ProviderName = 'aws' | 'azure' | 'callback'; + +export interface Workflow { + /** + * All device workflows must implement this method in order to get the access + * token and then call authenticate with it. + */ + execute( + connection: Connection, + credentials: MongoCredentials, + reauthenticating: boolean, + response?: Document + ): Promise; + + /** + * Get the document to add for speculative authentication. + */ + speculativeAuth(credentials: MongoCredentials): Promise; +} + +/** @internal */ +export const OIDC_WORKFLOWS: Map = new Map(); +OIDC_WORKFLOWS.set('callback', new CallbackWorkflow()); +OIDC_WORKFLOWS.set('aws', new AwsServiceWorkflow()); +OIDC_WORKFLOWS.set('azure', new AzureServiceWorkflow()); + +/** + * OIDC auth provider. + * @experimental + */ +export class MongoDBOIDC extends AuthProvider { + /** + * Instantiate the auth provider. + */ + constructor() { + super(); + } + + /** + * Authenticate using OIDC + */ + override async auth(authContext: AuthContext): Promise { + const { connection, reauthenticating, response } = authContext; + const credentials = getCredentials(authContext); + const workflow = getWorkflow(credentials); + await workflow.execute(connection, credentials, reauthenticating, response); + } + + /** + * Add the speculative auth for the initial handshake. + */ + override async prepare( + handshakeDoc: HandshakeDocument, + authContext: AuthContext + ): Promise { + const credentials = getCredentials(authContext); + const workflow = getWorkflow(credentials); + const result = await workflow.speculativeAuth(credentials); + return { ...handshakeDoc, ...result }; + } +} + +/** + * Get credentials from the auth context, throwing if they do not exist. + */ +function getCredentials(authContext: AuthContext): MongoCredentials { + const { credentials } = authContext; + if (!credentials) { + throw new MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR); + } + return credentials; +} + +/** + * Gets either a device workflow or callback workflow. + */ +function getWorkflow(credentials: MongoCredentials): Workflow { + const providerName = credentials.mechanismProperties.PROVIDER_NAME; + const workflow = OIDC_WORKFLOWS.get(providerName || 'callback'); + if (!workflow) { + throw new MongoInvalidArgumentError( + `Could not load workflow for provider ${credentials.mechanismProperties.PROVIDER_NAME}` + ); + } + return workflow; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/aws_service_workflow.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/aws_service_workflow.ts new file mode 100644 index 00000000..5dd07b1d --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/aws_service_workflow.ts @@ -0,0 +1,29 @@ +import * as fs from 'fs'; + +import { MongoAWSError } from '../../../error'; +import { ServiceWorkflow } from './service_workflow'; + +/** Error for when the token is missing in the environment. */ +const TOKEN_MISSING_ERROR = 'AWS_WEB_IDENTITY_TOKEN_FILE must be set in the environment.'; + +/** + * Device workflow implementation for AWS. + * + * @internal + */ +export class AwsServiceWorkflow extends ServiceWorkflow { + constructor() { + super(); + } + + /** + * Get the token from the environment. + */ + async getToken(): Promise { + const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE; + if (!tokenFile) { + throw new MongoAWSError(TOKEN_MISSING_ERROR); + } + return fs.promises.readFile(tokenFile, 'utf8'); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/azure_service_workflow.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/azure_service_workflow.ts new file mode 100644 index 00000000..fadbf5e9 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/azure_service_workflow.ts @@ -0,0 +1,86 @@ +import { MongoAzureError } from '../../../error'; +import { request } from '../../../utils'; +import type { MongoCredentials } from '../mongo_credentials'; +import { AzureTokenCache } from './azure_token_cache'; +import { ServiceWorkflow } from './service_workflow'; + +/** Base URL for getting Azure tokens. */ +const AZURE_BASE_URL = + 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01'; + +/** Azure request headers. */ +const AZURE_HEADERS = Object.freeze({ Metadata: 'true', Accept: 'application/json' }); + +/** Invalid endpoint result error. */ +const ENDPOINT_RESULT_ERROR = + 'Azure endpoint did not return a value with only access_token and expires_in properties'; + +/** Error for when the token audience is missing in the environment. */ +const TOKEN_AUDIENCE_MISSING_ERROR = + 'TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.'; + +/** + * The Azure access token format. + * @internal + */ +export interface AzureAccessToken { + access_token: string; + expires_in: number; +} + +/** + * Device workflow implementation for Azure. + * + * @internal + */ +export class AzureServiceWorkflow extends ServiceWorkflow { + cache = new AzureTokenCache(); + + /** + * Get the token from the environment. + */ + async getToken(credentials?: MongoCredentials): Promise { + const tokenAudience = credentials?.mechanismProperties.TOKEN_AUDIENCE; + if (!tokenAudience) { + throw new MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR); + } + let token; + const entry = this.cache.getEntry(tokenAudience); + if (entry?.isValid()) { + token = entry.token; + } else { + this.cache.deleteEntry(tokenAudience); + const response = await getAzureTokenData(tokenAudience); + if (!isEndpointResultValid(response)) { + throw new MongoAzureError(ENDPOINT_RESULT_ERROR); + } + this.cache.addEntry(tokenAudience, response); + token = response.access_token; + } + return token; + } +} + +/** + * Hit the Azure endpoint to get the token data. + */ +async function getAzureTokenData(tokenAudience: string): Promise { + const url = `${AZURE_BASE_URL}&resource=${tokenAudience}`; + const data = await request(url, { + json: true, + headers: AZURE_HEADERS + }); + return data as AzureAccessToken; +} + +/** + * Determines if a result returned from the endpoint is valid. + * This means the result is not nullish, contains the access_token required field + * and the expires_in required field. + */ +function isEndpointResultValid( + token: unknown +): token is { access_token: unknown; expires_in: unknown } { + if (token == null || typeof token !== 'object') return false; + return 'access_token' in token && 'expires_in' in token; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/azure_token_cache.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/azure_token_cache.ts new file mode 100644 index 00000000..f6872512 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/azure_token_cache.ts @@ -0,0 +1,51 @@ +import type { AzureAccessToken } from './azure_service_workflow'; +import { Cache, ExpiringCacheEntry } from './cache'; + +/** @internal */ +export class AzureTokenEntry extends ExpiringCacheEntry { + token: string; + + /** + * Instantiate the entry. + */ + constructor(token: string, expiration: number) { + super(expiration); + this.token = token; + } +} + +/** + * A cache of access tokens from Azure. + * @internal + */ +export class AzureTokenCache extends Cache { + /** + * Add an entry to the cache. + */ + addEntry(tokenAudience: string, token: AzureAccessToken): AzureTokenEntry { + const entry = new AzureTokenEntry(token.access_token, token.expires_in); + this.entries.set(tokenAudience, entry); + return entry; + } + + /** + * Create a cache key. + */ + cacheKey(tokenAudience: string): string { + return tokenAudience; + } + + /** + * Delete an entry from the cache. + */ + deleteEntry(tokenAudience: string): void { + this.entries.delete(tokenAudience); + } + + /** + * Get an Azure token entry from the cache. + */ + getEntry(tokenAudience: string): AzureTokenEntry | undefined { + return this.entries.get(tokenAudience); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/cache.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/cache.ts new file mode 100644 index 00000000..e23685b3 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/cache.ts @@ -0,0 +1,63 @@ +/* 5 minutes in milliseconds */ +const EXPIRATION_BUFFER_MS = 300000; + +/** + * An entry in a cache that can expire in a certain amount of time. + */ +export abstract class ExpiringCacheEntry { + expiration: number; + + /** + * Create a new expiring token entry. + */ + constructor(expiration: number) { + this.expiration = this.expirationTime(expiration); + } + /** + * The entry is still valid if the expiration is more than + * 5 minutes from the expiration time. + */ + isValid() { + return this.expiration - Date.now() > EXPIRATION_BUFFER_MS; + } + + /** + * Get an expiration time in milliseconds past epoch. + */ + private expirationTime(expiresInSeconds: number): number { + return Date.now() + expiresInSeconds * 1000; + } +} + +/** + * Base class for OIDC caches. + */ +export abstract class Cache { + entries: Map; + + /** + * Create a new cache. + */ + constructor() { + this.entries = new Map(); + } + + /** + * Clear the cache. + */ + clear() { + this.entries.clear(); + } + + /** + * Implement the cache key for the token. + */ + abstract cacheKey(address: string, username: string, callbackHash: string): string; + + /** + * Create a cache key from the address and username. + */ + hashedCacheKey(address: string, username: string, callbackHash: string): string { + return JSON.stringify([address, username, callbackHash]); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/callback_lock_cache.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/callback_lock_cache.ts new file mode 100644 index 00000000..b92a504b --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/callback_lock_cache.ts @@ -0,0 +1,114 @@ +import { MongoInvalidArgumentError } from '../../../error'; +import type { Connection } from '../../connection'; +import type { MongoCredentials } from '../mongo_credentials'; +import type { + IdPServerInfo, + IdPServerResponse, + OIDCCallbackContext, + OIDCRefreshFunction, + OIDCRequestFunction +} from '../mongodb_oidc'; +import { Cache } from './cache'; + +/** Error message for when request callback is missing. */ +const REQUEST_CALLBACK_REQUIRED_ERROR = + 'Auth mechanism property REQUEST_TOKEN_CALLBACK is required.'; +/* Counter for function "hashes".*/ +let FN_HASH_COUNTER = 0; +/* No function present function */ +const NO_FUNCTION: OIDCRequestFunction = async () => ({ accessToken: 'test' }); +/* The map of function hashes */ +const FN_HASHES = new WeakMap(); +/* Put the no function hash in the map. */ +FN_HASHES.set(NO_FUNCTION, FN_HASH_COUNTER); + +/** + * An entry of callbacks in the cache. + */ +interface CallbacksEntry { + requestCallback: OIDCRequestFunction; + refreshCallback?: OIDCRefreshFunction; + callbackHash: string; +} + +/** + * A cache of request and refresh callbacks per server/user. + */ +export class CallbackLockCache extends Cache { + /** + * Get the callbacks for the connection and credentials. If an entry does not + * exist a new one will get set. + */ + getEntry(connection: Connection, credentials: MongoCredentials): CallbacksEntry { + const requestCallback = credentials.mechanismProperties.REQUEST_TOKEN_CALLBACK; + const refreshCallback = credentials.mechanismProperties.REFRESH_TOKEN_CALLBACK; + if (!requestCallback) { + throw new MongoInvalidArgumentError(REQUEST_CALLBACK_REQUIRED_ERROR); + } + const callbackHash = hashFunctions(requestCallback, refreshCallback); + const key = this.cacheKey(connection.address, credentials.username, callbackHash); + const entry = this.entries.get(key); + if (entry) { + return entry; + } + return this.addEntry(key, callbackHash, requestCallback, refreshCallback); + } + + /** + * Set locked callbacks on for connection and credentials. + */ + private addEntry( + key: string, + callbackHash: string, + requestCallback: OIDCRequestFunction, + refreshCallback?: OIDCRefreshFunction + ): CallbacksEntry { + const entry = { + requestCallback: withLock(requestCallback), + refreshCallback: refreshCallback ? withLock(refreshCallback) : undefined, + callbackHash: callbackHash + }; + this.entries.set(key, entry); + return entry; + } + + /** + * Create a cache key from the address and username. + */ + cacheKey(address: string, username: string, callbackHash: string): string { + return this.hashedCacheKey(address, username, callbackHash); + } +} + +/** + * Ensure the callback is only executed one at a time. + */ +function withLock(callback: OIDCRequestFunction | OIDCRefreshFunction) { + let lock: Promise = Promise.resolve(); + return async (info: IdPServerInfo, context: OIDCCallbackContext): Promise => { + await lock; + lock = lock.then(() => callback(info, context)); + return lock; + }; +} + +/** + * Get the hash string for the request and refresh functions. + */ +function hashFunctions(requestFn: OIDCRequestFunction, refreshFn?: OIDCRefreshFunction): string { + let requestHash = FN_HASHES.get(requestFn); + let refreshHash = FN_HASHES.get(refreshFn ?? NO_FUNCTION); + if (requestHash == null) { + // Create a new one for the function and put it in the map. + FN_HASH_COUNTER++; + requestHash = FN_HASH_COUNTER; + FN_HASHES.set(requestFn, FN_HASH_COUNTER); + } + if (refreshHash == null && refreshFn) { + // Create a new one for the function and put it in the map. + FN_HASH_COUNTER++; + refreshHash = FN_HASH_COUNTER; + FN_HASHES.set(refreshFn, FN_HASH_COUNTER); + } + return `${requestHash}-${refreshHash}`; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/callback_workflow.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/callback_workflow.ts new file mode 100644 index 00000000..9822fd1e --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/callback_workflow.ts @@ -0,0 +1,296 @@ +import { Binary, BSON, type Document } from 'bson'; + +import { MONGODB_ERROR_CODES, MongoError, MongoMissingCredentialsError } from '../../../error'; +import { ns } from '../../../utils'; +import type { Connection } from '../../connection'; +import type { MongoCredentials } from '../mongo_credentials'; +import type { + IdPServerInfo, + IdPServerResponse, + OIDCCallbackContext, + OIDCRefreshFunction, + OIDCRequestFunction, + Workflow +} from '../mongodb_oidc'; +import { AuthMechanism } from '../providers'; +import { CallbackLockCache } from './callback_lock_cache'; +import { TokenEntryCache } from './token_entry_cache'; + +/** The current version of OIDC implementation. */ +const OIDC_VERSION = 0; + +/** 5 minutes in seconds */ +const TIMEOUT_S = 300; + +/** Properties allowed on results of callbacks. */ +const RESULT_PROPERTIES = ['accessToken', 'expiresInSeconds', 'refreshToken']; + +/** Error message when the callback result is invalid. */ +const CALLBACK_RESULT_ERROR = + 'User provided OIDC callbacks must return a valid object with an accessToken.'; + +/** + * OIDC implementation of a callback based workflow. + * @internal + */ +export class CallbackWorkflow implements Workflow { + cache: TokenEntryCache; + callbackCache: CallbackLockCache; + + /** + * Instantiate the workflow + */ + constructor() { + this.cache = new TokenEntryCache(); + this.callbackCache = new CallbackLockCache(); + } + + /** + * Get the document to add for speculative authentication. This also needs + * to add a db field from the credentials source. + */ + async speculativeAuth(credentials: MongoCredentials): Promise { + const document = startCommandDocument(credentials); + document.db = credentials.source; + return { speculativeAuthenticate: document }; + } + + /** + * Execute the OIDC callback workflow. + */ + async execute( + connection: Connection, + credentials: MongoCredentials, + reauthenticating: boolean, + response?: Document + ): Promise { + // Get the callbacks with locks from the callback lock cache. + const { requestCallback, refreshCallback, callbackHash } = this.callbackCache.getEntry( + connection, + credentials + ); + // Look for an existing entry in the cache. + const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash); + let result; + if (entry) { + // Reauthentication cannot use a token from the cache since the server has + // stated it is invalid by the request for reauthentication. + if (entry.isValid() && !reauthenticating) { + // Presence of a valid cache entry means we can skip to the finishing step. + result = await this.finishAuthentication( + connection, + credentials, + entry.tokenResult, + response?.speculativeAuthenticate?.conversationId + ); + } else { + // Presence of an expired cache entry means we must fetch a new one and + // then execute the final step. + const tokenResult = await this.fetchAccessToken( + connection, + credentials, + entry.serverInfo, + reauthenticating, + callbackHash, + requestCallback, + refreshCallback + ); + try { + result = await this.finishAuthentication( + connection, + credentials, + tokenResult, + reauthenticating ? undefined : response?.speculativeAuthenticate?.conversationId + ); + } catch (error) { + // If we are reauthenticating and this errors with reauthentication + // required, we need to do the entire process over again and clear + // the cache entry. + if ( + reauthenticating && + error instanceof MongoError && + error.code === MONGODB_ERROR_CODES.Reauthenticate + ) { + this.cache.deleteEntry(connection.address, credentials.username, callbackHash); + result = await this.execute(connection, credentials, reauthenticating); + } else { + throw error; + } + } + } + } else { + // No entry in the cache requires us to do all authentication steps + // from start to finish, including getting a fresh token for the cache. + const startDocument = await this.startAuthentication( + connection, + credentials, + reauthenticating, + response + ); + const conversationId = startDocument.conversationId; + const serverResult = BSON.deserialize(startDocument.payload.buffer) as IdPServerInfo; + const tokenResult = await this.fetchAccessToken( + connection, + credentials, + serverResult, + reauthenticating, + callbackHash, + requestCallback, + refreshCallback + ); + result = await this.finishAuthentication( + connection, + credentials, + tokenResult, + conversationId + ); + } + return result; + } + + /** + * Starts the callback authentication process. If there is a speculative + * authentication document from the initial handshake, then we will use that + * value to get the issuer, otherwise we will send the saslStart command. + */ + private async startAuthentication( + connection: Connection, + credentials: MongoCredentials, + reauthenticating: boolean, + response?: Document + ): Promise { + let result; + if (!reauthenticating && response?.speculativeAuthenticate) { + result = response.speculativeAuthenticate; + } else { + result = await connection.command( + ns(credentials.source), + startCommandDocument(credentials), + undefined + ); + } + return result; + } + + /** + * Finishes the callback authentication process. + */ + private async finishAuthentication( + connection: Connection, + credentials: MongoCredentials, + tokenResult: IdPServerResponse, + conversationId?: number + ): Promise { + const result = await connection.command( + ns(credentials.source), + finishCommandDocument(tokenResult.accessToken, conversationId), + undefined + ); + return result; + } + + /** + * Fetches an access token using either the request or refresh callbacks and + * puts it in the cache. + */ + private async fetchAccessToken( + connection: Connection, + credentials: MongoCredentials, + serverInfo: IdPServerInfo, + reauthenticating: boolean, + callbackHash: string, + requestCallback: OIDCRequestFunction, + refreshCallback?: OIDCRefreshFunction + ): Promise { + // Get the token from the cache. + const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash); + let result; + const context: OIDCCallbackContext = { timeoutSeconds: TIMEOUT_S, version: OIDC_VERSION }; + // Check if there's a token in the cache. + if (entry) { + // If the cache entry is valid, return the token result. + if (entry.isValid() && !reauthenticating) { + return entry.tokenResult; + } + // If the cache entry is not valid, remove it from the cache and first attempt + // to use the refresh callback to get a new token. If no refresh callback + // exists, then fallback to the request callback. + if (refreshCallback) { + context.refreshToken = entry.tokenResult.refreshToken; + result = await refreshCallback(serverInfo, context); + } else { + result = await requestCallback(serverInfo, context); + } + } else { + // With no token in the cache we use the request callback. + result = await requestCallback(serverInfo, context); + } + // Validate that the result returned by the callback is acceptable. If it is not + // we must clear the token result from the cache. + if (isCallbackResultInvalid(result)) { + this.cache.deleteEntry(connection.address, credentials.username, callbackHash); + throw new MongoMissingCredentialsError(CALLBACK_RESULT_ERROR); + } + // Cleanup the cache. + this.cache.deleteExpiredEntries(); + // Put the new entry into the cache. + this.cache.addEntry( + connection.address, + credentials.username || '', + callbackHash, + result, + serverInfo + ); + return result; + } +} + +/** + * Generate the finishing command document for authentication. Will be a + * saslStart or saslContinue depending on the presence of a conversation id. + */ +function finishCommandDocument(token: string, conversationId?: number): Document { + if (conversationId != null && typeof conversationId === 'number') { + return { + saslContinue: 1, + conversationId: conversationId, + payload: new Binary(BSON.serialize({ jwt: token })) + }; + } + // saslContinue requires a conversationId in the command to be valid so in this + // case the server allows "step two" to actually be a saslStart with the token + // as the jwt since the use of the cached value has no correlating conversating + // on the particular connection. + return { + saslStart: 1, + mechanism: AuthMechanism.MONGODB_OIDC, + payload: new Binary(BSON.serialize({ jwt: token })) + }; +} + +/** + * Determines if a result returned from a request or refresh callback + * function is invalid. This means the result is nullish, doesn't contain + * the accessToken required field, and does not contain extra fields. + */ +function isCallbackResultInvalid(tokenResult: unknown): boolean { + if (tokenResult == null || typeof tokenResult !== 'object') return true; + if (!('accessToken' in tokenResult)) return true; + return !Object.getOwnPropertyNames(tokenResult).every(prop => RESULT_PROPERTIES.includes(prop)); +} + +/** + * Generate the saslStart command document. + */ +function startCommandDocument(credentials: MongoCredentials): Document { + const payload: Document = {}; + if (credentials.username) { + payload.n = credentials.username; + } + return { + saslStart: 1, + autoAuthorize: 1, + mechanism: AuthMechanism.MONGODB_OIDC, + payload: new Binary(BSON.serialize(payload)) + }; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/service_workflow.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/service_workflow.ts new file mode 100644 index 00000000..afea78fa --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/service_workflow.ts @@ -0,0 +1,49 @@ +import { BSON, type Document } from 'bson'; + +import { ns } from '../../../utils'; +import type { Connection } from '../../connection'; +import type { MongoCredentials } from '../mongo_credentials'; +import type { Workflow } from '../mongodb_oidc'; +import { AuthMechanism } from '../providers'; + +/** + * Common behaviour for OIDC device workflows. + * @internal + */ +export abstract class ServiceWorkflow implements Workflow { + /** + * Execute the workflow. Looks for AWS_WEB_IDENTITY_TOKEN_FILE in the environment + * and then attempts to read the token from that path. + */ + async execute(connection: Connection, credentials: MongoCredentials): Promise { + const token = await this.getToken(credentials); + const command = commandDocument(token); + return connection.command(ns(credentials.source), command, undefined); + } + + /** + * Get the document to add for speculative authentication. + */ + async speculativeAuth(credentials: MongoCredentials): Promise { + const token = await this.getToken(credentials); + const document = commandDocument(token); + document.db = credentials.source; + return { speculativeAuthenticate: document }; + } + + /** + * Get the token from the environment or endpoint. + */ + abstract getToken(credentials: MongoCredentials): Promise; +} + +/** + * Create the saslStart command document. + */ +export function commandDocument(token: string): Document { + return { + saslStart: 1, + mechanism: AuthMechanism.MONGODB_OIDC, + payload: BSON.serialize({ jwt: token }) + }; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/token_entry_cache.ts b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/token_entry_cache.ts new file mode 100644 index 00000000..1b5b9de3 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/mongodb_oidc/token_entry_cache.ts @@ -0,0 +1,77 @@ +import type { IdPServerInfo, IdPServerResponse } from '../mongodb_oidc'; +import { Cache, ExpiringCacheEntry } from './cache'; + +/* Default expiration is now for when no expiration provided */ +const DEFAULT_EXPIRATION_SECS = 0; + +/** @internal */ +export class TokenEntry extends ExpiringCacheEntry { + tokenResult: IdPServerResponse; + serverInfo: IdPServerInfo; + + /** + * Instantiate the entry. + */ + constructor(tokenResult: IdPServerResponse, serverInfo: IdPServerInfo, expiration: number) { + super(expiration); + this.tokenResult = tokenResult; + this.serverInfo = serverInfo; + } +} + +/** + * Cache of OIDC token entries. + * @internal + */ +export class TokenEntryCache extends Cache { + /** + * Set an entry in the token cache. + */ + addEntry( + address: string, + username: string, + callbackHash: string, + tokenResult: IdPServerResponse, + serverInfo: IdPServerInfo + ): TokenEntry { + const entry = new TokenEntry( + tokenResult, + serverInfo, + tokenResult.expiresInSeconds ?? DEFAULT_EXPIRATION_SECS + ); + this.entries.set(this.cacheKey(address, username, callbackHash), entry); + return entry; + } + + /** + * Delete an entry from the cache. + */ + deleteEntry(address: string, username: string, callbackHash: string): void { + this.entries.delete(this.cacheKey(address, username, callbackHash)); + } + + /** + * Get an entry from the cache. + */ + getEntry(address: string, username: string, callbackHash: string): TokenEntry | undefined { + return this.entries.get(this.cacheKey(address, username, callbackHash)); + } + + /** + * Delete all expired entries from the cache. + */ + deleteExpiredEntries(): void { + for (const [key, entry] of this.entries) { + if (!entry.isValid()) { + this.entries.delete(key); + } + } + } + + /** + * Create a cache key from the address and username. + */ + cacheKey(address: string, username: string, callbackHash: string): string { + return this.hashedCacheKey(address, username, callbackHash); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/plain.ts b/nodejs/node_modules/mongodb/src/cmap/auth/plain.ts new file mode 100644 index 00000000..f5a43863 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/plain.ts @@ -0,0 +1,25 @@ +import { Binary } from '../../bson'; +import { MongoMissingCredentialsError } from '../../error'; +import { ns } from '../../utils'; +import { type AuthContext, AuthProvider } from './auth_provider'; + +export class Plain extends AuthProvider { + override async auth(authContext: AuthContext): Promise { + const { connection, credentials } = authContext; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + + const { username, password } = credentials; + + const payload = new Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + await connection.command(ns('$external.$cmd'), command, undefined); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/providers.ts b/nodejs/node_modules/mongodb/src/cmap/auth/providers.ts new file mode 100644 index 00000000..d01c0632 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/providers.ts @@ -0,0 +1,24 @@ +/** @public */ +export const AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509', + /** @experimental */ + MONGODB_OIDC: 'MONGODB-OIDC' +} as const); + +/** @public */ +export type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism]; + +/** @internal */ +export const AUTH_MECHS_AUTH_SRC_EXTERNAL = new Set([ + AuthMechanism.MONGODB_GSSAPI, + AuthMechanism.MONGODB_AWS, + AuthMechanism.MONGODB_OIDC, + AuthMechanism.MONGODB_X509 +]); diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/scram.ts b/nodejs/node_modules/mongodb/src/cmap/auth/scram.ts new file mode 100644 index 00000000..95858f9f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/scram.ts @@ -0,0 +1,344 @@ +import { saslprep } from '@mongodb-js/saslprep'; +import * as crypto from 'crypto'; + +import { Binary, type Document } from '../../bson'; +import { + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoRuntimeError +} from '../../error'; +import { ns, randomBytes } from '../../utils'; +import type { HandshakeDocument } from '../connect'; +import { type AuthContext, AuthProvider } from './auth_provider'; +import type { MongoCredentials } from './mongo_credentials'; +import { AuthMechanism } from './providers'; + +type CryptoMethod = 'sha1' | 'sha256'; + +class ScramSHA extends AuthProvider { + cryptoMethod: CryptoMethod; + + constructor(cryptoMethod: CryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + + override async prepare( + handshakeDoc: HandshakeDocument, + authContext: AuthContext + ): Promise { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + + const nonce = await randomBytes(24); + // store the nonce for later use + authContext.nonce = nonce; + + const request = { + ...handshakeDoc, + speculativeAuthenticate: { + ...makeFirstMessage(cryptoMethod, credentials, nonce), + db: credentials.source + } + }; + + return request; + } + + override async auth(authContext: AuthContext) { + const { reauthenticating, response } = authContext; + if (response?.speculativeAuthenticate && !reauthenticating) { + return continueScramConversation( + this.cryptoMethod, + response.speculativeAuthenticate, + authContext + ); + } + return executeScram(this.cryptoMethod, authContext); + } +} + +function cleanUsername(username: string) { + return username.replace('=', '=3D').replace(',', '=2C'); +} + +function clientFirstMessageBare(username: string, nonce: Buffer) { + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce.toString('base64'), 'utf8') + ]); +} + +function makeFirstMessage( + cryptoMethod: CryptoMethod, + credentials: MongoCredentials, + nonce: Buffer +) { + const username = cleanUsername(credentials.username); + const mechanism = + cryptoMethod === 'sha1' ? AuthMechanism.MONGODB_SCRAM_SHA1 : AuthMechanism.MONGODB_SCRAM_SHA256; + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + return { + saslStart: 1, + mechanism, + payload: new Binary( + Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)]) + ), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} + +async function executeScram(cryptoMethod: CryptoMethod, authContext: AuthContext): Promise { + const { connection, credentials } = authContext; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + if (!authContext.nonce) { + throw new MongoInvalidArgumentError('AuthContext must contain a valid nonce property'); + } + const nonce = authContext.nonce; + const db = credentials.source; + + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + const response = await connection.command(ns(`${db}.$cmd`), saslStartCmd, undefined); + await continueScramConversation(cryptoMethod, response, authContext); +} + +async function continueScramConversation( + cryptoMethod: CryptoMethod, + response: Document, + authContext: AuthContext +): Promise { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + if (!authContext.nonce) { + throw new MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce'); + } + const nonce = authContext.nonce; + + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + + const processedPassword = + cryptoMethod === 'sha256' ? saslprep(password) : passwordDigest(username, password); + + const payload: Binary = Buffer.isBuffer(response.payload) + ? new Binary(response.payload) + : response.payload; + + const dict = parsePayload(payload); + + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + // TODO(NODE-3483) + throw new MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`); + } + + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + throw new MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`); + } + + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [ + clientFirstMessageBare(username, nonce), + payload.toString('utf8'), + withoutProof + ].join(','); + + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + + const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); + const saslContinueCmd = { + saslContinue: 1, + conversationId: response.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + const r = await connection.command(ns(`${db}.$cmd`), saslContinueCmd, undefined); + const parsedResponse = parsePayload(r.payload); + + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + throw new MongoRuntimeError('Server returned an invalid signature'); + } + + if (r.done !== false) { + // If the server sends r.done === true we can save one RTT + return; + } + + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + + await connection.command(ns(`${db}.$cmd`), retrySaslContinueCmd, undefined); +} + +function parsePayload(payload: Binary) { + const payloadStr = payload.toString('utf8'); + const dict: Document = {}; + const parts = payloadStr.split(','); + for (let i = 0; i < parts.length; i++) { + const valueParts = (parts[i].match(/^([^=]*)=(.*)$/) ?? []).slice(1); + dict[valueParts[0]] = valueParts[1]; + } + return dict; +} + +function passwordDigest(username: string, password: string) { + if (typeof username !== 'string') { + throw new MongoInvalidArgumentError('Username must be a string'); + } + + if (typeof password !== 'string') { + throw new MongoInvalidArgumentError('Password must be a string'); + } + + if (password.length === 0) { + throw new MongoInvalidArgumentError('Password cannot be empty'); + } + + let md5: crypto.Hash; + try { + md5 = crypto.createHash('md5'); + } catch (err) { + if (crypto.getFips()) { + // This error is (slightly) more helpful than what comes from OpenSSL directly, e.g. + // 'Error: error:060800C8:digital envelope routines:EVP_DigestInit_ex:disabled for FIPS' + throw new Error('Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode'); + } + throw err; + } + md5.update(`${username}:mongo:${password}`, 'utf8'); + return md5.digest('hex'); +} + +// XOR two buffers +function xor(a: Buffer, b: Buffer) { + if (!Buffer.isBuffer(a)) { + a = Buffer.from(a); + } + + if (!Buffer.isBuffer(b)) { + b = Buffer.from(b); + } + + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method: CryptoMethod, text: Buffer) { + return crypto.createHash(method).update(text).digest(); +} + +function HMAC(method: CryptoMethod, key: Buffer, text: Buffer | string) { + return crypto.createHmac(method, key).update(text).digest(); +} + +interface HICache { + [key: string]: Buffer; +} + +let _hiCache: HICache = {}; +let _hiCacheCount = 0; +function _hiCachePurge() { + _hiCache = {}; + _hiCacheCount = 0; +} + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data: string, salt: Buffer, iterations: number, cryptoMethod: CryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] != null) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +function compareDigest(lhs: Buffer, rhs: Uint8Array) { + if (lhs.length !== rhs.length) { + return false; + } + + if (typeof crypto.timingSafeEqual === 'function') { + return crypto.timingSafeEqual(lhs, rhs); + } + + let result = 0; + for (let i = 0; i < lhs.length; i++) { + result |= lhs[i] ^ rhs[i]; + } + + return result === 0; +} + +export class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} + +export class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/auth/x509.ts b/nodejs/node_modules/mongodb/src/cmap/auth/x509.ts new file mode 100644 index 00000000..ec4c0007 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/auth/x509.ts @@ -0,0 +1,43 @@ +import type { Document } from '../../bson'; +import { MongoMissingCredentialsError } from '../../error'; +import { ns } from '../../utils'; +import type { HandshakeDocument } from '../connect'; +import { type AuthContext, AuthProvider } from './auth_provider'; +import type { MongoCredentials } from './mongo_credentials'; + +export class X509 extends AuthProvider { + override async prepare( + handshakeDoc: HandshakeDocument, + authContext: AuthContext + ): Promise { + const { credentials } = authContext; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + return { ...handshakeDoc, speculativeAuthenticate: x509AuthenticateCommand(credentials) }; + } + + override async auth(authContext: AuthContext) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + throw new MongoMissingCredentialsError('AuthContext must provide credentials.'); + } + const response = authContext.response; + + if (response?.speculativeAuthenticate) { + return; + } + + await connection.command(ns('$external.$cmd'), x509AuthenticateCommand(credentials), undefined); + } +} + +function x509AuthenticateCommand(credentials: MongoCredentials) { + const command: Document = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + + return command; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/command_monitoring_events.ts b/nodejs/node_modules/mongodb/src/cmap/command_monitoring_events.ts new file mode 100644 index 00000000..002ecf2c --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/command_monitoring_events.ts @@ -0,0 +1,343 @@ +import { type Document, type ObjectId } from '../bson'; +import { + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + LEGACY_HELLO_COMMAND, + LEGACY_HELLO_COMMAND_CAMEL_CASE +} from '../constants'; +import { calculateDurationInMs, deepCopy } from '../utils'; +import { OpMsgRequest, type OpQueryRequest, type WriteProtocolMessageType } from './commands'; +import type { Connection } from './connection'; + +/** + * An event indicating the start of a given command + * @public + * @category Event + */ +export class CommandStartedEvent { + commandObj?: Document; + requestId: number; + databaseName: string; + commandName: string; + command: Document; + address: string; + /** Driver generated connection id */ + connectionId?: string | number; + /** + * Server generated connection id + * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" + * from the server on 4.2+. + */ + serverConnectionId: bigint | null; + serviceId?: ObjectId; + /** @internal */ + name = COMMAND_STARTED; + + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + serverConnectionId: bigint | null + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + // TODO: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = command.databaseName; + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + this.serverConnectionId = serverConnectionId; + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +export class CommandSucceededEvent { + address: string; + /** Driver generated connection id */ + connectionId?: string | number; + /** + * Server generated connection id + * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+. + */ + serverConnectionId: bigint | null; + requestId: number; + duration: number; + commandName: string; + reply: unknown; + serviceId?: ObjectId; + /** @internal */ + name = COMMAND_SUCCEEDED; + + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + reply: Document | undefined, + started: number, + serverConnectionId: bigint | null + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = calculateDurationInMs(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + this.serverConnectionId = serverConnectionId; + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +export class CommandFailedEvent { + address: string; + /** Driver generated connection id */ + connectionId?: string | number; + /** + * Server generated connection id + * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+. + */ + serverConnectionId: bigint | null; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + /** @internal */ + name = COMMAND_FAILED; + + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor( + connection: Connection, + command: WriteProtocolMessageType, + error: Error | Document, + started: number, + serverConnectionId: bigint | null + ) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = calculateDurationInMs(started); + this.failure = maybeRedact(commandName, cmd, error) as Error; + this.serverConnectionId = serverConnectionId; + } + + /* @internal */ + get hasServiceId(): boolean { + return !!this.serviceId; + } +} + +/** + * Commands that we want to redact because of the sensitive nature of their contents + * @internal + */ +export const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +const HELLO_COMMANDS = new Set(['hello', LEGACY_HELLO_COMMAND, LEGACY_HELLO_COMMAND_CAMEL_CASE]); + +// helper methods +const extractCommandName = (commandDoc: Document) => Object.keys(commandDoc)[0]; +const namespace = (command: OpQueryRequest) => command.ns; +const collectionName = (command: OpQueryRequest) => command.ns.split('.')[1]; +const maybeRedact = (commandName: string, commandDoc: Document, result: Error | Document) => + SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; + +const LEGACY_FIND_QUERY_MAP: { [key: string]: string } = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldSelector: 'projection' +} as const; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +] as const; + +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command: WriteProtocolMessageType): Document { + if (command instanceof OpMsgRequest) { + return deepCopy(command.command); + } + + if (command.query?.$query) { + let result: Document; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command + result = Object.assign({}, command.query.$query); + } else { + // up-convert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = deepCopy(command.query[key]); + } + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key as keyof typeof LEGACY_FIND_OPTIONS_MAP; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = deepCopy(command[legacyKey]); + } + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) { + result[key] = command[key]; + } + }); + + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + return result; + } + + const clonedQuery: Record = {}; + const clonedCommand: Record = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = deepCopy(command.query[k]); + } + clonedCommand.query = clonedQuery; + } + + for (const k in command) { + if (k === 'query') continue; + clonedCommand[k] = deepCopy((command as unknown as Record)[k]); + } + return command.query ? clonedQuery : clonedCommand; +} + +function extractReply(command: WriteProtocolMessageType, reply?: Document) { + if (!reply) { + return reply; + } + + if (command instanceof OpMsgRequest) { + return deepCopy(reply.result ? reply.result : reply); + } + + // is this a legacy find command? + if (command.query && command.query.$query != null) { + return { + ok: 1, + cursor: { + id: deepCopy(reply.cursorId), + ns: namespace(command), + firstBatch: deepCopy(reply.documents) + } + }; + } + + return deepCopy(reply.result ? reply.result : reply); +} + +function extractConnectionDetails(connection: Connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/commands.ts b/nodejs/node_modules/mongodb/src/cmap/commands.ts new file mode 100644 index 00000000..57a605cf --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/commands.ts @@ -0,0 +1,766 @@ +import type { BSONSerializeOptions, Document, Long } from '../bson'; +import * as BSON from '../bson'; +import { MongoInvalidArgumentError, MongoRuntimeError } from '../error'; +import { type ReadPreference } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import type { CommandOptions } from './connection'; +import { + compress, + Compressor, + type CompressorName, + uncompressibleCommands +} from './wire_protocol/compression'; +import { OP_COMPRESSED, OP_MSG, OP_QUERY } from './wire_protocol/constants'; + +// Incrementing request id +let _requestId = 0; + +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SECONDARY = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; + +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; + +/** @internal */ +export type WriteProtocolMessageType = OpQueryRequest | OpMsgRequest; + +/** @internal */ +export interface OpQueryOptions extends CommandOptions { + socketTimeoutMS?: number; + session?: ClientSession; + documentsReturnedIn?: string; + numberToSkip?: number; + numberToReturn?: number; + returnFieldSelector?: Document; + pre32Limit?: number; + serializeFunctions?: boolean; + ignoreUndefined?: boolean; + maxBsonSize?: number; + checkKeys?: boolean; + secondaryOk?: boolean; + + requestId?: number; + moreToCome?: boolean; + exhaustAllowed?: boolean; +} + +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +export class OpQueryRequest { + ns: string; + numberToSkip: number; + numberToReturn: number; + returnFieldSelector?: Document; + requestId: number; + pre32Limit?: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + maxBsonSize: number; + checkKeys: boolean; + batchSize: number; + tailable: boolean; + secondaryOk: boolean; + oplogReplay: boolean; + noCursorTimeout: boolean; + awaitData: boolean; + exhaust: boolean; + partial: boolean; + + constructor(public databaseName: string, public query: Document, options: OpQueryOptions) { + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + const ns = `${databaseName}.$cmd`; + if (typeof databaseName !== 'string') { + throw new MongoRuntimeError('Database name must be a string for a query'); + } + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) throw new MongoRuntimeError('A query document must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new MongoRuntimeError('Namespace cannot contain a null character'); + } + + // Basic options + this.ns = ns; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + this.requestId = options.requestId ?? OpQueryRequest.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.batchSize = this.numberToReturn; + + // Flags + this.tailable = false; + this.secondaryOk = typeof options.secondaryOk === 'boolean' ? options.secondaryOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; + } + + /** Assign next request Id. */ + incRequestId(): void { + this.requestId = _requestId++; + } + + /** Peek next request Id. */ + nextRequestId(): number { + return _requestId + 1; + } + + /** Increment then return next request Id. */ + static getRequestId(): number { + return ++_requestId; + } + + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin(): Uint8Array[] { + const buffers = []; + let projection = null; + + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.secondaryOk) { + flags |= OPTS_SECONDARY; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) this.numberToReturn = this.batchSize; + + // Allocate write protocol header buffer + const header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + const totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + let index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; + } +} + +/** @internal */ +export interface MessageHeader { + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; +} + +/** @internal */ +export interface OpResponseOptions extends BSONSerializeOptions { + documentsReturnedIn?: string | null; +} + +/** @internal */ +export class OpQueryResponse { + parsed: boolean; + raw: Buffer; + data: Buffer; + opts: OpResponseOptions; + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; + responseFlags?: number; + cursorId?: Long; + startingFrom?: number; + numberReturned?: number; + documents: (Document | Buffer)[] = new Array(0); + cursorNotFound?: boolean; + queryFailure?: boolean; + shardConfigStale?: boolean; + awaitCapable?: boolean; + useBigInt64: boolean; + promoteLongs: boolean; + promoteValues: boolean; + promoteBuffers: boolean; + bsonRegExp?: boolean; + index?: number; + + /** moreToCome is an OP_MSG only concept */ + moreToCome = false; + + constructor( + message: Buffer, + msgHeader: MessageHeader, + msgBody: Buffer, + opts?: OpResponseOptions + ) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Flag values + this.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + + isParsed(): boolean { + return this.parsed; + } + + parse(options: OpResponseOptions): void { + // Don't parse again if not needed + if (this.parsed) return; + options = options ?? {}; + + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + let bsonSize; + + // Set up the options + const _options: BSONSerializeOptions = { + useBigInt64, + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + + // Position within OP_REPLY at which documents start + // (See https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // Read the message body + this.responseFlags = this.data.readInt32LE(0); + this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8)); + this.startingFrom = this.data.readInt32LE(12); + this.numberReturned = this.data.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + + // Parse Body + for (let i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = BSON.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw: Document = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = BSON.deserialize(this.documents[0] as Buffer, _options); + this.documents = [doc]; + } + + // Set parsed + this.parsed = true; + } +} + +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; + +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; + +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; + +/** @internal */ +export interface OpMsgOptions { + requestId: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + checkKeys: boolean; + maxBsonSize: number; + moreToCome: boolean; + exhaustAllowed: boolean; + readPreference: ReadPreference; +} + +/** @internal */ +export class OpMsgRequest { + requestId: number; + serializeFunctions: boolean; + ignoreUndefined: boolean; + checkKeys: boolean; + maxBsonSize: number; + checksumPresent: boolean; + moreToCome: boolean; + exhaustAllowed: boolean; + + constructor( + public databaseName: string, + public command: Document, + public options: OpQueryOptions + ) { + // Basic options needed to be passed in + if (command == null) + throw new MongoInvalidArgumentError('Query document must be specified for query'); + + // Basic options + this.command.$db = databaseName; + + // Ensure empty options + this.options = options ?? {}; + + // Additional options + this.requestId = options.requestId ? options.requestId : OpMsgRequest.getRequestId(); + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = + typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; + } + + toBin(): Buffer[] { + const buffers: Buffer[] = []; + let flags = 0; + + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + + const header = Buffer.alloc( + 4 * 4 + // Header + 4 // Flags + ); + + buffers.push(header); + + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + + makeDocumentSegment(buffers: Uint8Array[], document: Document): number { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + + return payloadTypeBuffer.length + documentBuffer.length; + } + + serializeBson(document: Document): Uint8Array { + return BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } + + static getRequestId(): number { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} + +/** @internal */ +export class OpMsgResponse { + parsed: boolean; + raw: Buffer; + data: Buffer; + opts: OpResponseOptions; + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; + responseFlags: number; + checksumPresent: boolean; + /** Indicates the server will be sending more responses on this connection */ + moreToCome: boolean; + exhaustAllowed: boolean; + useBigInt64: boolean; + promoteLongs: boolean; + promoteValues: boolean; + promoteBuffers: boolean; + bsonRegExp: boolean; + documents: (Document | Buffer)[]; + index?: number; + + constructor( + message: Buffer, + msgHeader: MessageHeader, + msgBody: Buffer, + opts?: OpResponseOptions + ) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts ?? { + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + this.promoteLongs = typeof this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + + this.documents = []; + } + + isParsed(): boolean { + return this.parsed; + } + + parse(options: OpResponseOptions): void { + // Don't parse again if not needed + if (this.parsed) return; + options = options ?? {}; + + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs; + const promoteValues = options.promoteValues ?? this.opts.promoteValues; + const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers; + const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp; + const validation = this.parseBsonSerializationOptions(options); + + // Set up the options + const bsonOptions: BSONSerializeOptions = { + useBigInt64, + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp, + validation + // Due to the strictness of the BSON libraries validation option we need this cast + } as BSONSerializeOptions & { validation: { utf8: { writeErrors: boolean } } }; + + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : BSON.deserialize(bin, bsonOptions)); + this.index += bsonSize; + } else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw: Document = {}; + fieldsAsRaw[documentsReturnedIn] = true; + bsonOptions.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0] as Buffer, bsonOptions); + this.documents = [doc]; + } + + this.parsed = true; + } + + parseBsonSerializationOptions({ enableUtf8Validation }: BSONSerializeOptions): { + utf8: { writeErrors: false } | false; + } { + if (enableUtf8Validation === false) { + return { utf8: false }; + } + + return { utf8: { writeErrors: false } }; + } +} + +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID + +/** + * @internal + * + * An OP_COMPRESSED request wraps either an OP_QUERY or OP_MSG message. + */ +export class OpCompressedRequest { + constructor( + private command: WriteProtocolMessageType, + private options: { zlibCompressionLevel: number; agreedCompressor: CompressorName } + ) {} + + // Return whether a command contains an uncompressible command term + // Will return true if command contains no uncompressible command terms + static canCompress(command: WriteProtocolMessageType) { + const commandDoc = command instanceof OpMsgRequest ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); + } + + async toBin(): Promise { + const concatenatedOriginalCommandBuffer = Buffer.concat(this.command.toBin()); + // otherwise, compress the message + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + const compressedMessage = await compress(this.options, messageToBeCompressed); + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(this.command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(Compressor[this.options.agreedCompressor], 8); // compressorID + return [msgHeader, compressionDetails, compressedMessage]; + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/connect.ts b/nodejs/node_modules/mongodb/src/cmap/connect.ts new file mode 100644 index 00000000..1b46926c --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/connect.ts @@ -0,0 +1,470 @@ +import type { Socket, SocketConnectOpts } from 'net'; +import * as net from 'net'; +import type { ConnectionOptions as TLSConnectionOpts, TLSSocket } from 'tls'; +import * as tls from 'tls'; + +import type { Document } from '../bson'; +import { LEGACY_HELLO_COMMAND } from '../constants'; +import { getSocks, type SocksLib } from '../deps'; +import { + MongoCompatibilityError, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoRuntimeError, + needsRetryableWriteLabel +} from '../error'; +import { HostAddress, ns, promiseWithResolvers } from '../utils'; +import { AuthContext } from './auth/auth_provider'; +import { AuthMechanism } from './auth/providers'; +import { + type CommandOptions, + Connection, + type ConnectionOptions, + CryptoConnection +} from './connection'; +import { + MAX_SUPPORTED_SERVER_VERSION, + MAX_SUPPORTED_WIRE_VERSION, + MIN_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION +} from './wire_protocol/constants'; + +/** @public */ +export type Stream = Socket | TLSSocket; + +export async function connect(options: ConnectionOptions): Promise { + let connection: Connection | null = null; + try { + const socket = await makeSocket(options); + connection = makeConnection(options, socket); + await performInitialHandshake(connection, options); + return connection; + } catch (error) { + connection?.destroy(); + throw error; + } +} + +export function makeConnection(options: ConnectionOptions, socket: Stream): Connection { + let ConnectionType = options.connectionType ?? Connection; + if (options.autoEncrypter) { + ConnectionType = CryptoConnection; + } + + return new ConnectionType(socket, options); +} + +function checkSupportedServer(hello: Document, options: ConnectionOptions) { + const maxWireVersion = Number(hello.maxWireVersion); + const minWireVersion = Number(hello.minWireVersion); + const serverVersionHighEnough = + !Number.isNaN(maxWireVersion) && maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = + !Number.isNaN(minWireVersion) && minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; + + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify( + hello.minWireVersion + )}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + return new MongoCompatibilityError(message); + } + + const message = `Server at ${options.hostAddress} reports maximum wire version ${ + JSON.stringify(hello.maxWireVersion) ?? 0 + }, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; + return new MongoCompatibilityError(message); +} + +export async function performInitialHandshake( + conn: Connection, + options: ConnectionOptions +): Promise { + const credentials = options.credentials; + + if (credentials) { + if ( + !(credentials.mechanism === AuthMechanism.MONGODB_DEFAULT) && + !options.authProviders.getOrCreateProvider(credentials.mechanism) + ) { + throw new MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`); + } + } + + const authContext = new AuthContext(conn, credentials, options); + conn.authContext = authContext; + + const handshakeDoc = await prepareHandshakeDocument(authContext); + + // @ts-expect-error: TODO(NODE-5141): The options need to be filtered properly, Connection options differ from Command options + const handshakeOptions: CommandOptions = { ...options }; + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; + } + + const start = new Date().getTime(); + const response = await conn.command(ns('admin.$cmd'), handshakeDoc, handshakeOptions); + + if (!('isWritablePrimary' in response)) { + // Provide hello-style response document. + response.isWritablePrimary = response[LEGACY_HELLO_COMMAND]; + } + + if (response.helloOk) { + conn.helloOk = true; + } + + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + throw supportedServerErr; + } + + if (options.loadBalanced) { + if (!response.serviceId) { + throw new MongoCompatibilityError( + 'Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.' + ); + } + } + + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.hello = response; + conn.lastHelloMS = new Date().getTime() - start; + + if (!response.arbiterOnly && credentials) { + // store the response on auth context + authContext.response = response; + + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = options.authProviders.getOrCreateProvider(resolvedCredentials.mechanism); + if (!provider) { + throw new MongoInvalidArgumentError( + `No AuthProvider for ${resolvedCredentials.mechanism} defined.` + ); + } + + try { + await provider.auth(authContext); + } catch (error) { + if (error instanceof MongoError) { + error.addErrorLabel(MongoErrorLabel.HandshakeError); + if (needsRetryableWriteLabel(error, response.maxWireVersion)) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + } + throw error; + } + } + + // Connection establishment is socket creation (tcp handshake, tls handshake, MongoDB handshake (saslStart, saslContinue)) + // Once connection is established, command logging can log events (if enabled) + conn.established = true; +} + +/** + * HandshakeDocument used during authentication. + * @internal + */ +export interface HandshakeDocument extends Document { + /** + * @deprecated Use hello instead + */ + ismaster?: boolean; + hello?: boolean; + helloOk?: boolean; + client: Document; + compression: string[]; + saslSupportedMechs?: string; + loadBalanced?: boolean; +} + +/** + * @internal + * + * This function is only exposed for testing purposes. + */ +export async function prepareHandshakeDocument( + authContext: AuthContext +): Promise { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const clientMetadata: Document = await options.extendedMetadata; + + const handshakeDoc: HandshakeDocument = { + [serverApi?.version || options.loadBalanced === true ? 'hello' : LEGACY_HELLO_COMMAND]: 1, + helloOk: true, + client: clientMetadata, + compression: compressors + }; + + if (options.loadBalanced === true) { + handshakeDoc.loadBalanced = true; + } + + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + + const provider = authContext.options.authProviders.getOrCreateProvider( + AuthMechanism.MONGODB_SCRAM_SHA256 + ); + if (!provider) { + // This auth mechanism is always present. + throw new MongoInvalidArgumentError( + `No AuthProvider for ${AuthMechanism.MONGODB_SCRAM_SHA256} defined.` + ); + } + return provider.prepare(handshakeDoc, authContext); + } + const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism); + if (!provider) { + throw new MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`); + } + return provider.prepare(handshakeDoc, authContext); + } + return handshakeDoc; +} + +/** @public */ +export const LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +] as const; + +/** @public */ +export const LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +] as const; + +function parseConnectOptions(options: ConnectionOptions): SocketConnectOpts { + const hostAddress = options.hostAddress; + if (!hostAddress) throw new MongoInvalidArgumentError('Option "hostAddress" is required'); + + const result: Partial = {}; + for (const name of LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + (result as Document)[name] = options[name]; + } + } + + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result as net.IpcNetConnectOpts; + } else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result as net.TcpNetConnectOpts; + } else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} + +type MakeConnectionOptions = ConnectionOptions & { existingSocket?: Stream }; + +function parseSslOptions(options: MakeConnectionOptions): TLSConnectionOpts { + const result: TLSConnectionOpts = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + (result as Document)[name] = options[name]; + } + } + + if (options.existingSocket) { + result.socket = options.existingSocket; + } + + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + + return result; +} + +export async function makeSocket(options: MakeConnectionOptions): Promise { + const useTLS = options.tls ?? false; + const noDelay = options.noDelay ?? true; + const connectTimeoutMS = options.connectTimeoutMS ?? 30000; + const existingSocket = options.existingSocket; + + let socket: Stream; + + if (options.proxyHost != null) { + // Currently, only Socks5 is supported. + return makeSocks5Connection({ + ...options, + connectTimeoutMS // Should always be present for Socks5 + }); + } + + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); + } + socket = tlsSocket; + } else if (existingSocket) { + // In the TLS case, parseSslOptions() sets options.socket to existingSocket, + // so we only need to handle the non-TLS case here (where existingSocket + // gives us all we need out of the box). + socket = existingSocket; + } else { + socket = net.createConnection(parseConnectOptions(options)); + } + + socket.setKeepAlive(true, 300000); + socket.setTimeout(connectTimeoutMS); + socket.setNoDelay(noDelay); + + let cancellationHandler: ((err: Error) => void) | null = null; + + const { promise: connectedSocket, resolve, reject } = promiseWithResolvers(); + if (existingSocket) { + resolve(socket); + } else { + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + socket + .once(connectEvent, () => resolve(socket)) + .once('error', error => reject(connectionFailureError('error', error))) + .once('timeout', () => reject(connectionFailureError('timeout'))) + .once('close', () => reject(connectionFailureError('close'))); + + if (options.cancellationToken != null) { + cancellationHandler = () => reject(connectionFailureError('cancel')); + options.cancellationToken.once('cancel', cancellationHandler); + } + } + + try { + socket = await connectedSocket; + return socket; + } catch (error) { + socket.destroy(); + throw error; + } finally { + socket.setTimeout(0); + socket.removeAllListeners(); + if (cancellationHandler != null) { + options.cancellationToken?.removeListener('cancel', cancellationHandler); + } + } +} + +let socks: SocksLib | null = null; +function loadSocks() { + if (socks == null) { + const socksImport = getSocks(); + if ('kModuleError' in socksImport) { + throw socksImport.kModuleError; + } + socks = socksImport; + } + return socks; +} + +async function makeSocks5Connection(options: MakeConnectionOptions): Promise { + const hostAddress = HostAddress.fromHostPort( + options.proxyHost ?? '', // proxyHost is guaranteed to set here + options.proxyPort ?? 1080 + ); + + // First, connect to the proxy server itself: + const rawSocket = await makeSocket({ + ...options, + hostAddress, + tls: false, + proxyHost: undefined + }); + + const destination = parseConnectOptions(options) as net.TcpNetConnectOpts; + if (typeof destination.host !== 'string' || typeof destination.port !== 'number') { + throw new MongoInvalidArgumentError('Can only make Socks5 connections to TCP hosts'); + } + + socks ??= loadSocks(); + + try { + // Then, establish the Socks5 proxy connection: + const { socket } = await socks.SocksClient.createConnection({ + existing_socket: rawSocket, + timeout: options.connectTimeoutMS, + command: 'connect', + destination: { + host: destination.host, + port: destination.port + }, + proxy: { + // host and port are ignored because we pass existing_socket + host: 'iLoveJavaScript', + port: 0, + type: 5, + userId: options.proxyUsername || undefined, + password: options.proxyPassword || undefined + } + }); + + // Finally, now treat the resulting duplex stream as the + // socket over which we send and receive wire protocol messages: + return await makeSocket({ + ...options, + existingSocket: socket, + proxyHost: undefined + }); + } catch (error) { + throw connectionFailureError('error', error); + } +} + +function connectionFailureError(type: 'error', cause: Error): MongoNetworkError; +function connectionFailureError(type: 'close' | 'timeout' | 'cancel'): MongoNetworkError; +function connectionFailureError( + type: 'error' | 'close' | 'timeout' | 'cancel', + cause?: Error +): MongoNetworkError { + switch (type) { + case 'error': + return new MongoNetworkError(MongoError.buildErrorMessage(cause), { cause }); + case 'timeout': + return new MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new MongoNetworkError('connection closed'); + case 'cancel': + return new MongoNetworkError('connection establishment was cancelled'); + default: + return new MongoNetworkError('unknown network error'); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/connection.ts b/nodejs/node_modules/mongodb/src/cmap/connection.ts new file mode 100644 index 00000000..bb84c100 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/connection.ts @@ -0,0 +1,739 @@ +import { type Readable, Transform, type TransformCallback } from 'stream'; +import { clearTimeout, setTimeout } from 'timers'; + +import type { BSONSerializeOptions, Document, ObjectId } from '../bson'; +import type { AutoEncrypter } from '../client-side-encryption/auto_encrypter'; +import { + CLOSE, + CLUSTER_TIME_RECEIVED, + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + PINNED, + UNPINNED +} from '../constants'; +import { + MongoCompatibilityError, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoParseError, + MongoServerError, + MongoUnexpectedServerResponseError, + MongoWriteConcernError +} from '../error'; +import type { ServerApi, SupportedNodeConnectionOptions } from '../mongo_client'; +import { type MongoClientAuthProviders } from '../mongo_client_auth_providers'; +import { MongoLoggableComponent, type MongoLogger, SeverityLevel } from '../mongo_logger'; +import { type CancellationToken, TypedEventEmitter } from '../mongo_types'; +import { ReadPreference, type ReadPreferenceLike } from '../read_preference'; +import { ServerType } from '../sdam/common'; +import { applySession, type ClientSession, updateSessionFromResponse } from '../sessions'; +import { + BufferPool, + calculateDurationInMs, + type Callback, + HostAddress, + maxWireVersion, + type MongoDBNamespace, + now, + once, + uuidV4 +} from '../utils'; +import type { WriteConcern } from '../write_concern'; +import type { AuthContext } from './auth/auth_provider'; +import type { MongoCredentials } from './auth/mongo_credentials'; +import { + CommandFailedEvent, + CommandStartedEvent, + CommandSucceededEvent +} from './command_monitoring_events'; +import { + OpCompressedRequest, + OpMsgRequest, + type OpMsgResponse, + OpQueryRequest, + type OpQueryResponse, + type WriteProtocolMessageType +} from './commands'; +import type { Stream } from './connect'; +import type { ClientMetadata } from './handshake/client_metadata'; +import { StreamDescription, type StreamDescriptionOptions } from './stream_description'; +import { type CompressorName, decompressResponse } from './wire_protocol/compression'; +import { onData } from './wire_protocol/on_data'; +import { getReadPreference, isSharded } from './wire_protocol/shared'; + +/** @internal */ +export interface CommandOptions extends BSONSerializeOptions { + secondaryOk?: boolean; + /** Specify read preference if command supports it */ + readPreference?: ReadPreferenceLike; + monitoring?: boolean; + socketTimeoutMS?: number; + /** Session to use for the operation */ + session?: ClientSession; + documentsReturnedIn?: string; + noResponse?: boolean; + omitReadPreference?: boolean; + + // TODO(NODE-2802): Currently the CommandOptions take a property willRetryWrite which is a hint + // from executeOperation that the txnNum should be applied to this command. + // Applying a session to a command should happen as part of command construction, + // most likely in the CommandOperation#executeCommand method, where we have access to + // the details we need to determine if a txnNum should also be applied. + willRetryWrite?: boolean; + + writeConcern?: WriteConcern; + + directConnection?: boolean; +} + +/** @public */ +export interface ProxyOptions { + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; +} + +/** @public */ +export interface ConnectionOptions + extends SupportedNodeConnectionOptions, + StreamDescriptionOptions, + ProxyOptions { + // Internal creation info + id: number | ''; + generation: number; + hostAddress: HostAddress; + /** @internal */ + autoEncrypter?: AutoEncrypter; + serverApi?: ServerApi; + monitorCommands: boolean; + /** @internal */ + connectionType?: any; + credentials?: MongoCredentials; + /** @internal */ + authProviders: MongoClientAuthProviders; + connectTimeoutMS?: number; + tls: boolean; + noDelay?: boolean; + socketTimeoutMS?: number; + cancellationToken?: CancellationToken; + metadata: ClientMetadata; + /** @internal */ + extendedMetadata: Promise; + /** @internal */ + mongoLogger?: MongoLogger | undefined; +} + +/** @public */ +export type ConnectionEvents = { + commandStarted(event: CommandStartedEvent): void; + commandSucceeded(event: CommandSucceededEvent): void; + commandFailed(event: CommandFailedEvent): void; + clusterTimeReceived(clusterTime: Document): void; + close(): void; + pinned(pinType: string): void; + unpinned(pinType: string): void; +}; + +/** @internal */ +export function hasSessionSupport(conn: Connection): boolean { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null; +} + +function streamIdentifier(stream: Stream, options: ConnectionOptions): string { + if (options.proxyHost) { + // If proxy options are specified, the properties of `stream` itself + // will not accurately reflect what endpoint this is connected to. + return options.hostAddress.toString(); + } + + const { remoteAddress, remotePort } = stream; + if (typeof remoteAddress === 'string' && typeof remotePort === 'number') { + return HostAddress.fromHostPort(remoteAddress, remotePort).toString(); + } + + return uuidV4().toString('hex'); +} + +/** @internal */ +export class Connection extends TypedEventEmitter { + public id: number | ''; + public address: string; + public lastHelloMS = -1; + public serverApi?: ServerApi; + public helloOk = false; + public authContext?: AuthContext; + public delayedTimeoutId: NodeJS.Timeout | null = null; + public generation: number; + public readonly description: Readonly; + /** + * Represents if the connection has been established: + * - TCP handshake + * - TLS negotiated + * - mongodb handshake (saslStart, saslContinue), includes authentication + * + * Once connection is established, command logging can log events (if enabled) + */ + public established: boolean; + /** Indicates that the connection (including underlying TCP socket) has been closed. */ + public closed = false; + + private lastUseTime: number; + private clusterTime: Document | null = null; + private error: Error | null = null; + private dataEvents: AsyncGenerator | null = null; + + private readonly socketTimeoutMS: number; + private readonly monitorCommands: boolean; + private readonly socket: Stream; + private readonly messageStream: Readable; + + /** @event */ + static readonly COMMAND_STARTED = COMMAND_STARTED; + /** @event */ + static readonly COMMAND_SUCCEEDED = COMMAND_SUCCEEDED; + /** @event */ + static readonly COMMAND_FAILED = COMMAND_FAILED; + /** @event */ + static readonly CLUSTER_TIME_RECEIVED = CLUSTER_TIME_RECEIVED; + /** @event */ + static readonly CLOSE = CLOSE; + /** @event */ + static readonly PINNED = PINNED; + /** @event */ + static readonly UNPINNED = UNPINNED; + + constructor(stream: Stream, options: ConnectionOptions) { + super(); + + this.socket = stream; + this.id = options.id; + this.address = streamIdentifier(stream, options); + this.socketTimeoutMS = options.socketTimeoutMS ?? 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.mongoLogger = options.mongoLogger; + this.established = false; + + this.description = new StreamDescription(this.address, options); + this.generation = options.generation; + this.lastUseTime = now(); + + this.messageStream = this.socket + .on('error', this.onError.bind(this)) + .pipe(new SizedMessageTransform({ connection: this })) + .on('error', this.onError.bind(this)); + this.socket.on('close', this.onClose.bind(this)); + this.socket.on('timeout', this.onTimeout.bind(this)); + } + + public get hello() { + return this.description.hello; + } + + // the `connect` method stores the result of the handshake hello on the connection + public set hello(response: Document | null) { + this.description.receiveResponse(response); + Object.freeze(this.description); + } + + public get serviceId(): ObjectId | undefined { + return this.hello?.serviceId; + } + + public get loadBalanced(): boolean { + return this.description.loadBalanced; + } + + public get idleTime(): number { + return calculateDurationInMs(this.lastUseTime); + } + + private get hasSessionSupport(): boolean { + return this.description.logicalSessionTimeoutMinutes != null; + } + + private get supportsOpMsg(): boolean { + return ( + this.description != null && + maxWireVersion(this) >= 6 && + !this.description.__nodejs_mock_server__ + ); + } + + private get shouldEmitAndLogCommand(): boolean { + return ( + (this.monitorCommands || + (this.established && + !this.authContext?.reauthenticating && + this.mongoLogger?.willLog(MongoLoggableComponent.COMMAND, SeverityLevel.DEBUG))) ?? + false + ); + } + + public markAvailable(): void { + this.lastUseTime = now(); + } + + public onError(error: Error) { + this.cleanup(error); + } + + private onClose() { + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(new MongoNetworkError(message)); + } + + private onTimeout() { + this.delayedTimeoutId = setTimeout(() => { + const message = `connection ${this.id} to ${this.address} timed out`; + const beforeHandshake = this.hello == null; + this.cleanup(new MongoNetworkTimeoutError(message, { beforeHandshake })); + }, 1).unref(); // No need for this timer to hold the event loop open + } + + public destroy(): void { + if (this.closed) { + return; + } + + // load balanced mode requires that these listeners remain on the connection + // after cleanup on timeouts, errors or close so we remove them before calling + // cleanup. + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(new MongoNetworkError(message)); + } + + /** + * A method that cleans up the connection. When `force` is true, this method + * forcibly destroys the socket. + * + * If an error is provided, any in-flight operations will be closed with the error. + * + * This method does nothing if the connection is already closed. + */ + private cleanup(error: Error): void { + if (this.closed) { + return; + } + + this.socket.destroy(); + this.error = error; + this.dataEvents?.throw(error).then(undefined, () => null); // squash unhandled rejection + this.closed = true; + this.emit(Connection.CLOSE); + } + + private prepareCommand(db: string, command: Document, options: CommandOptions) { + let cmd = { ...command }; + + const readPreference = getReadPreference(options); + const session = options?.session; + + let clusterTime = this.clusterTime; + + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + cmd.apiVersion = version; + if (strict != null) cmd.apiStrict = strict; + if (deprecationErrors != null) cmd.apiDeprecationErrors = deprecationErrors; + } + + if (this.hasSessionSupport && session) { + if ( + session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) + ) { + clusterTime = session.clusterTime; + } + + const sessionError = applySession(session, cmd, options); + if (sessionError) throw sessionError; + } else if (session?.explicit) { + throw new MongoCompatibilityError('Current topology does not support sessions'); + } + + // if we have a known cluster time, gossip it + if (clusterTime) { + cmd.$clusterTime = clusterTime; + } + + // For standalone, drivers MUST NOT set $readPreference. + if (this.description.type !== ServerType.Standalone) { + if ( + !isSharded(this) && + !this.description.loadBalanced && + this.supportsOpMsg && + options.directConnection === true && + readPreference?.mode === 'primary' + ) { + // For mongos and load balancers with 'primary' mode, drivers MUST NOT set $readPreference. + // For all other types with a direct connection, if the read preference is 'primary' + // (driver sets 'primary' as default if no read preference is configured), + // the $readPreference MUST be set to 'primaryPreferred' + // to ensure that any server type can handle the request. + cmd.$readPreference = ReadPreference.primaryPreferred.toJSON(); + } else if (isSharded(this) && !this.supportsOpMsg && readPreference?.mode !== 'primary') { + // When sending a read operation via OP_QUERY and the $readPreference modifier, + // the query MUST be provided using the $query modifier. + cmd = { + $query: cmd, + $readPreference: readPreference.toJSON() + }; + } else if (readPreference?.mode !== 'primary') { + // For mode 'primary', drivers MUST NOT set $readPreference. + // For all other read preference modes (i.e. 'secondary', 'primaryPreferred', ...), + // drivers MUST set $readPreference + cmd.$readPreference = readPreference.toJSON(); + } + } + + const commandOptions = { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + secondaryOk: readPreference.secondaryOk(), + ...options + }; + + const message = this.supportsOpMsg + ? new OpMsgRequest(db, cmd, commandOptions) + : new OpQueryRequest(db, cmd, commandOptions); + + return message; + } + + private async *sendWire(message: WriteProtocolMessageType, options: CommandOptions) { + this.throwIfAborted(); + + if (typeof options.socketTimeoutMS === 'number') { + this.socket.setTimeout(options.socketTimeoutMS); + } else if (this.socketTimeoutMS !== 0) { + this.socket.setTimeout(this.socketTimeoutMS); + } + + try { + await this.writeCommand(message, { + agreedCompressor: this.description.compressor ?? 'none', + zlibCompressionLevel: this.description.zlibCompressionLevel + }); + + if (options.noResponse) { + yield { ok: 1 }; + return; + } + + this.throwIfAborted(); + + for await (const response of this.readMany()) { + this.socket.setTimeout(0); + response.parse(options); + + const [document] = response.documents; + + if (!Buffer.isBuffer(document)) { + const { session } = options; + if (session) { + updateSessionFromResponse(session, document); + } + + if (document.$clusterTime) { + this.clusterTime = document.$clusterTime; + this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + } + + yield document; + this.throwIfAborted(); + + if (typeof options.socketTimeoutMS === 'number') { + this.socket.setTimeout(options.socketTimeoutMS); + } else if (this.socketTimeoutMS !== 0) { + this.socket.setTimeout(this.socketTimeoutMS); + } + } + } finally { + this.socket.setTimeout(0); + } + } + + private async *sendCommand( + ns: MongoDBNamespace, + command: Document, + options: CommandOptions = {} + ) { + const message = this.prepareCommand(ns.db, command, options); + + let started = 0; + if (this.shouldEmitAndLogCommand) { + started = now(); + this.emitAndLogCommand( + this.monitorCommands, + Connection.COMMAND_STARTED, + message.databaseName, + this.established, + new CommandStartedEvent(this, message, this.description.serverConnectionId) + ); + } + + let document; + try { + this.throwIfAborted(); + for await (document of this.sendWire(message, options)) { + if (!Buffer.isBuffer(document) && document.writeConcernError) { + throw new MongoWriteConcernError(document.writeConcernError, document); + } + + if ( + !Buffer.isBuffer(document) && + (document.ok === 0 || document.$err || document.errmsg || document.code) + ) { + throw new MongoServerError(document); + } + + if (this.shouldEmitAndLogCommand) { + this.emitAndLogCommand( + this.monitorCommands, + Connection.COMMAND_SUCCEEDED, + message.databaseName, + this.established, + new CommandSucceededEvent( + this, + message, + options.noResponse ? undefined : document, + started, + this.description.serverConnectionId + ) + ); + } + + yield document; + this.throwIfAborted(); + } + } catch (error) { + if (this.shouldEmitAndLogCommand) { + if (error.name === 'MongoWriteConcernError') { + this.emitAndLogCommand( + this.monitorCommands, + Connection.COMMAND_SUCCEEDED, + message.databaseName, + this.established, + new CommandSucceededEvent( + this, + message, + options.noResponse ? undefined : document, + started, + this.description.serverConnectionId + ) + ); + } else { + this.emitAndLogCommand( + this.monitorCommands, + Connection.COMMAND_FAILED, + message.databaseName, + this.established, + new CommandFailedEvent( + this, + message, + error, + started, + this.description.serverConnectionId + ) + ); + } + } + throw error; + } + } + + public async command( + ns: MongoDBNamespace, + command: Document, + options: CommandOptions = {} + ): Promise { + this.throwIfAborted(); + for await (const document of this.sendCommand(ns, command, options)) { + return document; + } + throw new MongoUnexpectedServerResponseError('Unable to get response from server'); + } + + public exhaustCommand( + ns: MongoDBNamespace, + command: Document, + options: CommandOptions, + replyListener: Callback + ) { + const exhaustLoop = async () => { + this.throwIfAborted(); + for await (const reply of this.sendCommand(ns, command, options)) { + replyListener(undefined, reply); + this.throwIfAborted(); + } + throw new MongoUnexpectedServerResponseError('Server ended moreToCome unexpectedly'); + }; + exhaustLoop().catch(replyListener); + } + + private throwIfAborted() { + if (this.error) throw this.error; + } + + /** + * @internal + * + * Writes an OP_MSG or OP_QUERY request to the socket, optionally compressing the command. This method + * waits until the socket's buffer has emptied (the Nodejs socket `drain` event has fired). + */ + private async writeCommand( + command: WriteProtocolMessageType, + options: { agreedCompressor?: CompressorName; zlibCompressionLevel?: number } + ): Promise { + const finalCommand = + options.agreedCompressor === 'none' || !OpCompressedRequest.canCompress(command) + ? command + : new OpCompressedRequest(command, { + agreedCompressor: options.agreedCompressor ?? 'none', + zlibCompressionLevel: options.zlibCompressionLevel ?? 0 + }); + + const buffer = Buffer.concat(await finalCommand.toBin()); + + if (this.socket.write(buffer)) return; + return once(this.socket, 'drain'); + } + + /** + * @internal + * + * Returns an async generator that yields full wire protocol messages from the underlying socket. This function + * yields messages until `moreToCome` is false or not present in a response, or the caller cancels the request + * by calling `return` on the generator. + * + * Note that `for-await` loops call `return` automatically when the loop is exited. + */ + private async *readMany(): AsyncGenerator { + try { + this.dataEvents = onData(this.messageStream); + for await (const message of this.dataEvents) { + const response = await decompressResponse(message); + yield response; + + if (!response.moreToCome) { + return; + } + } + } finally { + this.dataEvents = null; + this.throwIfAborted(); + } + } +} + +/** @internal */ +export class SizedMessageTransform extends Transform { + bufferPool: BufferPool; + connection: Connection; + + constructor({ connection }: { connection: Connection }) { + super({ objectMode: false }); + this.bufferPool = new BufferPool(); + this.connection = connection; + } + + override _transform(chunk: Buffer, encoding: unknown, callback: TransformCallback): void { + if (this.connection.delayedTimeoutId != null) { + clearTimeout(this.connection.delayedTimeoutId); + this.connection.delayedTimeoutId = null; + } + + this.bufferPool.append(chunk); + const sizeOfMessage = this.bufferPool.getInt32(); + + if (sizeOfMessage == null) { + return callback(); + } + + if (sizeOfMessage < 0) { + return callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}, too small`)); + } + + if (sizeOfMessage > this.bufferPool.length) { + return callback(); + } + + const message = this.bufferPool.read(sizeOfMessage); + return callback(null, message); + } +} + +/** @internal */ +export class CryptoConnection extends Connection { + /** @internal */ + autoEncrypter?: AutoEncrypter; + + constructor(stream: Stream, options: ConnectionOptions) { + super(stream, options); + this.autoEncrypter = options.autoEncrypter; + } + + /** @internal @override */ + override async command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions + ): Promise { + const { autoEncrypter } = this; + if (!autoEncrypter) { + throw new MongoMissingDependencyError('No AutoEncrypter available for encryption'); + } + + const serverWireVersion = maxWireVersion(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options); + } + + if (serverWireVersion < 8) { + throw new MongoCompatibilityError( + 'Auto-encryption requires a minimum MongoDB version of 4.2' + ); + } + + // Save sort or indexKeys based on the command being run + // the encrypt API serializes our JS objects to BSON to pass to the native code layer + // and then deserializes the encrypted result, the protocol level components + // of the command (ex. sort) are then converted to JS objects potentially losing + // import key order information. These fields are never encrypted so we can save the values + // from before the encryption and replace them after encryption has been performed + const sort: Map | null = cmd.find || cmd.findAndModify ? cmd.sort : null; + const indexKeys: Map[] | null = cmd.createIndexes + ? cmd.indexes.map((index: { key: Map }) => index.key) + : null; + + const encrypted = await autoEncrypter.encrypt(ns.toString(), cmd, options); + + // Replace the saved values + if (sort != null && (cmd.find || cmd.findAndModify)) { + encrypted.sort = sort; + } + + if (indexKeys != null && cmd.createIndexes) { + for (const [offset, index] of indexKeys.entries()) { + // @ts-expect-error `encrypted` is a generic "command", but we've narrowed for only `createIndexes` commands here + encrypted.indexes[offset].key = index; + } + } + + const response = await super.command(ns, encrypted, options); + + return autoEncrypter.decrypt(response, options); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/connection_pool.ts b/nodejs/node_modules/mongodb/src/cmap/connection_pool.ts new file mode 100644 index 00000000..b49c3d1d --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/connection_pool.ts @@ -0,0 +1,841 @@ +import { clearTimeout, setTimeout } from 'timers'; + +import type { ObjectId } from '../bson'; +import { + APM_EVENTS, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_READY +} from '../constants'; +import { + type AnyError, + type MongoError, + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoNetworkError, + MongoRuntimeError, + MongoServerError +} from '../error'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import { + type Callback, + List, + makeCounter, + promiseWithResolvers, + TimeoutController +} from '../utils'; +import { connect } from './connect'; +import { Connection, type ConnectionEvents, type ConnectionOptions } from './connection'; +import { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolReadyEvent, + ConnectionReadyEvent +} from './connection_pool_events'; +import { + PoolClearedError, + PoolClearedOnNetworkError, + PoolClosedError, + WaitQueueTimeoutError +} from './errors'; +import { ConnectionPoolMetrics } from './metrics'; + +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPending = Symbol('pending'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); +/** @internal */ +const kPoolState = Symbol('poolState'); + +/** @public */ +export interface ConnectionPoolOptions extends Omit { + /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */ + maxPoolSize: number; + /** The minimum number of connections that MUST exist at any moment in a single connection pool. */ + minPoolSize: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting: number; + /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */ + maxIdleTimeMS: number; + /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */ + waitQueueTimeoutMS: number; + /** If we are in load balancer mode. */ + loadBalanced: boolean; + /** @internal */ + minPoolSizeCheckFrequencyMS?: number; +} + +/** @internal */ +export interface WaitQueueMember { + resolve: (conn: Connection) => void; + reject: (err: AnyError) => void; + timeoutController: TimeoutController; + [kCancelled]?: boolean; +} + +/** @internal */ +export const PoolState = Object.freeze({ + paused: 'paused', + ready: 'ready', + closed: 'closed' +} as const); + +/** + * @public + * @deprecated This interface is deprecated and will be removed in a future release as it is not used + * in the driver + */ +export interface CloseOptions { + force?: boolean; +} + +/** @public */ +export type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolReady(event: ConnectionPoolReadyEvent): void; + connectionPoolClosed(event: ConnectionPoolClosedEvent): void; + connectionPoolCleared(event: ConnectionPoolClearedEvent): void; + connectionCreated(event: ConnectionCreatedEvent): void; + connectionReady(event: ConnectionReadyEvent): void; + connectionClosed(event: ConnectionClosedEvent): void; + connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void; + connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void; + connectionCheckedOut(event: ConnectionCheckedOutEvent): void; + connectionCheckedIn(event: ConnectionCheckedInEvent): void; +} & Omit; + +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +export class ConnectionPool extends TypedEventEmitter { + options: Readonly; + [kPoolState]: (typeof PoolState)[keyof typeof PoolState]; + [kServer]: Server; + [kConnections]: List; + [kPending]: number; + [kCheckedOut]: Set; + [kMinPoolSizeTimer]?: NodeJS.Timeout; + /** + * An integer representing the SDAM generation of the pool + */ + [kGeneration]: number; + /** + * A map of generations to service ids + */ + [kServiceGenerations]: Map; + [kConnectionCounter]: Generator; + [kCancellationToken]: CancellationToken; + [kWaitQueue]: List; + [kMetrics]: ConnectionPoolMetrics; + [kProcessingWaitQueue]: boolean; + + /** + * Emitted when the connection pool is created. + * @event + */ + static readonly CONNECTION_POOL_CREATED = CONNECTION_POOL_CREATED; + /** + * Emitted once when the connection pool is closed + * @event + */ + static readonly CONNECTION_POOL_CLOSED = CONNECTION_POOL_CLOSED; + /** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ + static readonly CONNECTION_POOL_CLEARED = CONNECTION_POOL_CLEARED; + /** + * Emitted each time the connection pool is marked ready + * @event + */ + static readonly CONNECTION_POOL_READY = CONNECTION_POOL_READY; + /** + * Emitted when a connection is created. + * @event + */ + static readonly CONNECTION_CREATED = CONNECTION_CREATED; + /** + * Emitted when a connection becomes established, and is ready to use + * @event + */ + static readonly CONNECTION_READY = CONNECTION_READY; + /** + * Emitted when a connection is closed + * @event + */ + static readonly CONNECTION_CLOSED = CONNECTION_CLOSED; + /** + * Emitted when an attempt to check out a connection begins + * @event + */ + static readonly CONNECTION_CHECK_OUT_STARTED = CONNECTION_CHECK_OUT_STARTED; + /** + * Emitted when an attempt to check out a connection fails + * @event + */ + static readonly CONNECTION_CHECK_OUT_FAILED = CONNECTION_CHECK_OUT_FAILED; + /** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ + static readonly CONNECTION_CHECKED_OUT = CONNECTION_CHECKED_OUT; + /** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ + static readonly CONNECTION_CHECKED_IN = CONNECTION_CHECKED_IN; + + constructor(server: Server, options: ConnectionPoolOptions) { + super(); + + this.options = Object.freeze({ + connectionType: Connection, + ...options, + maxPoolSize: options.maxPoolSize ?? 100, + minPoolSize: options.minPoolSize ?? 0, + maxConnecting: options.maxConnecting ?? 2, + maxIdleTimeMS: options.maxIdleTimeMS ?? 0, + waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, + minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, + autoEncrypter: options.autoEncrypter + }); + + if (this.options.minPoolSize > this.options.maxPoolSize) { + throw new MongoInvalidArgumentError( + 'Connection pool minimum size must not be greater than maximum pool size' + ); + } + + this[kPoolState] = PoolState.paused; + this[kServer] = server; + this[kConnections] = new List(); + this[kPending] = 0; + this[kCheckedOut] = new Set(); + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = makeCounter(1); + this[kCancellationToken] = new CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new List(); + this[kMetrics] = new ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + + this.mongoLogger = this[kServer].topology.client?.mongoLogger; + this.component = 'connection'; + + process.nextTick(() => { + this.emitAndLog(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this)); + }); + } + + /** The address of the endpoint the pool is connected to */ + get address(): string { + return this.options.hostAddress.toString(); + } + + /** + * Check if the pool has been closed + * + * TODO(NODE-3263): We can remove this property once shell no longer needs it + */ + get closed(): boolean { + return this[kPoolState] === PoolState.closed; + } + + /** An integer representing the SDAM generation of the pool */ + get generation(): number { + return this[kGeneration]; + } + + /** An integer expressing how many total connections (available + pending + in use) the pool currently has */ + get totalConnectionCount(): number { + return ( + this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount + ); + } + + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount(): number { + return this[kConnections].length; + } + + get pendingConnectionCount(): number { + return this[kPending]; + } + + get currentCheckedOutCount(): number { + return this[kCheckedOut].size; + } + + get waitQueueSize(): number { + return this[kWaitQueue].length; + } + + get loadBalanced(): boolean { + return this.options.loadBalanced; + } + + get serviceGenerations(): Map { + return this[kServiceGenerations]; + } + + get serverError() { + return this[kServer].description.error; + } + + /** + * This is exposed ONLY for use in mongosh, to enable + * killing all connections if a user quits the shell with + * operations in progress. + * + * This property may be removed as a part of NODE-3263. + */ + get checkedOutConnections() { + return this[kCheckedOut]; + } + + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + private waitQueueErrorMetrics(): string { + return this[kMetrics].info(this.options.maxPoolSize); + } + + /** + * Set the pool state to "ready" + */ + ready(): void { + if (this[kPoolState] !== PoolState.paused) { + return; + } + this[kPoolState] = PoolState.ready; + this.emitAndLog(ConnectionPool.CONNECTION_POOL_READY, new ConnectionPoolReadyEvent(this)); + clearTimeout(this[kMinPoolSizeTimer]); + this.ensureMinPoolSize(); + } + + /** + * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it + * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or + * explicitly destroyed by the new owner. + */ + async checkOut(): Promise { + this.emitAndLog( + ConnectionPool.CONNECTION_CHECK_OUT_STARTED, + new ConnectionCheckOutStartedEvent(this) + ); + + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + + const { promise, resolve, reject } = promiseWithResolvers(); + const waitQueueMember: WaitQueueMember = { + resolve, + reject, + timeoutController: new TimeoutController(waitQueueTimeoutMS) + }; + waitQueueMember.timeoutController.signal.addEventListener('abort', () => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timeoutController.clear(); + + this.emitAndLog( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'timeout') + ); + waitQueueMember.reject( + new WaitQueueTimeoutError( + this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', + this.address + ) + ); + }); + + this[kWaitQueue].push(waitQueueMember); + process.nextTick(() => this.processWaitQueue()); + + return promise; + } + + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection: Connection): void { + if (!this[kCheckedOut].has(connection)) { + return; + } + const poolClosed = this.closed; + const stale = this.connectionIsStale(connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + + this[kCheckedOut].delete(connection); + this.emitAndLog( + ConnectionPool.CONNECTION_CHECKED_IN, + new ConnectionCheckedInEvent(this, connection) + ); + + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + this.destroyConnection(connection, reason); + } + + process.nextTick(() => this.processWaitQueue()); + } + + /** + * Clear the pool + * + * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a + * previous generation will eventually be pruned during subsequent checkouts. + */ + clear(options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {}): void { + if (this.closed) { + return; + } + + // handle load balanced case + if (this.loadBalanced) { + const { serviceId } = options; + if (!serviceId) { + throw new MongoRuntimeError( + 'ConnectionPool.clear() called in load balanced mode with no serviceId.' + ); + } + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + throw new MongoRuntimeError('Service generations are required in load balancer mode.'); + } else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); + } + this.emitAndLog( + ConnectionPool.CONNECTION_POOL_CLEARED, + new ConnectionPoolClearedEvent(this, { serviceId }) + ); + return; + } + // handle non load-balanced case + const interruptInUseConnections = options.interruptInUseConnections ?? false; + const oldGeneration = this[kGeneration]; + this[kGeneration] += 1; + const alreadyPaused = this[kPoolState] === PoolState.paused; + this[kPoolState] = PoolState.paused; + + this.clearMinPoolSizeTimer(); + if (!alreadyPaused) { + this.emitAndLog( + ConnectionPool.CONNECTION_POOL_CLEARED, + new ConnectionPoolClearedEvent(this, { + interruptInUseConnections + }) + ); + } + + if (interruptInUseConnections) { + process.nextTick(() => this.interruptInUseConnections(oldGeneration)); + } + + this.processWaitQueue(); + } + + /** + * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. + * + * Only connections where `connection.generation <= minGeneration` are killed. + */ + private interruptInUseConnections(minGeneration: number) { + for (const connection of this[kCheckedOut]) { + if (connection.generation <= minGeneration) { + connection.onError(new PoolClearedOnNetworkError(this)); + this.checkIn(connection); + } + } + } + + /** Close the pool */ + close(): void { + if (this.closed) { + return; + } + + // immediately cancel any in-flight connections + this[kCancellationToken].emit('cancel'); + + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + + this[kPoolState] = PoolState.closed; + this.clearMinPoolSizeTimer(); + this.processWaitQueue(); + + for (const conn of this[kConnections]) { + this.emitAndLog( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, conn, 'poolClosed') + ); + conn.destroy(); + } + this[kConnections].clear(); + this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLOSED, new ConnectionPoolClosedEvent(this)); + } + + /** + * @internal + * Reauthenticate a connection + */ + async reauthenticate(connection: Connection): Promise { + const authContext = connection.authContext; + if (!authContext) { + throw new MongoRuntimeError('No auth context found on connection.'); + } + const credentials = authContext.credentials; + if (!credentials) { + throw new MongoMissingCredentialsError( + 'Connection is missing credentials when asked to reauthenticate' + ); + } + + const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello); + const provider = this[kServer].topology.client.s.authProviders.getOrCreateProvider( + resolvedCredentials.mechanism + ); + + if (!provider) { + throw new MongoMissingCredentialsError( + `Reauthenticate failed due to no auth provider for ${credentials.mechanism}` + ); + } + + await provider.reauth(authContext); + + return; + } + + /** Clear the min pool size timer */ + private clearMinPoolSizeTimer(): void { + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + } + + private destroyConnection( + connection: Connection, + reason: 'error' | 'idle' | 'stale' | 'poolClosed' + ) { + this.emitAndLog( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, connection, reason) + ); + // destroy the connection + connection.destroy(); + } + + private connectionIsStale(connection: Connection) { + const serviceId = connection.serviceId; + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + return connection.generation !== generation; + } + + return connection.generation !== this[kGeneration]; + } + + private connectionIsIdle(connection: Connection) { + return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); + } + + /** + * Destroys a connection if the connection is perished. + * + * @returns `true` if the connection was destroyed, `false` otherwise. + */ + private destroyConnectionIfPerished(connection: Connection): boolean { + const isStale = this.connectionIsStale(connection); + const isIdle = this.connectionIsIdle(connection); + if (!isStale && !isIdle && !connection.closed) { + return false; + } + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + this.destroyConnection(connection, reason); + return true; + } + + private createConnection(callback: Callback) { + const connectOptions: ConnectionOptions = { + ...this.options, + id: this[kConnectionCounter].next().value, + generation: this[kGeneration], + cancellationToken: this[kCancellationToken], + mongoLogger: this.mongoLogger, + authProviders: this[kServer].topology.client.s.authProviders + }; + + this[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + this.emitAndLog( + ConnectionPool.CONNECTION_CREATED, + new ConnectionCreatedEvent(this, { id: connectOptions.id }) + ); + + connect(connectOptions).then( + connection => { + // The pool might have closed since we started trying to create a connection + if (this[kPoolState] !== PoolState.ready) { + this[kPending]--; + connection.destroy(); + callback(this.closed ? new PoolClosedError(this) : new PoolClearedError(this)); + return; + } + + // forward all events from the connection to the pool + for (const event of [...APM_EVENTS, Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e: any) => this.emit(event, e)); + } + + if (this.loadBalanced) { + connection.on(Connection.PINNED, pinType => this[kMetrics].markPinned(pinType)); + connection.on(Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType)); + + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = this.serviceGenerations.get(sid))) { + connection.generation = generation; + } else { + this.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + + connection.markAvailable(); + this.emitAndLog( + ConnectionPool.CONNECTION_READY, + new ConnectionReadyEvent(this, connection) + ); + + this[kPending]--; + callback(undefined, connection); + }, + error => { + this[kPending]--; + this.emitAndLog( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent( + this, + { id: connectOptions.id, serviceId: undefined }, + 'error', + // TODO(NODE-5192): Remove this cast + error as MongoError + ) + ); + if (error instanceof MongoNetworkError || error instanceof MongoServerError) { + error.connectionGeneration = connectOptions.generation; + } + callback(error ?? new MongoRuntimeError('Connection creation failed without error')); + } + ); + } + + private ensureMinPoolSize() { + const minPoolSize = this.options.minPoolSize; + if (this[kPoolState] !== PoolState.ready || minPoolSize === 0) { + return; + } + + this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection)); + + if ( + this.totalConnectionCount < minPoolSize && + this.pendingConnectionCount < this.options.maxConnecting + ) { + // NOTE: ensureMinPoolSize should not try to get all the pending + // connection permits because that potentially delays the availability of + // the connection to a checkout request + this.createConnection((err, connection) => { + if (err) { + this[kServer].handleError(err); + } + if (!err && connection) { + this[kConnections].push(connection); + process.nextTick(() => this.processWaitQueue()); + } + if (this[kPoolState] === PoolState.ready) { + clearTimeout(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = setTimeout( + () => this.ensureMinPoolSize(), + this.options.minPoolSizeCheckFrequencyMS + ); + } + }); + } else { + clearTimeout(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = setTimeout( + () => this.ensureMinPoolSize(), + this.options.minPoolSizeCheckFrequencyMS + ); + } + } + + private processWaitQueue() { + if (this[kProcessingWaitQueue]) { + return; + } + this[kProcessingWaitQueue] = true; + + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].first(); + if (!waitQueueMember) { + this[kWaitQueue].shift(); + continue; + } + + if (waitQueueMember[kCancelled]) { + this[kWaitQueue].shift(); + continue; + } + + if (this[kPoolState] !== PoolState.ready) { + const reason = this.closed ? 'poolClosed' : 'connectionError'; + const error = this.closed ? new PoolClosedError(this) : new PoolClearedError(this); + this.emitAndLog( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, reason, error) + ); + waitQueueMember.timeoutController.clear(); + this[kWaitQueue].shift(); + waitQueueMember.reject(error); + continue; + } + + if (!this.availableConnectionCount) { + break; + } + + const connection = this[kConnections].shift(); + if (!connection) { + break; + } + + if (!this.destroyConnectionIfPerished(connection)) { + this[kCheckedOut].add(connection); + this.emitAndLog( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(this, connection) + ); + waitQueueMember.timeoutController.clear(); + + this[kWaitQueue].shift(); + waitQueueMember.resolve(connection); + } + } + + const { maxPoolSize, maxConnecting } = this.options; + while ( + this.waitQueueSize > 0 && + this.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize) + ) { + const waitQueueMember = this[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + this.createConnection((err, connection) => { + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + this[kConnections].push(connection); + } + } else { + if (err) { + this.emitAndLog( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + // TODO(NODE-5192): Remove this cast + new ConnectionCheckOutFailedEvent(this, 'connectionError', err as MongoError) + ); + waitQueueMember.reject(err); + } else if (connection) { + this[kCheckedOut].add(connection); + this.emitAndLog( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(this, connection) + ); + waitQueueMember.resolve(connection); + } + + waitQueueMember.timeoutController.clear(); + } + process.nextTick(() => this.processWaitQueue()); + }); + } + this[kProcessingWaitQueue] = false; + } +} + +/** + * A callback provided to `withConnection` + * @internal + * + * @param error - An error instance representing the error during the execution. + * @param connection - The managed connection which was checked out of the pool. + * @param callback - A function to call back after connection management is complete + */ +export type WithConnectionCallback = ( + error: MongoError | undefined, + connection: Connection | undefined, + callback: Callback +) => void; diff --git a/nodejs/node_modules/mongodb/src/cmap/connection_pool_events.ts b/nodejs/node_modules/mongodb/src/cmap/connection_pool_events.ts new file mode 100644 index 00000000..379bc2d5 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/connection_pool_events.ts @@ -0,0 +1,268 @@ +import type { ObjectId } from '../bson'; +import { + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_READY +} from '../constants'; +import type { MongoError } from '../error'; +import type { Connection } from './connection'; +import type { ConnectionPool, ConnectionPoolOptions } from './connection_pool'; + +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +export abstract class ConnectionPoolMonitoringEvent { + /** A timestamp when the event was created */ + time: Date; + /** The address (host/port pair) of the pool */ + address: string; + /** @internal */ + abstract name: + | typeof CONNECTION_CHECK_OUT_FAILED + | typeof CONNECTION_CHECK_OUT_STARTED + | typeof CONNECTION_CHECKED_IN + | typeof CONNECTION_CHECKED_OUT + | typeof CONNECTION_CLOSED + | typeof CONNECTION_CREATED + | typeof CONNECTION_POOL_CLEARED + | typeof CONNECTION_POOL_CLOSED + | typeof CONNECTION_POOL_CREATED + | typeof CONNECTION_POOL_READY + | typeof CONNECTION_READY; + + /** @internal */ + constructor(pool: ConnectionPool) { + this.time = new Date(); + this.address = pool.address; + } +} + +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +export class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** The options used to create this connection pool */ + options: Pick< + ConnectionPoolOptions, + 'maxPoolSize' | 'minPoolSize' | 'maxConnecting' | 'maxIdleTimeMS' | 'waitQueueTimeoutMS' + >; + /** @internal */ + name = CONNECTION_POOL_CREATED; + + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + const { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS } = + pool.options; + this.options = { maxConnecting, maxPoolSize, minPoolSize, maxIdleTimeMS, waitQueueTimeoutMS }; + } +} + +/** + * An event published when a connection pool is ready + * @public + * @category Event + */ +export class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + name = CONNECTION_POOL_READY; + + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +export class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + name = CONNECTION_POOL_CLOSED; + + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +export class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** A monotonically increasing, per-pool id for the newly created connection */ + connectionId: number | ''; + /** @internal */ + name = CONNECTION_CREATED; + + /** @internal */ + constructor(pool: ConnectionPool, connection: { id: number | '' }) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +export class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** @internal */ + name = CONNECTION_READY; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is closed + * @public + * @category Event + */ +export class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** The reason the connection was closed */ + reason: string; + serviceId?: ObjectId; + /** @internal */ + name = CONNECTION_CLOSED; + /** @internal */ + error: MongoError | null; + + /** @internal */ + constructor( + pool: ConnectionPool, + connection: Pick, + reason: 'idle' | 'stale' | 'poolClosed' | 'error', + error?: MongoError + ) { + super(pool); + this.connectionId = connection.id; + this.reason = reason; + this.serviceId = connection.serviceId; + this.error = error ?? null; + } +} + +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +export class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + name = CONNECTION_CHECK_OUT_STARTED; + + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +export class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** The reason the attempt to check out failed */ + reason: string; + /** @internal */ + error?: MongoError; + /** @internal */ + name = CONNECTION_CHECK_OUT_FAILED; + + /** @internal */ + constructor( + pool: ConnectionPool, + reason: 'poolClosed' | 'timeout' | 'connectionError', + error?: MongoError + ) { + super(pool); + this.reason = reason; + this.error = error; + } +} + +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +export class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** @internal */ + name = CONNECTION_CHECKED_OUT; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +export class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** The id of the connection */ + connectionId: number | ''; + /** @internal */ + name = CONNECTION_CHECKED_IN; + + /** @internal */ + constructor(pool: ConnectionPool, connection: Connection) { + super(pool); + this.connectionId = connection.id; + } +} + +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +export class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + serviceId?: ObjectId; + + interruptInUseConnections?: boolean; + /** @internal */ + name = CONNECTION_POOL_CLEARED; + + /** @internal */ + constructor( + pool: ConnectionPool, + options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {} + ) { + super(pool); + this.serviceId = options.serviceId; + this.interruptInUseConnections = options.interruptInUseConnections; + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/errors.ts b/nodejs/node_modules/mongodb/src/cmap/errors.ts new file mode 100644 index 00000000..9d51aa02 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/errors.ts @@ -0,0 +1,119 @@ +import { MongoDriverError, MongoErrorLabel, MongoNetworkError } from '../error'; +import type { ConnectionPool } from './connection_pool'; + +/** + * An error indicating a connection pool is closed + * @category Error + */ +export class PoolClosedError extends MongoDriverError { + /** The address of the connection pool */ + address: string; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(pool: ConnectionPool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + + override get name(): string { + return 'MongoPoolClosedError'; + } +} + +/** + * An error indicating a connection pool is currently paused + * @category Error + */ +export class PoolClearedError extends MongoNetworkError { + /** The address of the connection pool */ + address: string; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(pool: ConnectionPool, message?: string) { + const errorMessage = message + ? message + : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; + super(errorMessage, pool.serverError ? { cause: pool.serverError } : undefined); + this.address = pool.address; + + this.addErrorLabel(MongoErrorLabel.PoolRequstedRetry); + } + + override get name(): string { + return 'MongoPoolClearedError'; + } +} + +/** + * An error indicating that a connection pool has been cleared after the monitor for that server timed out. + * @category Error + */ +export class PoolClearedOnNetworkError extends PoolClearedError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(pool: ConnectionPool) { + super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); + } + + override get name(): string { + return 'PoolClearedOnNetworkError'; + } +} + +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +export class WaitQueueTimeoutError extends MongoDriverError { + /** The address of the connection pool */ + address: string; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, address: string) { + super(message); + this.address = address; + } + + override get name(): string { + return 'MongoWaitQueueTimeoutError'; + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/handshake/client_metadata.ts b/nodejs/node_modules/mongodb/src/cmap/handshake/client_metadata.ts new file mode 100644 index 00000000..c9589f6e --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/handshake/client_metadata.ts @@ -0,0 +1,323 @@ +import { promises as fs } from 'fs'; +import * as os from 'os'; +import * as process from 'process'; + +import { BSON, type Document, Int32 } from '../../bson'; +import { MongoInvalidArgumentError } from '../../error'; +import type { MongoOptions } from '../../mongo_client'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = require('../../../package.json').version; + +/** + * @public + * @see https://github.com/mongodb/specifications/blob/master/source/mongodb-handshake/handshake.rst#hello-command + */ +export interface ClientMetadata { + driver: { + name: string; + version: string; + }; + os: { + type: string; + name?: NodeJS.Platform; + architecture?: string; + version?: string; + }; + platform: string; + application?: { + name: string; + }; + /** FaaS environment information */ + env?: { + name: 'aws.lambda' | 'gcp.func' | 'azure.func' | 'vercel'; + timeout_sec?: Int32; + memory_mb?: Int32; + region?: string; + url?: string; + }; +} + +/** @public */ +export interface ClientMetadataOptions { + driverInfo?: { + name?: string; + version?: string; + platform?: string; + }; + appName?: string; +} + +/** @internal */ +export class LimitedSizeDocument { + private document = new Map(); + /** BSON overhead: Int32 + Null byte */ + private documentSize = 5; + constructor(private maxSize: number) {} + + /** Only adds key/value if the bsonByteLength is less than MAX_SIZE */ + public ifItFitsItSits(key: string, value: Record | string): boolean { + // The BSON byteLength of the new element is the same as serializing it to its own document + // subtracting the document size int32 and the null terminator. + const newElementSize = BSON.serialize(new Map().set(key, value)).byteLength - 5; + + if (newElementSize + this.documentSize > this.maxSize) { + return false; + } + + this.documentSize += newElementSize; + + this.document.set(key, value); + + return true; + } + + toObject(): Document { + return BSON.deserialize(BSON.serialize(this.document), { + promoteLongs: false, + promoteBuffers: false, + promoteValues: false, + useBigInt64: false + }); + } +} + +type MakeClientMetadataOptions = Pick; +/** + * From the specs: + * Implementors SHOULD cumulatively update fields in the following order until the document is under the size limit: + * 1. Omit fields from `env` except `env.name`. + * 2. Omit fields from `os` except `os.type`. + * 3. Omit the `env` document entirely. + * 4. Truncate `platform`. -- special we do not truncate this field + */ +export function makeClientMetadata(options: MakeClientMetadataOptions): ClientMetadata { + const metadataDocument = new LimitedSizeDocument(512); + + const { appName = '' } = options; + // Add app name first, it must be sent + if (appName.length > 0) { + const name = + Buffer.byteLength(appName, 'utf8') <= 128 + ? options.appName + : Buffer.from(appName, 'utf8').subarray(0, 128).toString('utf8'); + metadataDocument.ifItFitsItSits('application', { name }); + } + + const { name = '', version = '', platform = '' } = options.driverInfo; + + const driverInfo = { + name: name.length > 0 ? `nodejs|${name}` : 'nodejs', + version: version.length > 0 ? `${NODE_DRIVER_VERSION}|${version}` : NODE_DRIVER_VERSION + }; + + if (!metadataDocument.ifItFitsItSits('driver', driverInfo)) { + throw new MongoInvalidArgumentError( + 'Unable to include driverInfo name and version, metadata cannot exceed 512 bytes' + ); + } + + let runtimeInfo = getRuntimeInfo(); + if (platform.length > 0) { + runtimeInfo = `${runtimeInfo}|${platform}`; + } + + if (!metadataDocument.ifItFitsItSits('platform', runtimeInfo)) { + throw new MongoInvalidArgumentError( + 'Unable to include driverInfo platform, metadata cannot exceed 512 bytes' + ); + } + + // Note: order matters, os.type is last so it will be removed last if we're at maxSize + const osInfo = new Map() + .set('name', process.platform) + .set('architecture', process.arch) + .set('version', os.release()) + .set('type', os.type()); + + if (!metadataDocument.ifItFitsItSits('os', osInfo)) { + for (const key of osInfo.keys()) { + osInfo.delete(key); + if (osInfo.size === 0) break; + if (metadataDocument.ifItFitsItSits('os', osInfo)) break; + } + } + + const faasEnv = getFAASEnv(); + if (faasEnv != null) { + if (!metadataDocument.ifItFitsItSits('env', faasEnv)) { + for (const key of faasEnv.keys()) { + faasEnv.delete(key); + if (faasEnv.size === 0) break; + if (metadataDocument.ifItFitsItSits('env', faasEnv)) break; + } + } + } + return metadataDocument.toObject() as ClientMetadata; +} + +let dockerPromise: Promise; +/** @internal */ +async function getContainerMetadata() { + const containerMetadata: Record = {}; + dockerPromise ??= fs.access('/.dockerenv').then( + () => true, + () => false + ); + const isDocker = await dockerPromise; + + const { KUBERNETES_SERVICE_HOST = '' } = process.env; + const isKubernetes = KUBERNETES_SERVICE_HOST.length > 0 ? true : false; + + if (isDocker) containerMetadata.runtime = 'docker'; + if (isKubernetes) containerMetadata.orchestrator = 'kubernetes'; + + return containerMetadata; +} + +/** + * @internal + * Re-add each metadata value. + * Attempt to add new env container metadata, but keep old data if it does not fit. + */ +export async function addContainerMetadata(originalMetadata: ClientMetadata) { + const containerMetadata = await getContainerMetadata(); + if (Object.keys(containerMetadata).length === 0) return originalMetadata; + + const extendedMetadata = new LimitedSizeDocument(512); + + const extendedEnvMetadata = { ...originalMetadata?.env, container: containerMetadata }; + + for (const [key, val] of Object.entries(originalMetadata)) { + if (key !== 'env') { + extendedMetadata.ifItFitsItSits(key, val); + } else { + if (!extendedMetadata.ifItFitsItSits('env', extendedEnvMetadata)) { + // add in old data if newer / extended metadata does not fit + extendedMetadata.ifItFitsItSits('env', val); + } + } + } + + if (!('env' in originalMetadata)) { + extendedMetadata.ifItFitsItSits('env', extendedEnvMetadata); + } + + return extendedMetadata.toObject(); +} + +/** + * Collects FaaS metadata. + * - `name` MUST be the last key in the Map returned. + */ +export function getFAASEnv(): Map | null { + const { + AWS_EXECUTION_ENV = '', + AWS_LAMBDA_RUNTIME_API = '', + FUNCTIONS_WORKER_RUNTIME = '', + K_SERVICE = '', + FUNCTION_NAME = '', + VERCEL = '', + AWS_LAMBDA_FUNCTION_MEMORY_SIZE = '', + AWS_REGION = '', + FUNCTION_MEMORY_MB = '', + FUNCTION_REGION = '', + FUNCTION_TIMEOUT_SEC = '', + VERCEL_REGION = '' + } = process.env; + + const isAWSFaaS = + AWS_EXECUTION_ENV.startsWith('AWS_Lambda_') || AWS_LAMBDA_RUNTIME_API.length > 0; + const isAzureFaaS = FUNCTIONS_WORKER_RUNTIME.length > 0; + const isGCPFaaS = K_SERVICE.length > 0 || FUNCTION_NAME.length > 0; + const isVercelFaaS = VERCEL.length > 0; + + // Note: order matters, name must always be the last key + const faasEnv = new Map(); + + // When isVercelFaaS is true so is isAWSFaaS; Vercel inherits the AWS env + if (isVercelFaaS && !(isAzureFaaS || isGCPFaaS)) { + if (VERCEL_REGION.length > 0) { + faasEnv.set('region', VERCEL_REGION); + } + + faasEnv.set('name', 'vercel'); + return faasEnv; + } + + if (isAWSFaaS && !(isAzureFaaS || isGCPFaaS || isVercelFaaS)) { + if (AWS_REGION.length > 0) { + faasEnv.set('region', AWS_REGION); + } + + if ( + AWS_LAMBDA_FUNCTION_MEMORY_SIZE.length > 0 && + Number.isInteger(+AWS_LAMBDA_FUNCTION_MEMORY_SIZE) + ) { + faasEnv.set('memory_mb', new Int32(AWS_LAMBDA_FUNCTION_MEMORY_SIZE)); + } + + faasEnv.set('name', 'aws.lambda'); + return faasEnv; + } + + if (isAzureFaaS && !(isGCPFaaS || isAWSFaaS || isVercelFaaS)) { + faasEnv.set('name', 'azure.func'); + return faasEnv; + } + + if (isGCPFaaS && !(isAzureFaaS || isAWSFaaS || isVercelFaaS)) { + if (FUNCTION_REGION.length > 0) { + faasEnv.set('region', FUNCTION_REGION); + } + + if (FUNCTION_MEMORY_MB.length > 0 && Number.isInteger(+FUNCTION_MEMORY_MB)) { + faasEnv.set('memory_mb', new Int32(FUNCTION_MEMORY_MB)); + } + + if (FUNCTION_TIMEOUT_SEC.length > 0 && Number.isInteger(+FUNCTION_TIMEOUT_SEC)) { + faasEnv.set('timeout_sec', new Int32(FUNCTION_TIMEOUT_SEC)); + } + + faasEnv.set('name', 'gcp.func'); + return faasEnv; + } + + return null; +} + +/** + * @internal + * This type represents the global Deno object and the minimal type contract we expect it to satisfy. + */ +declare const Deno: { version?: { deno?: string } } | undefined; + +/** + * @internal + * This type represents the global Bun object and the minimal type contract we expect it to satisfy. + */ +declare const Bun: { (): void; version?: string } | undefined; + +/** + * @internal + * Get current JavaScript runtime platform + * + * NOTE: The version information fetching is intentionally written defensively + * to avoid having a released driver version that becomes incompatible + * with a future change to these global objects. + */ +function getRuntimeInfo(): string { + if ('Deno' in globalThis) { + const version = typeof Deno?.version?.deno === 'string' ? Deno?.version?.deno : '0.0.0-unknown'; + + return `Deno v${version}, ${os.endianness()}`; + } + + if ('Bun' in globalThis) { + const version = typeof Bun?.version === 'string' ? Bun?.version : '0.0.0-unknown'; + + return `Bun v${version}, ${os.endianness()}`; + } + + return `Node.js ${process.version}, ${os.endianness()}`; +} diff --git a/nodejs/node_modules/mongodb/src/cmap/metrics.ts b/nodejs/node_modules/mongodb/src/cmap/metrics.ts new file mode 100644 index 00000000..b825b539 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/metrics.ts @@ -0,0 +1,58 @@ +/** @internal */ +export class ConnectionPoolMetrics { + static readonly TXN = 'txn' as const; + static readonly CURSOR = 'cursor' as const; + static readonly OTHER = 'other' as const; + + txnConnections = 0; + cursorConnections = 0; + otherConnections = 0; + + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType: string): void { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; + } else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; + } else { + this.otherConnections += 1; + } + } + + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType: string): void { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; + } else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; + } else { + this.otherConnections -= 1; + } + } + + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize: number): string { + return ( + 'Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}` + ); + } + + /** + * Reset the metrics to the initial values. + */ + reset(): void { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/stream_description.ts b/nodejs/node_modules/mongodb/src/cmap/stream_description.ts new file mode 100644 index 00000000..88411c92 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/stream_description.ts @@ -0,0 +1,96 @@ +import { type Document, type Double, Long } from '../bson'; +import { ServerType } from '../sdam/common'; +import { parseServerType } from '../sdam/server_description'; +import type { CompressorName } from './wire_protocol/compression'; + +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +] as const; + +/** @public */ +export interface StreamDescriptionOptions { + compressors?: CompressorName[]; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; +} + +/** @public */ +export class StreamDescription { + address: string; + type: ServerType; + minWireVersion?: number; + maxWireVersion?: number; + maxBsonObjectSize: number; + maxMessageSizeBytes: number; + maxWriteBatchSize: number; + compressors: CompressorName[]; + compressor?: CompressorName; + logicalSessionTimeoutMinutes?: number; + loadBalanced: boolean; + + __nodejs_mock_server__?: boolean; + + zlibCompressionLevel?: number; + serverConnectionId: bigint | null; + + public hello: Document | null = null; + + constructor(address: string, options?: StreamDescriptionOptions) { + this.address = address; + this.type = ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options?.logicalSessionTimeoutMinutes; + this.loadBalanced = !!options?.loadBalanced; + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + this.serverConnectionId = null; + } + + receiveResponse(response: Document | null): void { + if (response == null) { + return; + } + this.hello = response; + this.type = parseServerType(response); + if ('connectionId' in response) { + this.serverConnectionId = this.parseServerConnectionID(response.connectionId); + } else { + this.serverConnectionId = null; + } + for (const field of RESPONSE_FIELDS) { + if (response[field] != null) { + this[field] = response[field]; + } + + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; + } + } + + if (response.compression) { + this.compressor = this.compressors.filter(c => response.compression?.includes(c))[0]; + } + } + + /* @internal */ + parseServerConnectionID(serverConnectionId: number | Double | bigint | Long): bigint { + // Connection ids are always integral, so it's safe to coerce doubles as well as + // any integral type. + return Long.isLong(serverConnectionId) + ? serverConnectionId.toBigInt() + : // @ts-expect-error: Doubles are coercible to number + BigInt(serverConnectionId); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/wire_protocol/compression.ts b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/compression.ts new file mode 100644 index 00000000..6a7d5a6b --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/compression.ts @@ -0,0 +1,198 @@ +import { promisify } from 'util'; +import * as zlib from 'zlib'; + +import { LEGACY_HELLO_COMMAND } from '../../constants'; +import { getSnappy, getZstdLibrary, type SnappyLib, type ZStandard } from '../../deps'; +import { MongoDecompressionError, MongoInvalidArgumentError } from '../../error'; +import { + type MessageHeader, + OpCompressedRequest, + OpMsgResponse, + OpQueryResponse, + type WriteProtocolMessageType +} from '../commands'; +import { OP_COMPRESSED, OP_MSG } from './constants'; + +/** @public */ +export const Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2, + zstd: 3 +} as const); + +/** @public */ +export type Compressor = (typeof Compressor)[CompressorName]; + +/** @public */ +export type CompressorName = keyof typeof Compressor; + +export const uncompressibleCommands = new Set([ + LEGACY_HELLO_COMMAND, + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]); + +const ZSTD_COMPRESSION_LEVEL = 3; + +const zlibInflate = promisify(zlib.inflate.bind(zlib)); +const zlibDeflate = promisify(zlib.deflate.bind(zlib)); + +let zstd: typeof ZStandard; +let Snappy: SnappyLib | null = null; +function loadSnappy() { + if (Snappy == null) { + const snappyImport = getSnappy(); + if ('kModuleError' in snappyImport) { + throw snappyImport.kModuleError; + } + Snappy = snappyImport; + } + return Snappy; +} + +// Facilitate compressing a message using an agreed compressor +export async function compress( + options: { zlibCompressionLevel: number; agreedCompressor: CompressorName }, + dataToBeCompressed: Buffer +): Promise { + const zlibOptions = {} as zlib.ZlibOptions; + switch (options.agreedCompressor) { + case 'snappy': { + Snappy ??= loadSnappy(); + return Snappy.compress(dataToBeCompressed); + } + case 'zstd': { + loadZstd(); + if ('kModuleError' in zstd) { + throw zstd['kModuleError']; + } + return zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); + } + case 'zlib': { + if (options.zlibCompressionLevel) { + zlibOptions.level = options.zlibCompressionLevel; + } + return zlibDeflate(dataToBeCompressed, zlibOptions); + } + default: { + throw new MongoInvalidArgumentError( + `Unknown compressor ${options.agreedCompressor} failed to compress` + ); + } + } +} + +// Decompress a message using the given compressor +export async function decompress(compressorID: number, compressedData: Buffer): Promise { + if ( + compressorID !== Compressor.snappy && + compressorID !== Compressor.zstd && + compressorID !== Compressor.zlib && + compressorID !== Compressor.none + ) { + throw new MongoDecompressionError( + `Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})` + ); + } + + switch (compressorID) { + case Compressor.snappy: { + Snappy ??= loadSnappy(); + return Snappy.uncompress(compressedData, { asBuffer: true }); + } + case Compressor.zstd: { + loadZstd(); + if ('kModuleError' in zstd) { + throw zstd['kModuleError']; + } + return zstd.decompress(compressedData); + } + case Compressor.zlib: { + return zlibInflate(compressedData); + } + default: { + return compressedData; + } + } +} + +/** + * Load ZStandard if it is not already set. + */ +function loadZstd() { + if (!zstd) { + zstd = getZstdLibrary(); + } +} + +const MESSAGE_HEADER_SIZE = 16; + +/** + * @internal + * + * Compresses an OP_MSG or OP_QUERY message, if compression is configured. This method + * also serializes the command to BSON. + */ +export async function compressCommand( + command: WriteProtocolMessageType, + description: { agreedCompressor?: CompressorName; zlibCompressionLevel?: number } +): Promise { + const finalCommand = + description.agreedCompressor === 'none' || !OpCompressedRequest.canCompress(command) + ? command + : new OpCompressedRequest(command, { + agreedCompressor: description.agreedCompressor ?? 'none', + zlibCompressionLevel: description.zlibCompressionLevel ?? 0 + }); + const data = await finalCommand.toBin(); + return Buffer.concat(data); +} + +/** + * @internal + * + * Decompresses an OP_MSG or OP_QUERY response from the server, if compression is configured. + * + * This method does not parse the response's BSON. + */ +export async function decompressResponse( + message: Buffer +): Promise { + const messageHeader: MessageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + + if (messageHeader.opCode !== OP_COMPRESSED) { + const ResponseType = messageHeader.opCode === OP_MSG ? OpMsgResponse : OpQueryResponse; + const messageBody = message.subarray(MESSAGE_HEADER_SIZE); + return new ResponseType(message, messageHeader, messageBody); + } + + const header: MessageHeader = { + ...messageHeader, + fromCompressed: true, + opCode: message.readInt32LE(MESSAGE_HEADER_SIZE), + length: message.readInt32LE(MESSAGE_HEADER_SIZE + 4) + }; + const compressorID = message[MESSAGE_HEADER_SIZE + 8]; + const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); + + // recalculate based on wrapped opcode + const ResponseType = header.opCode === OP_MSG ? OpMsgResponse : OpQueryResponse; + const messageBody = await decompress(compressorID, compressedBuffer); + if (messageBody.length !== header.length) { + throw new MongoDecompressionError('Message body and message header must be the same length'); + } + return new ResponseType(message, header, messageBody); +} diff --git a/nodejs/node_modules/mongodb/src/cmap/wire_protocol/constants.ts b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/constants.ts new file mode 100644 index 00000000..b62cdc90 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/constants.ts @@ -0,0 +1,13 @@ +export const MIN_SUPPORTED_SERVER_VERSION = '3.6'; +export const MAX_SUPPORTED_SERVER_VERSION = '7.0'; +export const MIN_SUPPORTED_WIRE_VERSION = 6; +export const MAX_SUPPORTED_WIRE_VERSION = 21; +export const MIN_SUPPORTED_QE_WIRE_VERSION = 21; +export const MIN_SUPPORTED_QE_SERVER_VERSION = '7.0'; +export const OP_REPLY = 1; +export const OP_UPDATE = 2001; +export const OP_INSERT = 2002; +export const OP_QUERY = 2004; +export const OP_DELETE = 2006; +export const OP_COMPRESSED = 2012; +export const OP_MSG = 2013; diff --git a/nodejs/node_modules/mongodb/src/cmap/wire_protocol/on_data.ts b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/on_data.ts new file mode 100644 index 00000000..b99c950d --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/on_data.ts @@ -0,0 +1,118 @@ +import { type EventEmitter } from 'events'; + +import { List, promiseWithResolvers } from '../../utils'; + +/** + * @internal + * An object holding references to a promise's resolve and reject functions. + */ +type PendingPromises = Omit< + ReturnType>>, + 'promise' +>; + +/** + * onData is adapted from Node.js' events.on helper + * https://nodejs.org/api/events.html#eventsonemitter-eventname-options + * + * Returns an AsyncIterator that iterates each 'data' event emitted from emitter. + * It will reject upon an error event. + */ +export function onData(emitter: EventEmitter) { + // Setup pending events and pending promise lists + /** + * When the caller has not yet called .next(), we store the + * value from the event in this list. Next time they call .next() + * we pull the first value out of this list and resolve a promise with it. + */ + const unconsumedEvents = new List(); + /** + * When there has not yet been an event, a new promise will be created + * and implicitly stored in this list. When an event occurs we take the first + * promise in this list and resolve it. + */ + const unconsumedPromises = new List(); + + /** + * Stored an error created by an error event. + * This error will turn into a rejection for the subsequent .next() call + */ + let error: Error | null = null; + + /** Set to true only after event listeners have been removed. */ + let finished = false; + + const iterator: AsyncGenerator = { + next() { + // First, we consume all unread events + const value = unconsumedEvents.shift(); + if (value != null) { + return Promise.resolve({ value, done: false }); + } + + // Then we error, if an error happened + // This happens one time if at all, because after 'error' + // we stop listening + if (error != null) { + const p = Promise.reject(error); + // Only the first element errors + error = null; + return p; + } + + // If the iterator is finished, resolve to done + if (finished) return closeHandler(); + + // Wait until an event happens + const { promise, resolve, reject } = promiseWithResolvers>(); + unconsumedPromises.push({ resolve, reject }); + return promise; + }, + + return() { + return closeHandler(); + }, + + throw(err: Error) { + errorHandler(err); + return Promise.resolve({ value: undefined, done: true }); + }, + + [Symbol.asyncIterator]() { + return this; + } + }; + + // Adding event handlers + emitter.on('data', eventHandler); + emitter.on('error', errorHandler); + + return iterator; + + function eventHandler(value: Buffer) { + const promise = unconsumedPromises.shift(); + if (promise != null) promise.resolve({ value, done: false }); + else unconsumedEvents.push(value); + } + + function errorHandler(err: Error) { + const promise = unconsumedPromises.shift(); + if (promise != null) promise.reject(err); + else error = err; + void closeHandler(); + } + + function closeHandler() { + // Adding event handlers + emitter.off('data', eventHandler); + emitter.off('error', errorHandler); + finished = true; + const doneResult = { value: undefined, done: finished } as const; + + for (const promise of unconsumedPromises) { + promise.resolve(doneResult); + } + + return Promise.resolve(doneResult); + } +} diff --git a/nodejs/node_modules/mongodb/src/cmap/wire_protocol/shared.ts b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/shared.ts new file mode 100644 index 00000000..98e01490 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cmap/wire_protocol/shared.ts @@ -0,0 +1,49 @@ +import { MongoInvalidArgumentError } from '../../error'; +import type { ReadPreferenceLike } from '../../read_preference'; +import { ReadPreference } from '../../read_preference'; +import { ServerType } from '../../sdam/common'; +import type { Server } from '../../sdam/server'; +import type { ServerDescription } from '../../sdam/server_description'; +import type { Topology } from '../../sdam/topology'; +import { TopologyDescription } from '../../sdam/topology_description'; +import type { Connection } from '../connection'; + +export interface ReadPreferenceOption { + readPreference?: ReadPreferenceLike; +} + +export function getReadPreference(options?: ReadPreferenceOption): ReadPreference { + // Default to command version of the readPreference. + let readPreference = options?.readPreference ?? ReadPreference.primary; + + if (typeof readPreference === 'string') { + readPreference = ReadPreference.fromString(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoInvalidArgumentError( + 'Option "readPreference" must be a ReadPreference instance' + ); + } + + return readPreference; +} + +export function isSharded(topologyOrServer?: Topology | Server | Connection): boolean { + if (topologyOrServer == null) { + return false; + } + + if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { + return true; + } + + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { + const servers: ServerDescription[] = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server: ServerDescription) => server.type === ServerType.Mongos); + } + + return false; +} diff --git a/nodejs/node_modules/mongodb/src/collection.ts b/nodejs/node_modules/mongodb/src/collection.ts new file mode 100644 index 00000000..a735a3a0 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/collection.ts @@ -0,0 +1,1138 @@ +import { type BSONSerializeOptions, type Document, resolveBSONOptions } from './bson'; +import type { AnyBulkWriteOperation, BulkWriteOptions, BulkWriteResult } from './bulk/common'; +import { OrderedBulkOperation } from './bulk/ordered'; +import { UnorderedBulkOperation } from './bulk/unordered'; +import { ChangeStream, type ChangeStreamDocument, type ChangeStreamOptions } from './change_stream'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { FindCursor } from './cursor/find_cursor'; +import { ListIndexesCursor } from './cursor/list_indexes_cursor'; +import { + ListSearchIndexesCursor, + type ListSearchIndexesOptions +} from './cursor/list_search_indexes_cursor'; +import type { Db } from './db'; +import { MongoInvalidArgumentError } from './error'; +import type { MongoClient, PkFactory } from './mongo_client'; +import type { + Filter, + Flatten, + OptionalUnlessRequiredId, + TODO_NODE_3286, + UpdateFilter, + WithId, + WithoutId +} from './mongo_types'; +import type { AggregateOptions } from './operations/aggregate'; +import { BulkWriteOperation } from './operations/bulk_write'; +import type { IndexInformationOptions } from './operations/common_functions'; +import { CountOperation, type CountOptions } from './operations/count'; +import { CountDocumentsOperation, type CountDocumentsOptions } from './operations/count_documents'; +import { + DeleteManyOperation, + DeleteOneOperation, + type DeleteOptions, + type DeleteResult +} from './operations/delete'; +import { DistinctOperation, type DistinctOptions } from './operations/distinct'; +import { DropCollectionOperation, type DropCollectionOptions } from './operations/drop'; +import { + EstimatedDocumentCountOperation, + type EstimatedDocumentCountOptions +} from './operations/estimated_document_count'; +import { executeOperation } from './operations/execute_operation'; +import type { FindOptions } from './operations/find'; +import { + FindOneAndDeleteOperation, + type FindOneAndDeleteOptions, + FindOneAndReplaceOperation, + type FindOneAndReplaceOptions, + FindOneAndUpdateOperation, + type FindOneAndUpdateOptions +} from './operations/find_and_modify'; +import { + CreateIndexesOperation, + type CreateIndexesOptions, + CreateIndexOperation, + type DropIndexesOptions, + DropIndexOperation, + type IndexDescription, + IndexesOperation, + IndexExistsOperation, + IndexInformationOperation, + type IndexSpecification, + type ListIndexesOptions +} from './operations/indexes'; +import { + InsertManyOperation, + type InsertManyResult, + InsertOneOperation, + type InsertOneOptions, + type InsertOneResult +} from './operations/insert'; +import { IsCappedOperation } from './operations/is_capped'; +import type { Hint, OperationOptions } from './operations/operation'; +import { OptionsOperation } from './operations/options_operation'; +import { RenameOperation, type RenameOptions } from './operations/rename'; +import { + CreateSearchIndexesOperation, + type SearchIndexDescription +} from './operations/search_indexes/create'; +import { DropSearchIndexOperation } from './operations/search_indexes/drop'; +import { UpdateSearchIndexOperation } from './operations/search_indexes/update'; +import { + ReplaceOneOperation, + type ReplaceOptions, + UpdateManyOperation, + UpdateOneOperation, + type UpdateOptions, + type UpdateResult +} from './operations/update'; +import { ReadConcern, type ReadConcernLike } from './read_concern'; +import { ReadPreference, type ReadPreferenceLike } from './read_preference'; +import { + DEFAULT_PK_FACTORY, + MongoDBCollectionNamespace, + normalizeHintField, + resolveOptions +} from './utils'; +import { WriteConcern, type WriteConcernOptions } from './write_concern'; + +/** @public */ +export interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions { + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; +} + +/** @internal */ +export interface CollectionPrivate { + pkFactory: PkFactory; + db: Db; + options: any; + namespace: MongoDBCollectionNamespace; + readPreference?: ReadPreference; + bsonOptions: BSONSerializeOptions; + collectionHint?: Hint; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; +} + +/** + * The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +export class Collection { + /** @internal */ + s: CollectionPrivate; + + /** @internal */ + client: MongoClient; + + /** + * Create a new Collection instance + * @internal + */ + constructor(db: Db, name: string, options?: CollectionOptions) { + // Internal state + this.s = { + db, + options, + namespace: new MongoDBCollectionNamespace(db.databaseName, name), + pkFactory: db.options?.pkFactory ?? DEFAULT_PK_FACTORY, + readPreference: ReadPreference.fromOptions(options), + bsonOptions: resolveBSONOptions(options, db), + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options) + }; + + this.client = db.client; + } + + /** + * The name of the database this collection belongs to + */ + get dbName(): string { + return this.s.namespace.db; + } + + /** + * The name of this collection + */ + get collectionName(): string { + return this.s.namespace.collection; + } + + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace(): string { + return this.fullNamespace.toString(); + } + + /** + * @internal + * + * The `MongoDBNamespace` for the collection. + */ + get fullNamespace(): MongoDBCollectionNamespace { + return this.s.namespace; + } + + /** + * The current readConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readConcern(): ReadConcern | undefined { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } + + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference(): ReadPreference | undefined { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern(): WriteConcern | undefined { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } + + /** The current index hint for the collection */ + get hint(): Hint | undefined { + return this.s.collectionHint; + } + + set hint(v: Hint | undefined) { + this.s.collectionHint = normalizeHintField(v); + } + + /** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param doc - The document to insert + * @param options - Optional settings for the command + */ + async insertOne( + doc: OptionalUnlessRequiredId, + options?: InsertOneOptions + ): Promise> { + return executeOperation( + this.client, + new InsertOneOperation( + this as TODO_NODE_3286, + doc, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param docs - The documents to insert + * @param options - Optional settings for the command + */ + async insertMany( + docs: OptionalUnlessRequiredId[], + options?: BulkWriteOptions + ): Promise> { + return executeOperation( + this.client, + new InsertManyOperation( + this as TODO_NODE_3286, + docs, + resolveOptions(this, options ?? { ordered: true }) + ) as TODO_NODE_3286 + ); + } + + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @param operations - Bulk operations to perform + * @param options - Optional settings for the command + * @throws MongoDriverError if operations is not an array + */ + async bulkWrite( + operations: AnyBulkWriteOperation[], + options?: BulkWriteOptions + ): Promise { + if (!Array.isArray(operations)) { + throw new MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + + return executeOperation( + this.client, + new BulkWriteOperation( + this as TODO_NODE_3286, + operations as TODO_NODE_3286, + resolveOptions(this, options ?? { ordered: true }) + ) + ); + } + + /** + * Update a single document in a collection + * + * The value of `update` can be either: + * - UpdateFilter - A document that contains update operator expressions, + * - Document[] - an aggregation pipeline. + * + * @param filter - The filter used to select the document to update + * @param update - The modifications to apply + * @param options - Optional settings for the command + */ + async updateOne( + filter: Filter, + update: UpdateFilter | Document[], + options?: UpdateOptions + ): Promise> { + return executeOperation( + this.client, + new UpdateOneOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Replace a document in a collection with another document + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + */ + async replaceOne( + filter: Filter, + replacement: WithoutId, + options?: ReplaceOptions + ): Promise | Document> { + return executeOperation( + this.client, + new ReplaceOneOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) + ); + } + + /** + * Update multiple documents in a collection + * + * The value of `update` can be either: + * - UpdateFilter - A document that contains update operator expressions, + * - Document[] - an aggregation pipeline. + * + * @param filter - The filter used to select the document to update + * @param update - The modifications to apply + * @param options - Optional settings for the command + */ + async updateMany( + filter: Filter, + update: UpdateFilter | Document[], + options?: UpdateOptions + ): Promise> { + return executeOperation( + this.client, + new UpdateManyOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async deleteOne( + filter: Filter = {}, + options: DeleteOptions = {} + ): Promise { + return executeOperation( + this.client, + new DeleteOneOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + async deleteMany( + filter: Filter = {}, + options: DeleteOptions = {} + ): Promise { + return executeOperation( + this.client, + new DeleteManyOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * Rename the collection. + * + * @remarks + * This operation does not inherit options from the Db or MongoClient. + * + * @param newName - New name of of the collection. + * @param options - Optional settings for the command + */ + async rename(newName: string, options?: RenameOptions): Promise { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.client, + new RenameOperation(this as TODO_NODE_3286, newName, { + ...options, + readPreference: ReadPreference.PRIMARY + }) as TODO_NODE_3286 + ); + } + + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + async drop(options?: DropCollectionOptions): Promise { + return executeOperation( + this.client, + new DropCollectionOperation(this.s.db, this.collectionName, options) + ); + } + + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + */ + async findOne(): Promise | null>; + async findOne(filter: Filter): Promise | null>; + async findOne(filter: Filter, options: FindOptions): Promise | null>; + + // allow an override of the schema. + async findOne(): Promise; + async findOne(filter: Filter): Promise; + async findOne(filter: Filter, options?: FindOptions): Promise; + + async findOne( + filter: Filter = {}, + options: FindOptions = {} + ): Promise | null> { + const cursor = this.find(filter, options).limit(-1).batchSize(1); + const res = await cursor.next(); + await cursor.close(); + return res; + } + + /** + * Creates a cursor for a filter that can be used to iterate over results from MongoDB + * + * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate + */ + find(): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor>; + find(filter: Filter, options?: FindOptions): FindCursor; + find(filter: Filter = {}, options: FindOptions = {}): FindCursor> { + return new FindCursor>( + this.client, + this.s.namespace, + filter, + resolveOptions(this as TODO_NODE_3286, options) + ); + } + + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + */ + async options(options?: OperationOptions): Promise { + return executeOperation( + this.client, + new OptionsOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + async isCapped(options?: OperationOptions): Promise { + return executeOperation( + this.client, + new IsCappedOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Creates an index on the db and collection collection. + * + * @param indexSpec - The field name or index specification to create an index for + * @param options - Optional settings for the command + * + * @example + * ```ts + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + * ``` + */ + async createIndex( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.client, + new CreateIndexOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpec, + resolveOptions(this, options) + ) + ); + } + + /** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}. + * + * @param indexSpecs - An array of index specifications to be created + * @param options - Optional settings for the command + * + * @example + * ```ts + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + * ``` + */ + async createIndexes( + indexSpecs: IndexDescription[], + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.client, + new CreateIndexesOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpecs, + resolveOptions(this, { ...options, maxTimeMS: undefined }) + ) + ); + } + + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + async dropIndex(indexName: string, options?: DropIndexesOptions): Promise { + return executeOperation( + this.client, + new DropIndexOperation(this as TODO_NODE_3286, indexName, { + ...resolveOptions(this, options), + readPreference: ReadPreference.primary + }) + ); + } + + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + async dropIndexes(options?: DropIndexesOptions): Promise { + try { + await executeOperation( + this.client, + new DropIndexOperation(this as TODO_NODE_3286, '*', resolveOptions(this, options)) + ); + return true; + } catch { + return false; + } + } + + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options?: ListIndexesOptions): ListIndexesCursor { + return new ListIndexesCursor(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * + * @param indexes - One or more index names to check. + * @param options - Optional settings for the command + */ + async indexExists( + indexes: string | string[], + options?: IndexInformationOptions + ): Promise { + return executeOperation( + this.client, + new IndexExistsOperation(this as TODO_NODE_3286, indexes, resolveOptions(this, options)) + ); + } + + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + async indexInformation(options?: IndexInformationOptions): Promise { + return executeOperation( + this.client, + new IndexInformationOperation(this.s.db, this.collectionName, resolveOptions(this, options)) + ); + } + + /** + * Gets an estimate of the count of documents in a collection using collection metadata. + * This will always run a count command on all server versions. + * + * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, + * which estimatedDocumentCount uses in its implementation, was not included in v1 of + * the Stable API, and so users of the Stable API with estimatedDocumentCount are + * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid + * encountering errors. + * + * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior} + * @param options - Optional settings for the command + */ + async estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise { + return executeOperation( + this.client, + new EstimatedDocumentCountOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/ + * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ + * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center + * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param filter - The filter for the count + * @param options - Optional settings for the command + * + * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/ + * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ + * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center + * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + async countDocuments( + filter: Filter = {}, + options: CountDocumentsOptions = {} + ): Promise { + return executeOperation( + this.client, + new CountDocumentsOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * The distinct command returns a list of distinct values for the given key across a collection. + * + * @param key - Field of the document to find distinct values for + * @param filter - The filter for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings for the command + */ + distinct>( + key: Key + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions + ): Promise[Key]>>>; + + // Embedded documents overload + distinct(key: string): Promise; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + + async distinct>( + key: Key, + filter: Filter = {}, + options: DistinctOptions = {} + ): Promise { + return executeOperation( + this.client, + new DistinctOperation( + this as TODO_NODE_3286, + key as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) + ); + } + + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + async indexes(options?: IndexInformationOptions): Promise { + return executeOperation( + this.client, + new IndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions & { includeResultMetadata: true } + ): Promise>; + async findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions & { includeResultMetadata: false } + ): Promise | null>; + async findOneAndDelete( + filter: Filter, + options: FindOneAndDeleteOptions + ): Promise | null>; + async findOneAndDelete(filter: Filter): Promise | null>; + async findOneAndDelete( + filter: Filter, + options?: FindOneAndDeleteOptions + ): Promise | ModifyResult | null> { + return executeOperation( + this.client, + new FindOneAndDeleteOperation( + this as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to replace + * @param replacement - The Document that replaces the matching document + * @param options - Optional settings for the command + */ + async findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options: FindOneAndReplaceOptions & { includeResultMetadata: true } + ): Promise>; + async findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options: FindOneAndReplaceOptions & { includeResultMetadata: false } + ): Promise | null>; + async findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options: FindOneAndReplaceOptions + ): Promise | null>; + async findOneAndReplace( + filter: Filter, + replacement: WithoutId + ): Promise | null>; + async findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options?: FindOneAndReplaceOptions + ): Promise | ModifyResult | null> { + return executeOperation( + this.client, + new FindOneAndReplaceOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @param filter - The filter used to select the document to update + * @param update - Update operations to be performed on the document + * @param options - Optional settings for the command + */ + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions & { includeResultMetadata: true } + ): Promise>; + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions & { includeResultMetadata: false } + ): Promise | null>; + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options: FindOneAndUpdateOptions + ): Promise | null>; + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter + ): Promise | null>; + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options?: FindOneAndUpdateOptions + ): Promise | ModifyResult | null> { + return executeOperation( + this.client, + new FindOneAndUpdateOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate( + pipeline: Document[] = [], + options?: AggregateOptions + ): AggregationCursor { + if (!Array.isArray(pipeline)) { + throw new MongoInvalidArgumentError( + 'Argument "pipeline" must be an array of aggregation stages' + ); + } + + return new AggregationCursor( + this.client, + this.s.namespace, + pipeline, + resolveOptions(this, options) + ); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to override the schema that may be defined for this specific collection + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * @example + * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>` + * ```ts + * collection.watch<{ _id: number }>() + * .on('change', change => console.log(change._id.toFixed(4))); + * ``` + * + * @example + * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. + * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. + * No need start from scratch on the ChangeStreamInsertDocument type! + * By using an intersection we can save time and ensure defaults remain the same type! + * ```ts + * collection + * .watch & { comment: string }>([ + * { $addFields: { comment: 'big changes' } }, + * { $match: { operationType: 'insert' } } + * ]) + * .on('change', change => { + * change.comment.startsWith('big'); + * change.operationType === 'insert'; + * // No need to narrow in code because the generics did that for us! + * expectType(change.fullDocument); + * }); + * ``` + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TLocal - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch>( + pipeline: Document[] = [], + options: ChangeStreamOptions = {} + ): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation { + return new UnorderedBulkOperation(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @throws MongoNotConnectedError + * @remarks + * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation { + return new OrderedBulkOperation(this as TODO_NODE_3286, resolveOptions(this, options)); + } + + /** + * An estimated count of matching documents in the db to a filter. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. + * + * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead + * + * @param filter - The filter for the count. + * @param options - Optional settings for the command + */ + async count(filter: Filter = {}, options: CountOptions = {}): Promise { + return executeOperation( + this.client, + new CountOperation(this.fullNamespace, filter, resolveOptions(this, options)) + ); + } + + /** + * Returns all search indexes for the current collection. + * + * @param options - The options for the list indexes operation. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + listSearchIndexes(options?: ListSearchIndexesOptions): ListSearchIndexesCursor; + /** + * Returns all search indexes for the current collection. + * + * @param name - The name of the index to search for. Only indexes with matching index names will be returned. + * @param options - The options for the list indexes operation. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + listSearchIndexes(name: string, options?: ListSearchIndexesOptions): ListSearchIndexesCursor; + listSearchIndexes( + indexNameOrOptions?: string | ListSearchIndexesOptions, + options?: ListSearchIndexesOptions + ): ListSearchIndexesCursor { + options = + typeof indexNameOrOptions === 'object' ? indexNameOrOptions : options == null ? {} : options; + const indexName = + indexNameOrOptions == null + ? null + : typeof indexNameOrOptions === 'object' + ? null + : indexNameOrOptions; + + return new ListSearchIndexesCursor(this as TODO_NODE_3286, indexName, options); + } + + /** + * Creates a single search index for the collection. + * + * @param description - The index description for the new search index. + * @returns A promise that resolves to the name of the new search index. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + async createSearchIndex(description: SearchIndexDescription): Promise { + const [index] = await this.createSearchIndexes([description]); + return index; + } + + /** + * Creates multiple search indexes for the current collection. + * + * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes. + * @returns A promise that resolves to an array of the newly created search index names. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + * @returns + */ + async createSearchIndexes(descriptions: SearchIndexDescription[]): Promise { + return executeOperation( + this.client, + new CreateSearchIndexesOperation(this as TODO_NODE_3286, descriptions) + ); + } + + /** + * Deletes a search index by index name. + * + * @param name - The name of the search index to be deleted. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + async dropSearchIndex(name: string): Promise { + return executeOperation( + this.client, + new DropSearchIndexOperation(this as TODO_NODE_3286, name) + ); + } + + /** + * Updates a search index by replacing the existing index definition with the provided definition. + * + * @param name - The name of the search index to update. + * @param definition - The new search index definition. + * + * @remarks Only available when used against a 7.0+ Atlas cluster. + */ + async updateSearchIndex(name: string, definition: Document): Promise { + return executeOperation( + this.client, + new UpdateSearchIndexOperation(this as TODO_NODE_3286, name, definition) + ); + } +} diff --git a/nodejs/node_modules/mongodb/src/connection_string.ts b/nodejs/node_modules/mongodb/src/connection_string.ts new file mode 100644 index 00000000..152a4be6 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/connection_string.ts @@ -0,0 +1,1330 @@ +import * as dns from 'dns'; +import ConnectionString from 'mongodb-connection-string-url'; +import { URLSearchParams } from 'url'; + +import type { Document } from './bson'; +import { MongoCredentials } from './cmap/auth/mongo_credentials'; +import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from './cmap/auth/providers'; +import { addContainerMetadata, makeClientMetadata } from './cmap/handshake/client_metadata'; +import { Compressor, type CompressorName } from './cmap/wire_protocol/compression'; +import { Encrypter } from './encrypter'; +import { + MongoAPIError, + MongoInvalidArgumentError, + MongoMissingCredentialsError, + MongoParseError +} from './error'; +import { + MongoClient, + type MongoClientOptions, + type MongoOptions, + type PkFactory, + type ServerApi, + ServerApiVersion +} from './mongo_client'; +import { + MongoLoggableComponent, + MongoLogger, + type MongoLoggerEnvOptions, + type MongoLoggerMongoClientOptions, + SeverityLevel +} from './mongo_logger'; +import { ReadConcern, type ReadConcernLevel } from './read_concern'; +import { ReadPreference, type ReadPreferenceMode } from './read_preference'; +import { ServerMonitoringMode } from './sdam/monitor'; +import type { TagSet } from './sdam/server_description'; +import { + DEFAULT_PK_FACTORY, + emitWarning, + HostAddress, + isRecord, + matchesParentDomain, + parseInteger, + setDifference +} from './utils'; +import { type W, WriteConcern } from './write_concern'; + +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; + +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = + 'loadBalanced option not supported when directConnection is provided'; + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +export async function resolveSRVRecord(options: MongoOptions): Promise { + if (typeof options.srvHost !== 'string') { + throw new MongoAPIError('Option "srvHost" must not be empty'); + } + + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + throw new MongoAPIError('URI must include hostname, domain name, and tld'); + } + + // Asynchronously start TXT resolution so that we do not have to wait until + // the SRV record is resolved before starting a second DNS query. + const lookupAddress = options.srvHost; + const txtResolutionPromise = dns.promises.resolveTxt(lookupAddress); + txtResolutionPromise.catch(() => { + /* rejections will be handled later */ + }); + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const addresses = await dns.promises.resolveSrv( + `_${options.srvServiceName}._tcp.${lookupAddress}` + ); + + if (addresses.length === 0) { + throw new MongoAPIError('No addresses found at host'); + } + + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + throw new MongoAPIError('Server record does not share hostname with parent URI'); + } + } + + const hostAddresses = addresses.map(r => HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); + + validateLoadBalancedOptions(hostAddresses, options, true); + + // Use the result of resolving the TXT record and add options from there if they exist. + let record; + try { + record = await txtResolutionPromise; + } catch (error) { + if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { + throw error; + } + return hostAddresses; + } + + if (record.length > 1) { + throw new MongoParseError('Multiple text records not allowed'); + } + + const txtRecordOptions = new URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + throw new MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); + } + + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + throw new MongoParseError('Cannot have empty URI params in DNS TXT Record'); + } + + const source = txtRecordOptions.get('authSource') ?? undefined; + const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined; + const loadBalanced = txtRecordOptions.get('loadBalanced') ?? undefined; + + if ( + !options.userSpecifiedAuthSource && + source && + options.credentials && + !AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism) + ) { + options.credentials = MongoCredentials.merge(options.credentials, { source }); + } + + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + + if (options.replicaSet && options.srvMaxHosts > 0) { + throw new MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); + } + + validateLoadBalancedOptions(hostAddresses, options, true); + + return hostAddresses; +} + +/** + * Checks if TLS options are valid + * + * @param allOptions - All options provided by user or included in default options map + * @throws MongoAPIError if TLS options are invalid + */ +function checkTLSOptions(allOptions: CaseInsensitiveMap): void { + if (!allOptions) return; + const check = (a: string, b: string) => { + if (allOptions.has(a) && allOptions.has(b)) { + throw new MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} +function getBoolean(name: string, value: unknown): boolean { + if (typeof value === 'boolean') return value; + switch (value) { + case 'true': + return true; + case 'false': + return false; + default: + throw new MongoParseError(`${name} must be either "true" or "false"`); + } +} + +function getIntFromOptions(name: string, value: unknown): number { + const parsedInt = parseInteger(value); + if (parsedInt != null) { + return parsedInt; + } + throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} + +function getUIntFromOptions(name: string, value: unknown): number { + const parsedValue = getIntFromOptions(name, value); + if (parsedValue < 0) { + throw new MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} + +function* entriesFromString(value: string): Generator<[string, string]> { + if (value === '') { + return; + } + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(/:(.*)/); + if (value == null) { + throw new MongoParseError('Cannot have undefined values in key value pairs'); + } + + yield [key, value]; + } +} + +class CaseInsensitiveMap extends Map { + constructor(entries: Array<[string, any]> = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + override has(k: string) { + return super.has(k.toLowerCase()); + } + override get(k: string) { + return super.get(k.toLowerCase()); + } + override set(k: string, v: any) { + return super.set(k.toLowerCase(), v); + } + override delete(k: string): boolean { + return super.delete(k.toLowerCase()); + } +} + +export function parseOptions( + uri: string, + mongoClient: MongoClient | MongoClientOptions | undefined = undefined, + options: MongoClientOptions = {} +): MongoOptions { + if (mongoClient != null && !(mongoClient instanceof MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + + // validate BSONOptions + if (options.useBigInt64 && typeof options.promoteLongs === 'boolean' && !options.promoteLongs) { + throw new MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + + if (options.useBigInt64 && typeof options.promoteValues === 'boolean' && !options.promoteValues) { + throw new MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + + const url = new ConnectionString(uri); + const { hosts, isSRV } = url; + + const mongoOptions = Object.create(null); + + // Feature flags + for (const flag of Object.getOwnPropertySymbols(options)) { + if (FEATURE_FLAGS.has(flag)) { + mongoOptions[flag] = options[flag]; + } + } + + mongoOptions.hosts = isSRV ? [] : hosts.map(HostAddress.fromString); + + const urlOptions = new CaseInsensitiveMap(); + + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent( + url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname + ); + if (dbName) { + urlOptions.set('dbName', [dbName]); + } + } + + if (url.username !== '') { + const auth: Document = { + username: decodeURIComponent(url.username) + }; + + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); + } + + urlOptions.set('auth', [auth]); + } + + for (const key of url.searchParams.keys()) { + const values = url.searchParams.getAll(key); + + const isReadPreferenceTags = /readPreferenceTags/i.test(key); + + if (!isReadPreferenceTags && values.length > 1) { + throw new MongoInvalidArgumentError( + `URI option "${key}" cannot appear more than once in the connection string` + ); + } + + if (!isReadPreferenceTags && values.includes('')) { + throw new MongoAPIError(`URI option "${key}" cannot be specified with no value`); + } + + if (!urlOptions.has(key)) { + urlOptions.set(key, values); + } + } + + const objectOptions = new CaseInsensitiveMap( + Object.entries(options).filter(([, v]) => v != null) + ); + + // Validate options that can only be provided by one of uri or object + + if (urlOptions.has('serverApi')) { + throw new MongoParseError( + 'URI cannot contain `serverApi`, it can only be passed to the client' + ); + } + + const uriMechanismProperties = urlOptions.get('authMechanismProperties'); + if (uriMechanismProperties) { + for (const property of uriMechanismProperties) { + if (/(^|,)ALLOWED_HOSTS:/.test(property as string)) { + throw new MongoParseError( + 'Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.' + ); + } + } + } + + if (objectOptions.has('loadBalanced')) { + throw new MongoParseError('loadBalanced is only a valid option in the URI'); + } + + // All option collection + + const allProvidedOptions = new CaseInsensitiveMap(); + + const allProvidedKeys = new Set([...urlOptions.keys(), ...objectOptions.keys()]); + + for (const key of allProvidedKeys) { + const values = []; + const objectOptionValue = objectOptions.get(key); + if (objectOptionValue != null) { + values.push(objectOptionValue); + } + + const urlValues = urlOptions.get(key) ?? []; + values.push(...urlValues); + allProvidedOptions.set(key, values); + } + + if (allProvidedOptions.has('tls') || allProvidedOptions.has('ssl')) { + const tlsAndSslOpts = (allProvidedOptions.get('tls') || []) + .concat(allProvidedOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new MongoParseError('All values of tls/ssl must be the same.'); + } + } + + checkTLSOptions(allProvidedOptions); + + const unsupportedOptions = setDifference( + allProvidedKeys, + Array.from(Object.keys(OPTIONS)).map(s => s.toLowerCase()) + ); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new MongoParseError( + `${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported` + ); + } + + // Option parsing and setting + + for (const [key, descriptor] of Object.entries(OPTIONS)) { + const values = allProvidedOptions.get(key); + if (!values || values.length === 0) { + if (DEFAULT_OPTIONS.has(key)) { + setOption(mongoOptions, key, descriptor, [DEFAULT_OPTIONS.get(key)]); + } + } else { + const { deprecated } = descriptor; + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + emitWarning(`${key} is a deprecated option${deprecatedMsg}`); + } + + setOption(mongoOptions, key, descriptor, values); + } + } + + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_AWS; + const isOidc = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_OIDC; + if ( + (isGssapi || isX509) && + allProvidedOptions.has('authSource') && + mongoOptions.credentials.source !== '$external' + ) { + // If authSource was explicitly given and its incorrect, we error + throw new MongoParseError( + `authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'` + ); + } + + if ( + !(isGssapi || isX509 || isAws || isOidc) && + mongoOptions.dbName && + !allProvidedOptions.has('authSource') + ) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName + }); + } + + if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { + throw new MongoMissingCredentialsError( + `When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified` + ); + } + + mongoOptions.credentials.validate(); + + // Check if the only auth related option provided was authSource, if so we can remove credentials + if ( + mongoOptions.credentials.password === '' && + mongoOptions.credentials.username === '' && + mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_DEFAULT && + Object.keys(mongoOptions.credentials.mechanismProperties).length === 0 + ) { + delete mongoOptions.credentials; + } + } + + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + + validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + + if (mongoClient && mongoOptions.autoEncryption) { + Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + + // Potential SRV Overrides and SRV connection string validations + + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + + if (mongoOptions.directConnection) { + throw new MongoAPIError('SRV URI does not support directConnection'); + } + + if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') { + throw new MongoParseError('Cannot use srvMaxHosts option with replicaSet'); + } + + // SRV turns on TLS by default, but users can override and turn it off + const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls'); + const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl'); + if (noUserSpecifiedTLS && noUserSpecifiedSSL) { + mongoOptions.tls = true; + } + } else { + const userSpecifiedSrvOptions = + urlOptions.has('srvMaxHosts') || + objectOptions.has('srvMaxHosts') || + urlOptions.has('srvServiceName') || + objectOptions.has('srvServiceName'); + + if (userSpecifiedSrvOptions) { + throw new MongoParseError( + 'Cannot use srvMaxHosts or srvServiceName with a non-srv connection string' + ); + } + } + + if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) { + throw new MongoParseError('directConnection option requires exactly one host'); + } + + if ( + !mongoOptions.proxyHost && + (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword) + ) { + throw new MongoParseError('Must specify proxyHost if other proxy options are passed'); + } + + if ( + (mongoOptions.proxyUsername && !mongoOptions.proxyPassword) || + (!mongoOptions.proxyUsername && mongoOptions.proxyPassword) + ) { + throw new MongoParseError('Can only specify both of proxy username/password or neither'); + } + + const proxyOptions = ['proxyHost', 'proxyPort', 'proxyUsername', 'proxyPassword'].map( + key => urlOptions.get(key) ?? [] + ); + + if (proxyOptions.some(options => options.length > 1)) { + throw new MongoParseError( + 'Proxy options cannot be specified multiple times in the connection string' + ); + } + + const loggerFeatureFlag = Symbol.for('@@mdb.enableMongoLogger'); + mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false; + + let loggerEnvOptions: MongoLoggerEnvOptions = {}; + let loggerClientOptions: MongoLoggerMongoClientOptions = {}; + if (mongoOptions[loggerFeatureFlag]) { + loggerEnvOptions = { + MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, + MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, + MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, + MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, + MONGODB_LOG_CLIENT: process.env.MONGODB_LOG_CLIENT, + MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, + MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, + MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH, + ...mongoOptions[Symbol.for('@@mdb.internalLoggerConfig')] + }; + loggerClientOptions = { + mongodbLogPath: mongoOptions.mongodbLogPath, + mongodbLogComponentSeverities: mongoOptions.mongodbLogComponentSeverities, + mongodbLogMaxDocumentLength: mongoOptions.mongodbLogMaxDocumentLength + }; + } + mongoOptions.mongoLoggerOptions = MongoLogger.resolveOptions( + loggerEnvOptions, + loggerClientOptions + ); + + mongoOptions.metadata = makeClientMetadata(mongoOptions); + + mongoOptions.extendedMetadata = addContainerMetadata(mongoOptions.metadata).catch(() => { + /* rejections will be handled later */ + }); + + return mongoOptions; +} + +/** + * #### Throws if LB mode is true: + * - hosts contains more than one host + * - there is a replicaSet name set + * - directConnection is set + * - if srvMaxHosts is used when an srv connection string is passed in + * + * @throws MongoParseError + */ +function validateLoadBalancedOptions( + hosts: HostAddress[] | string[], + mongoOptions: MongoOptions, + isSrv: boolean +): void { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + throw new MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + throw new MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + throw new MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + + if (isSrv && mongoOptions.srvMaxHosts > 0) { + throw new MongoParseError('Cannot limit srv hosts with loadBalanced enabled'); + } + } + return; +} + +function setOption( + mongoOptions: any, + key: string, + descriptor: OptionDescriptor, + values: unknown[] +) { + const { target, type, transform } = descriptor; + const name = target ?? key; + + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getIntFromOptions(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUIntFromOptions(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!isRecord(values[0])) { + throw new MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; + } + } +} + +interface OptionDescriptor { + target?: string; + type?: 'boolean' | 'int' | 'uint' | 'record' | 'string' | 'any'; + default?: any; + + deprecated?: boolean | string; + /** + * @param name - the original option name + * @param options - the options so far for resolution + * @param values - the possible values in precedence order + */ + transform?: (args: { name: string; options: MongoOptions; values: unknown[] }) => unknown; +} + +export const OPTIONS = { + appName: { + type: 'string' + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }): MongoCredentials { + if (!isRecord(value, ['username', 'password'] as const)) { + throw new MongoParseError( + `${name} must be an object with 'username' and 'password' properties` + ); + } + return MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password + }); + } + }, + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + const mechanisms = Object.values(AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw`\b${value}\b`, 'i'))); + if (!mechanism) { + throw new MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = options.credentials?.source; + if ( + mechanism === AuthMechanism.MONGODB_PLAIN || + AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism) + ) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + + let password = options.credentials?.password; + if (mechanism === AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); + } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values }): MongoCredentials { + // We can have a combination of options passed in the URI and options passed + // as an object to the MongoClient. So we must transform the string options + // as well as merge them together with a potentially provided object. + let mechanismProperties = Object.create(null); + + for (const optionValue of values) { + if (typeof optionValue === 'string') { + for (const [key, value] of entriesFromString(optionValue)) { + try { + mechanismProperties[key] = getBoolean(key, value); + } catch { + mechanismProperties[key] = value; + } + } + } else { + if (!isRecord(optionValue)) { + throw new MongoParseError('AuthMechanismProperties must be an object'); + } + mechanismProperties = { ...optionValue }; + } + } + return MongoCredentials.merge(options.credentials, { + mechanismProperties + }); + } + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }): MongoCredentials { + const source = String(value); + return MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }): ServerApi { + const serverApiToValidate = + typeof version === 'string' ? ({ version } as ServerApi) : (version as ServerApi); + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new MongoParseError( + `Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values( + ServerApiVersion + ).join('", "')}"]` + ); + } + if (!Object.values(ServerApiVersion).some(v => v === versionToValidate)) { + throw new MongoParseError( + `Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values( + ServerApiVersion + ).join('", "')}"]` + ); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values as (CompressorName[] | string)[]) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new MongoInvalidArgumentError( + 'compressors must be an array or a comma-delimited list of strings' + ); + } + for (const c of compValArray) { + if (Object.keys(Compressor).includes(String(c))) { + compressionList.add(String(c)); + } else { + throw new MongoInvalidArgumentError( + `${c} is not a valid compression mechanism. Must be one of: ${Object.keys( + Compressor + )}.` + ); + } + } + } + return [...compressionList]; + } + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + default: {}, + type: 'record' + }, + enableUtf8Validation: { type: 'boolean', default: true }, + family: { + transform({ name, values: [value] }): 4 | 6 { + const transformValue = getIntFromOptions(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; + } + throw new MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; + } + } as OptionDescriptor, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + } as OptionDescriptor, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }): WriteConcern { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) + } + }); + if (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }): number { + const maxConnecting = getUIntFromOptions(name, value); + if (maxConnecting === 0) { + throw new MongoInvalidArgumentError('maxConnecting must be > 0 if specified'); + } + return maxConnecting; + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUIntFromOptions(name, value); + if (options.readPreference) { + return ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } + }); + } else { + return new ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + } as OptionDescriptor, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: DEFAULT_PK_FACTORY, + transform({ values: [value] }): PkFactory { + if (isRecord(value, ['createPk'] as const) && typeof value.createPk === 'function') { + return value as PkFactory; + } + throw new MongoParseError( + `Option pkFactory must be an object with a createPk function, got ${value}` + ); + } + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + useBigInt64: { + type: 'boolean' + }, + proxyHost: { + type: 'string' + }, + proxyPassword: { + type: 'string' + }, + proxyPort: { + type: 'uint' + }, + proxyUsername: { + type: 'string' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof ReadConcern || isRecord(value, ['level'] as const)) { + return ReadConcern.fromOptions({ ...options.readConcern, ...value } as any); + } + throw new MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return ReadConcern.fromOptions({ + ...options.readConcern, + level: level as ReadConcernLevel + }); + } + }, + readPreference: { + default: ReadPreference.primary, + transform({ values: [value], options }) { + if (value instanceof ReadPreference) { + return ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + } as any); + } + if (isRecord(value, ['mode'] as const)) { + const rp = ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + } as any); + if (rp) return rp; + else throw new MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: options.readPreference?.hedge, + maxStalenessSeconds: options.readPreference?.maxStalenessSeconds + }; + return new ReadPreference( + value as ReadPreferenceMode, + options.readPreference?.tags, + rpOpts + ); + } + throw new MongoParseError(`Unknown ReadPreference value: ${value}`); + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ + values, + options + }: { + values: Array[]>; + options: MongoClientOptions; + }) { + const tags: Array> = Array.isArray(values[0]) + ? values[0] + : (values as Array); + const readPreferenceTags = []; + for (const tag of tags) { + const readPreferenceTag: TagSet = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of entriesFromString(tag)) { + readPreferenceTag[k] = v; + } + } + if (isRecord(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } + } + readPreferenceTags.push(readPreferenceTag); + } + return ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); + } + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverMonitoringMode: { + default: 'auto', + transform({ values: [value] }) { + if (!Object.values(ServerMonitoringMode).includes(value as any)) { + throw new MongoParseError( + 'serverMonitoringMode must be one of `auto`, `poll`, or `stream`' + ); + } + return value; + } + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + srvMaxHosts: { + type: 'uint', + default: 0 + }, + srvServiceName: { + type: 'string', + default: 'mongodb' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + timeoutMS: { + type: 'uint' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + type: 'string' + }, + tlsCRLFile: { + type: 'string' + }, + tlsCertificateKeyFile: { + type: 'string' + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; + } + return tlsInsecure; + } + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value as W } }); + } + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if (isRecord(value) || value instanceof WriteConcern) { + return WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } + }); + } else if (value === 'majority' || typeof value === 'number') { + return WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); + } + + throw new MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUIntFromOptions('wtimeout', value) + } + }); + if (wc) return wc; + throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + } as OptionDescriptor, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUIntFromOptions('wtimeoutMS', value) + } + }); + if (wc) return wc; + throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy options from v3 era + useNewUrlParser: { + type: 'boolean', + deprecated: + 'useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version' + } as OptionDescriptor, + useUnifiedTopology: { + type: 'boolean', + deprecated: + 'useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version' + } as OptionDescriptor, + // MongoLogger + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogPath: { + transform({ values: [value] }) { + if ( + !( + (typeof value === 'string' && ['stderr', 'stdout'].includes(value)) || + (value && + typeof value === 'object' && + 'write' in value && + typeof value.write === 'function') + ) + ) { + throw new MongoAPIError( + `Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable` + ); + } + return value; + } + }, + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogComponentSeverities: { + transform({ values: [value] }) { + if (typeof value !== 'object' || !value) { + throw new MongoAPIError(`Option 'mongodbLogComponentSeverities' must be a non-null object`); + } + for (const [k, v] of Object.entries(value)) { + if (typeof v !== 'string' || typeof k !== 'string') { + throw new MongoAPIError( + `User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value` + ); + } + if (!Object.values(MongoLoggableComponent).some(val => val === k) && k !== 'default') { + throw new MongoAPIError( + `User input for option 'mongodbLogComponentSeverities' contains invalid key: ${k}` + ); + } + if (!Object.values(SeverityLevel).some(val => val === v)) { + throw new MongoAPIError( + `Option 'mongodbLogComponentSeverities' does not support ${v} as a value for ${k}` + ); + } + } + return value; + } + }, + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogMaxDocumentLength: { type: 'uint' } +} as Record; + +export const DEFAULT_OPTIONS = new CaseInsensitiveMap( + Object.entries(OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default]) +); + +/** + * Set of permitted feature flags + * @internal + */ +export const FEATURE_FLAGS = new Set([ + Symbol.for('@@mdb.skipPingOnConnect'), + Symbol.for('@@mdb.enableMongoLogger'), + Symbol.for('@@mdb.internalLoggerConfig') +]); diff --git a/nodejs/node_modules/mongodb/src/constants.ts b/nodejs/node_modules/mongodb/src/constants.ts new file mode 100644 index 00000000..293749ca --- /dev/null +++ b/nodejs/node_modules/mongodb/src/constants.ts @@ -0,0 +1,167 @@ +export const SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +export const SYSTEM_INDEX_COLLECTION = 'system.indexes'; +export const SYSTEM_PROFILE_COLLECTION = 'system.profile'; +export const SYSTEM_USER_COLLECTION = 'system.users'; +export const SYSTEM_COMMAND_COLLECTION = '$cmd'; +export const SYSTEM_JS_COLLECTION = 'system.js'; + +// events +export const ERROR = 'error' as const; +export const TIMEOUT = 'timeout' as const; +export const CLOSE = 'close' as const; +export const OPEN = 'open' as const; +export const CONNECT = 'connect' as const; +export const CLOSED = 'closed' as const; +export const ENDED = 'ended' as const; +export const MESSAGE = 'message' as const; +export const PINNED = 'pinned' as const; +export const UNPINNED = 'unpinned' as const; +export const DESCRIPTION_RECEIVED = 'descriptionReceived'; +/** @internal */ +export const SERVER_OPENING = 'serverOpening' as const; +/** @internal */ +export const SERVER_CLOSED = 'serverClosed' as const; +/** @internal */ +export const SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged' as const; +/** @internal */ +export const TOPOLOGY_OPENING = 'topologyOpening' as const; +/** @internal */ +export const TOPOLOGY_CLOSED = 'topologyClosed' as const; +/** @internal */ +export const TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged' as const; +/** @internal */ +export const SERVER_SELECTION_STARTED = 'serverSelectionStarted' as const; +/** @internal */ +export const SERVER_SELECTION_FAILED = 'serverSelectionFailed' as const; +/** @internal */ +export const SERVER_SELECTION_SUCCEEDED = 'serverSelectionSucceeded' as const; +/** @internal */ +export const WAITING_FOR_SUITABLE_SERVER = 'waitingForSuitableServer' as const; +/** @internal */ +export const CONNECTION_POOL_CREATED = 'connectionPoolCreated' as const; +/** @internal */ +export const CONNECTION_POOL_CLOSED = 'connectionPoolClosed' as const; +/** @internal */ +export const CONNECTION_POOL_CLEARED = 'connectionPoolCleared' as const; +/** @internal */ +export const CONNECTION_POOL_READY = 'connectionPoolReady' as const; +/** @internal */ +export const CONNECTION_CREATED = 'connectionCreated' as const; +/** @internal */ +export const CONNECTION_READY = 'connectionReady' as const; +/** @internal */ +export const CONNECTION_CLOSED = 'connectionClosed' as const; +/** @internal */ +export const CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted' as const; +/** @internal */ +export const CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed' as const; +/** @internal */ +export const CONNECTION_CHECKED_OUT = 'connectionCheckedOut' as const; +/** @internal */ +export const CONNECTION_CHECKED_IN = 'connectionCheckedIn' as const; +export const CLUSTER_TIME_RECEIVED = 'clusterTimeReceived' as const; +/** @internal */ +export const COMMAND_STARTED = 'commandStarted' as const; +/** @internal */ +export const COMMAND_SUCCEEDED = 'commandSucceeded' as const; +/** @internal */ +export const COMMAND_FAILED = 'commandFailed' as const; +/** @internal */ +export const SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted' as const; +/** @internal */ +export const SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded' as const; +/** @internal */ +export const SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed' as const; +export const RESPONSE = 'response' as const; +export const MORE = 'more' as const; +export const INIT = 'init' as const; +export const CHANGE = 'change' as const; +export const END = 'end' as const; +export const RESUME_TOKEN_CHANGED = 'resumeTokenChanged' as const; + +/** @public */ +export const HEARTBEAT_EVENTS = Object.freeze([ + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_HEARTBEAT_FAILED +] as const); + +/** @public */ +export const CMAP_EVENTS = Object.freeze([ + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_CREATED, + CONNECTION_READY, + CONNECTION_CLOSED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECKED_OUT, + CONNECTION_CHECKED_IN +] as const); + +/** @public */ +export const TOPOLOGY_EVENTS = Object.freeze([ + SERVER_OPENING, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + ERROR, + TIMEOUT, + CLOSE +] as const); + +/** @public */ +export const APM_EVENTS = Object.freeze([ + COMMAND_STARTED, + COMMAND_SUCCEEDED, + COMMAND_FAILED +] as const); + +/** + * All events that we relay to the `Topology` + * @internal + */ +export const SERVER_RELAY_EVENTS = Object.freeze([ + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_HEARTBEAT_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + COMMAND_FAILED, + ...CMAP_EVENTS +] as const); + +/** + * All events we listen to from `Server` instances, but do not forward to the client + * @internal + */ +export const LOCAL_SERVER_EVENTS = Object.freeze([ + CONNECT, + DESCRIPTION_RECEIVED, + CLOSED, + ENDED +] as const); + +/** @public */ +export const MONGO_CLIENT_EVENTS = Object.freeze([ + ...CMAP_EVENTS, + ...APM_EVENTS, + ...TOPOLOGY_EVENTS, + ...HEARTBEAT_EVENTS +] as const); + +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +export const LEGACY_HELLO_COMMAND = 'ismaster'; + +/** + * @internal + * The legacy hello command that was deprecated in MongoDB 5.0. + */ +export const LEGACY_HELLO_COMMAND_CAMEL_CASE = 'isMaster'; diff --git a/nodejs/node_modules/mongodb/src/cursor/abstract_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/abstract_cursor.ts new file mode 100644 index 00000000..412361d0 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/abstract_cursor.ts @@ -0,0 +1,947 @@ +import { Readable, Transform } from 'stream'; + +import { type BSONSerializeOptions, type Document, Long, pluckBSONSerializeOptions } from '../bson'; +import { + type AnyError, + MongoAPIError, + MongoCursorExhaustedError, + MongoCursorInUseError, + MongoInvalidArgumentError, + MongoNetworkError, + MongoRuntimeError, + MongoTailableCursorError +} from '../error'; +import type { MongoClient } from '../mongo_client'; +import { type TODO_NODE_3286, TypedEventEmitter } from '../mongo_types'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import { GetMoreOperation } from '../operations/get_more'; +import { KillCursorsOperation } from '../operations/kill_cursors'; +import { ReadConcern, type ReadConcernLike } from '../read_concern'; +import { ReadPreference, type ReadPreferenceLike } from '../read_preference'; +import type { Server } from '../sdam/server'; +import { ClientSession, maybeClearPinnedConnection } from '../sessions'; +import { List, type MongoDBNamespace, ns } from '../utils'; + +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kClient = Symbol('client'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); +/** @internal */ +const kInit = Symbol('kInit'); + +/** @public */ +export const CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +] as const; + +/** @public */ +export interface CursorStreamOptions { + /** A transformation method applied to each document emitted by the stream */ + transform?(this: void, doc: Document): Document; +} + +/** @public */ +export type CursorFlag = (typeof CURSOR_FLAGS)[number]; + +/** @public */ +export interface AbstractCursorOptions extends BSONSerializeOptions { + session?: ClientSession; + readPreference?: ReadPreferenceLike; + readConcern?: ReadConcernLike; + /** + * Specifies the number of documents to return in each response from MongoDB + */ + batchSize?: number; + /** + * When applicable `maxTimeMS` controls the amount of time the initial command + * that constructs a cursor should take. (ex. find, aggregate, listCollections) + */ + maxTimeMS?: number; + /** + * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores + * that a cursor uses to fetch more data should take. (ex. cursor.next()) + */ + maxAwaitTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + /** + * By default, MongoDB will automatically close a cursor when the + * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections) + * you may use a Tailable Cursor that remains open after the client exhausts + * the results in the initial cursor. + */ + tailable?: boolean; + /** + * If awaitData is set to true, when the cursor reaches the end of the capped collection, + * MongoDB blocks the query thread for a period of time waiting for new data to arrive. + * When new data is inserted into the capped collection, the blocked thread is signaled + * to wake up and return the next batch to the client. + */ + awaitData?: boolean; + noCursorTimeout?: boolean; +} + +/** @internal */ +export type InternalAbstractCursorOptions = Omit & { + // resolved + readPreference: ReadPreference; + readConcern?: ReadConcern; + + // cursor flags, some are deprecated + oplogReplay?: boolean; + exhaust?: boolean; + partial?: boolean; +}; + +/** @public */ +export type AbstractCursorEvents = { + [AbstractCursor.CLOSE](): void; +}; + +/** @public */ +export abstract class AbstractCursor< + TSchema = any, + CursorEvents extends AbstractCursorEvents = AbstractCursorEvents +> extends TypedEventEmitter { + /** @internal */ + [kId]: Long | null; + /** @internal */ + [kSession]: ClientSession; + /** @internal */ + [kServer]?: Server; + /** @internal */ + [kNamespace]: MongoDBNamespace; + /** @internal */ + [kDocuments]: List; + /** @internal */ + [kClient]: MongoClient; + /** @internal */ + [kTransform]?: (doc: TSchema) => any; + /** @internal */ + [kInitialized]: boolean; + /** @internal */ + [kClosed]: boolean; + /** @internal */ + [kKilled]: boolean; + /** @internal */ + [kOptions]: InternalAbstractCursorOptions; + + /** @event */ + static readonly CLOSE = 'close' as const; + + /** @internal */ + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + options: AbstractCursorOptions = {} + ) { + super(); + + if (!client.s.isMongoClient) { + throw new MongoRuntimeError('Cursor must be constructed with MongoClient'); + } + this[kClient] = client; + this[kNamespace] = namespace; + this[kId] = null; + this[kDocuments] = new List(); + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: + options.readPreference && options.readPreference instanceof ReadPreference + ? options.readPreference + : ReadPreference.primary, + ...pluckBSONSerializeOptions(options) + }; + + const readConcern = ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this[kOptions].comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + + if (typeof options.maxAwaitTimeMS === 'number') { + this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS; + } + + if (options.session instanceof ClientSession) { + this[kSession] = options.session; + } else { + this[kSession] = this[kClient].startSession({ owner: this, explicit: false }); + } + } + + get id(): Long | undefined { + return this[kId] ?? undefined; + } + + /** @internal */ + get isDead() { + return (this[kId]?.isZero() ?? false) || this[kClosed] || this[kKilled]; + } + + /** @internal */ + get client(): MongoClient { + return this[kClient]; + } + + /** @internal */ + get server(): Server | undefined { + return this[kServer]; + } + + get namespace(): MongoDBNamespace { + return this[kNamespace]; + } + + get readPreference(): ReadPreference { + return this[kOptions].readPreference; + } + + get readConcern(): ReadConcern | undefined { + return this[kOptions].readConcern; + } + + /** @internal */ + get session(): ClientSession { + return this[kSession]; + } + + set session(clientSession: ClientSession) { + this[kSession] = clientSession; + } + + /** @internal */ + get cursorOptions(): InternalAbstractCursorOptions { + return this[kOptions]; + } + + get closed(): boolean { + return this[kClosed]; + } + + get killed(): boolean { + return this[kKilled]; + } + + get loadBalanced(): boolean { + return !!this[kClient].topology?.loadBalanced; + } + + /** Returns current buffered documents length */ + bufferedCount(): number { + return this[kDocuments].length; + } + + /** Returns current buffered documents */ + readBufferedDocuments(number?: number): TSchema[] { + const bufferedDocs: TSchema[] = []; + const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length); + + for (let count = 0; count < documentsToRead; count++) { + const document = this[kDocuments].shift(); + if (document != null) { + bufferedDocs.push(document); + } + } + + return bufferedDocs; + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + if (this.closed) { + return; + } + + try { + while (true) { + const document = await this.next(); + + // Intentional strict null check, because users can map cursors to falsey values. + // We allow mapping to all values except for null. + // eslint-disable-next-line no-restricted-syntax + if (document === null) { + if (!this.closed) { + const message = + 'Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.'; + + await cleanupCursor(this, { needsToEmitClosed: true }).catch(() => null); + + throw new MongoAPIError(message); + } + break; + } + + yield document; + + if (this[kId] === Long.ZERO) { + // Cursor exhausted + break; + } + } + } finally { + // Only close the cursor if it has not already been closed. This finally clause handles + // the case when a user would break out of a for await of loop early. + if (!this.closed) { + await this.close().catch(() => null); + } + } + } + + stream(options?: CursorStreamOptions): Readable & AsyncIterable { + if (options?.transform) { + const transform = options.transform; + const readable = new ReadableCursorStream(this); + + const transformedStream = readable.pipe( + new Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } catch (err) { + callback(err); + } + } + }) + ); + + // Bubble errors to transformed stream, because otherwise no way + // to handle this error. + readable.on('error', err => transformedStream.emit('error', err)); + + return transformedStream; + } + + return new ReadableCursorStream(this); + } + + async hasNext(): Promise { + if (this[kId] === Long.ZERO) { + return false; + } + + if (this[kDocuments].length !== 0) { + return true; + } + + const doc = await next(this, { blocking: true, transform: false }); + + if (doc) { + this[kDocuments].unshift(doc); + return true; + } + + return false; + } + + /** Get the next available document from the cursor, returns null if no more documents are available. */ + async next(): Promise { + if (this[kId] === Long.ZERO) { + throw new MongoCursorExhaustedError(); + } + + return next(this, { blocking: true, transform: true }); + } + + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + async tryNext(): Promise { + if (this[kId] === Long.ZERO) { + throw new MongoCursorExhaustedError(); + } + + return next(this, { blocking: false, transform: true }); + } + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + * @deprecated - Will be removed in a future release. Use for await...of instead. + */ + async forEach(iterator: (doc: TSchema) => boolean | void): Promise { + if (typeof iterator !== 'function') { + throw new MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + for await (const document of this) { + const result = iterator(document); + if (result === false) { + break; + } + } + } + + async close(): Promise { + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + await cleanupCursor(this, { needsToEmitClosed }); + } + + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + */ + async toArray(): Promise { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } + + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag: CursorFlag, value: boolean): this { + assertUninitialized(this); + if (!CURSOR_FLAGS.includes(flag)) { + throw new MongoInvalidArgumentError(`Flag ${flag} is not one of ${CURSOR_FLAGS}`); + } + + if (typeof value !== 'boolean') { + throw new MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + + this[kOptions][flag] = value; + return this; + } + + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * + * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform: (doc: TSchema) => T): AbstractCursor { + assertUninitialized(this); + const oldTransform = this[kTransform] as (doc: TSchema) => TSchema; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; + } else { + this[kTransform] = transform; + } + + return this as unknown as AbstractCursor; + } + + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference: ReadPreferenceLike): this { + assertUninitialized(this); + if (readPreference instanceof ReadPreference) { + this[kOptions].readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this[kOptions].readPreference = ReadPreference.fromString(readPreference); + } else { + throw new MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); + } + + return this; + } + + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern: ReadConcernLike): this { + assertUninitialized(this); + const resolvedReadConcern = ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + + this[kOptions].maxTimeMS = value; + return this; + } + + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}. + */ + batchSize(value: number): this { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + + this[kOptions].batchSize = value; + return this; + } + + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind(): void { + if (!this[kInitialized]) { + return; + } + + this[kId] = null; + this[kDocuments].clear(); + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false) { + if (!session.hasEnded) { + session.endSession().catch(() => null); + } + this[kSession] = this.client.startSession({ owner: this, explicit: false }); + } + } + } + + /** + * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance + */ + abstract clone(): AbstractCursor; + + /** @internal */ + protected abstract _initialize(session: ClientSession | undefined): Promise; + + /** @internal */ + async getMore(batchSize: number): Promise { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new GetMoreOperation(this[kNamespace], this[kId]!, this[kServer]!, { + ...this[kOptions], + session: this[kSession], + batchSize + }); + + return executeOperation(this[kClient], getMoreOperation); + } + + /** + * @internal + * + * This function is exposed for the unified test runner's createChangeStream + * operation. We cannot refactor to use the abstract _initialize method without + * a significant refactor. + */ + async [kInit](): Promise { + try { + const state = await this._initialize(this[kSession]); + const response = state.response; + this[kServer] = state.server; + if (response.cursor) { + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this[kId] = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? Long.fromBigInt(response.cursor.id) + : response.cursor.id; + + if (response.cursor.ns) { + this[kNamespace] = ns(response.cursor.ns); + } + + this[kDocuments].pushMany(response.cursor.firstBatch); + } + + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (this[kId] == null) { + this[kId] = Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + this[kDocuments].push(state.response as TODO_NODE_3286); + } + + // the cursor is now initialized, even if it is dead + this[kInitialized] = true; + } catch (error) { + // the cursor is now initialized, even if an error occurred + this[kInitialized] = true; + await cleanupCursor(this, { error }); + throw error; + } + + if (this.isDead) { + await cleanupCursor(this, undefined); + } + + return; + } +} + +/** + * @param cursor - the cursor on which to call `next` + * @param blocking - a boolean indicating whether or not the cursor should `block` until data + * is available. Generally, this flag is set to `false` because if the getMore returns no documents, + * the cursor has been exhausted. In certain scenarios (ChangeStreams, tailable await cursors and + * `tryNext`, for example) blocking is necessary because a getMore returning no documents does + * not indicate the end of the cursor. + * @param transform - if true, the cursor's transform function is applied to the result document (if the transform exists) + * @returns the next document in the cursor, or `null`. When `blocking` is `true`, a `null` document means + * the cursor has been exhausted. Otherwise, it means that there is no document available in the cursor's buffer. + */ +async function next( + cursor: AbstractCursor, + { + blocking, + transform + }: { + blocking: boolean; + transform: boolean; + } +): Promise { + if (cursor.closed) { + return null; + } + + do { + if (cursor[kId] == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + await cursor[kInit](); + } + + if (cursor[kDocuments].length !== 0) { + const doc = cursor[kDocuments].shift(); + + if (doc != null && transform && cursor[kTransform]) { + try { + return cursor[kTransform](doc); + } catch (error) { + // `cleanupCursorAsync` should never throw, but if it does we want to throw the original + // error instead. + await cleanupCursor(cursor, { error, needsToEmitClosed: true }).catch(() => null); + throw error; + } + } + + return doc; + } + + if (cursor.isDead) { + // if the cursor is dead, we clean it up + // cleanupCursorAsync should never throw, but if it does it indicates a bug in the driver + // and we should surface the error + await cleanupCursor(cursor, {}); + return null; + } + + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + + try { + const response = await cursor.getMore(batchSize); + + if (response) { + const cursorId = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? Long.fromBigInt(response.cursor.id) + : response.cursor.id; + + cursor[kDocuments].pushMany(response.cursor.nextBatch); + cursor[kId] = cursorId; + } + } catch (error) { + // `cleanupCursorAsync` should never throw, but if it does we want to throw the original + // error instead. + await cleanupCursor(cursor, { error }).catch(() => null); + throw error; + } + + if (cursor.isDead) { + // If we successfully received a response from a cursor BUT the cursor indicates that it is exhausted, + // we intentionally clean up the cursor to release its session back into the pool before the cursor + // is iterated. This prevents a cursor that is exhausted on the server from holding + // onto a session indefinitely until the AbstractCursor is iterated. + // + // cleanupCursorAsync should never throw, but if it does it indicates a bug in the driver + // and we should surface the error + await cleanupCursor(cursor, {}); + } + + if (cursor[kDocuments].length === 0 && blocking === false) { + return null; + } + } while (!cursor.isDead || cursor[kDocuments].length !== 0); + + return null; +} + +async function cleanupCursor( + cursor: AbstractCursor, + options: { error?: AnyError | undefined; needsToEmitClosed?: boolean } | undefined +): Promise { + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options?.error; + + // Cursors only emit closed events once the client-side cursor has been exhausted fully or there + // was an error. Notably, when the server returns a cursor id of 0 and a non-empty batch, we + // cleanup the cursor but don't emit a `close` event. + const needsToEmitClosed = options?.needsToEmitClosed ?? cursor[kDocuments].length === 0; + + if (error) { + if (cursor.loadBalanced && error instanceof MongoNetworkError) { + return completeCleanup(); + } + } + + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); + } + + if (session) { + if (session.owner === cursor) { + await session.endSession({ error }); + return; + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + return; + } + + async function completeCleanup() { + if (session) { + if (session.owner === cursor) { + try { + await session.endSession({ error }); + } finally { + cursor.emit(AbstractCursor.CLOSE); + } + return; + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + cursor.emit(AbstractCursor.CLOSE); + return; + } + + cursor[kKilled] = true; + + if (session.hasEnded) { + return completeCleanup(); + } + + try { + await executeOperation( + cursor[kClient], + new KillCursorsOperation(cursorId, cursorNs, server, { session }) + ).catch(() => null); + } finally { + await completeCleanup(); + } +} + +/** @internal */ +export function assertUninitialized(cursor: AbstractCursor): void { + if (cursor[kInitialized]) { + throw new MongoCursorInUseError(); + } +} + +class ReadableCursorStream extends Readable { + private _cursor: AbstractCursor; + private _readInProgress = false; + + constructor(cursor: AbstractCursor) { + super({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + this._cursor = cursor; + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + override _read(size: number): void { + if (!this._readInProgress) { + this._readInProgress = true; + this._readNext(); + } + } + + override _destroy(error: Error | null, callback: (error?: Error | null) => void): void { + this._cursor.close().then( + () => callback(error), + closeError => callback(closeError) + ); + } + + private _readNext() { + next(this._cursor, { blocking: true, transform: true }).then( + result => { + if (result == null) { + this.push(null); + } else if (this.destroyed) { + this._cursor.close().catch(() => null); + } else { + if (this.push(result)) { + return this._readNext(); + } + + this._readInProgress = false; + } + }, + err => { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + this._cursor.close().catch(() => null); + return this.push(null); + } + + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation was interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/operation was interrupted/)) { + return this.push(null); + } + + // NOTE: The two above checks on the message of the error will cause a null to be pushed + // to the stream, thus closing the stream before the destroy call happens. This means + // that either of those error messages on a change stream will not get a proper + // 'error' event to be emitted (the error passed to destroy). Change stream resumability + // relies on that error event to be emitted to create its new cursor and thus was not + // working on 4.4 servers because the error emitted on failover was "interrupted at + // shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down". + // See NODE-4475. + return this.destroy(err); + } + ); + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/aggregation_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/aggregation_cursor.ts new file mode 100644 index 00000000..c2979199 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/aggregation_cursor.ts @@ -0,0 +1,206 @@ +import type { Document } from '../bson'; +import type { ExplainVerbosityLike } from '../explain'; +import type { MongoClient } from '../mongo_client'; +import { AggregateOperation, type AggregateOptions } from '../operations/aggregate'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import type { ClientSession } from '../sessions'; +import type { Sort } from '../sort'; +import type { MongoDBNamespace } from '../utils'; +import { mergeOptions } from '../utils'; +import type { AbstractCursorOptions } from './abstract_cursor'; +import { AbstractCursor, assertUninitialized } from './abstract_cursor'; + +/** @public */ +export interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {} + +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); + +/** + * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * @public + */ +export class AggregationCursor extends AbstractCursor { + /** @internal */ + [kPipeline]: Document[]; + /** @internal */ + [kOptions]: AggregateOptions; + + /** @internal */ + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + pipeline: Document[] = [], + options: AggregateOptions = {} + ) { + super(client, namespace, options); + + this[kPipeline] = pipeline; + this[kOptions] = options; + } + + get pipeline(): Document[] { + return this[kPipeline]; + } + + clone(): AggregationCursor { + const clonedOptions = mergeOptions({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.client, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + + override map(transform: (doc: TSchema) => T): AggregationCursor { + return super.map(transform) as AggregationCursor; + } + + /** @internal */ + async _initialize(session: ClientSession): Promise { + const aggregateOperation = new AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + + const response = await executeOperation(this.client, aggregateOperation); + + // TODO: NODE-2882 + return { server: aggregateOperation.server, session, response }; + } + + /** Execute the explain for the cursor */ + async explain(verbosity?: ExplainVerbosityLike): Promise { + return executeOperation( + this.client, + new AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + explain: verbosity ?? true + }) + ); + } + + /** Add a group stage to the aggregation pipeline */ + group($group: Document): AggregationCursor; + group($group: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $group }); + return this; + } + + /** Add a limit stage to the aggregation pipeline */ + limit($limit: number): this { + assertUninitialized(this); + this[kPipeline].push({ $limit }); + return this; + } + + /** Add a match stage to the aggregation pipeline */ + match($match: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $match }); + return this; + } + + /** Add an out stage to the aggregation pipeline */ + out($out: { db: string; coll: string } | string): this { + assertUninitialized(this); + this[kPipeline].push({ $out }); + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project: Document): AggregationCursor { + assertUninitialized(this); + this[kPipeline].push({ $project }); + return this as unknown as AggregationCursor; + } + + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $lookup }); + return this; + } + + /** Add a redact stage to the aggregation pipeline */ + redact($redact: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $redact }); + return this; + } + + /** Add a skip stage to the aggregation pipeline */ + skip($skip: number): this { + assertUninitialized(this); + this[kPipeline].push({ $skip }); + return this; + } + + /** Add a sort stage to the aggregation pipeline */ + sort($sort: Sort): this { + assertUninitialized(this); + this[kPipeline].push({ $sort }); + return this; + } + + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind: Document | string): this { + assertUninitialized(this); + this[kPipeline].push({ $unwind }); + return this; + } + + /** Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/change_stream_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/change_stream_cursor.ts new file mode 100644 index 00000000..31fda330 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/change_stream_cursor.ts @@ -0,0 +1,185 @@ +import type { Document, Long, Timestamp } from '../bson'; +import { + ChangeStream, + type ChangeStreamDocument, + type ChangeStreamEvents, + type OperationTime, + type ResumeToken +} from '../change_stream'; +import { INIT, RESPONSE } from '../constants'; +import type { MongoClient } from '../mongo_client'; +import type { TODO_NODE_3286 } from '../mongo_types'; +import { AggregateOperation } from '../operations/aggregate'; +import type { CollationOptions } from '../operations/command'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import type { ClientSession } from '../sessions'; +import { maxWireVersion, type MongoDBNamespace } from '../utils'; +import { AbstractCursor, type AbstractCursorOptions } from './abstract_cursor'; + +/** @internal */ +export interface ChangeStreamCursorOptions extends AbstractCursorOptions { + startAtOperationTime?: OperationTime; + resumeAfter?: ResumeToken; + startAfter?: ResumeToken; + maxAwaitTimeMS?: number; + collation?: CollationOptions; + fullDocument?: string; +} + +/** @internal */ +export type ChangeStreamAggregateRawResult = { + $clusterTime: { clusterTime: Timestamp }; + cursor: { + postBatchResumeToken: ResumeToken; + ns: string; + id: number | Long; + } & ({ firstBatch: TChange[] } | { nextBatch: TChange[] }); + ok: 1; + operationTime: Timestamp; +}; + +/** @internal */ +export class ChangeStreamCursor< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument +> extends AbstractCursor { + _resumeToken: ResumeToken; + startAtOperationTime?: OperationTime; + hasReceived?: boolean; + resumeAfter: ResumeToken; + startAfter: ResumeToken; + options: ChangeStreamCursorOptions; + + postBatchResumeToken?: ResumeToken; + pipeline: Document[]; + + /** + * @internal + * + * used to determine change stream resumability + */ + maxWireVersion: number | undefined; + + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + pipeline: Document[] = [], + options: ChangeStreamCursorOptions = {} + ) { + super(client, namespace, options); + + this.pipeline = pipeline; + this.options = options; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + + if (options.startAfter) { + this.resumeToken = options.startAfter; + } else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + + set resumeToken(token: ResumeToken) { + this._resumeToken = token; + this.emit(ChangeStream.RESUME_TOKEN_CHANGED, token); + } + + get resumeToken(): ResumeToken { + return this._resumeToken; + } + + get resumeOptions(): ChangeStreamCursorOptions { + const options: ChangeStreamCursorOptions = { + ...this.options + }; + + for (const key of ['resumeAfter', 'startAfter', 'startAtOperationTime'] as const) { + delete options[key]; + } + + if (this.resumeToken != null) { + if (this.options.startAfter && !this.hasReceived) { + options.startAfter = this.resumeToken; + } else { + options.resumeAfter = this.resumeToken; + } + } else if (this.startAtOperationTime != null && maxWireVersion(this.server) >= 7) { + options.startAtOperationTime = this.startAtOperationTime; + } + + return options; + } + + cacheResumeToken(resumeToken: ResumeToken): void { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + + _processBatch(response: ChangeStreamAggregateRawResult): void { + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = response.cursor.postBatchResumeToken; + + const batch = + 'firstBatch' in response.cursor ? response.cursor.firstBatch : response.cursor.nextBatch; + if (batch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + + clone(): AbstractCursor { + return new ChangeStreamCursor(this.client, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + + async _initialize(session: ClientSession): Promise { + const aggregateOperation = new AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + + const response = await executeOperation< + TODO_NODE_3286, + ChangeStreamAggregateRawResult + >(session.client, aggregateOperation); + + const server = aggregateOperation.server; + this.maxWireVersion = maxWireVersion(server); + + if ( + this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + this.maxWireVersion >= 7 + ) { + this.startAtOperationTime = response.operationTime; + } + + this._processBatch(response); + + this.emit(INIT, response); + this.emit(RESPONSE); + + // TODO: NODE-2882 + return { server, session, response }; + } + + override async getMore(batchSize: number): Promise { + const response = await super.getMore(batchSize); + + this.maxWireVersion = maxWireVersion(this.server); + this._processBatch(response as ChangeStreamAggregateRawResult); + + this.emit(ChangeStream.MORE, response); + this.emit(ChangeStream.RESPONSE); + return response; + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/find_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/find_cursor.ts new file mode 100644 index 00000000..8f829a61 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/find_cursor.ts @@ -0,0 +1,454 @@ +import { type Document, Long } from '../bson'; +import { MongoInvalidArgumentError, MongoTailableCursorError } from '../error'; +import { type ExplainVerbosityLike } from '../explain'; +import type { MongoClient } from '../mongo_client'; +import type { CollationOptions } from '../operations/command'; +import { CountOperation, type CountOptions } from '../operations/count'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import { FindOperation, type FindOptions } from '../operations/find'; +import type { Hint } from '../operations/operation'; +import type { ClientSession } from '../sessions'; +import { formatSort, type Sort, type SortDirection } from '../sort'; +import { emitWarningOnce, mergeOptions, type MongoDBNamespace } from '../utils'; +import { AbstractCursor, assertUninitialized } from './abstract_cursor'; + +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); + +/** @public Flags allowed for cursor */ +export const FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +] as const; + +/** @public */ +export class FindCursor extends AbstractCursor { + /** @internal */ + [kFilter]: Document; + /** @internal */ + [kNumReturned]?: number; + /** @internal */ + [kBuiltOptions]: FindOptions; + + /** @internal */ + constructor( + client: MongoClient, + namespace: MongoDBNamespace, + filter: Document = {}, + options: FindOptions = {} + ) { + super(client, namespace, options); + + this[kFilter] = filter; + this[kBuiltOptions] = options; + + if (options.sort != null) { + this[kBuiltOptions].sort = formatSort(options.sort); + } + } + + clone(): FindCursor { + const clonedOptions = mergeOptions({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.client, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + + override map(transform: (doc: TSchema) => T): FindCursor { + return super.map(transform) as FindCursor; + } + + /** @internal */ + async _initialize(session: ClientSession): Promise { + const findOperation = new FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + session + }); + + const response = await executeOperation(this.client, findOperation); + + // the response is not a cursor when `explain` is enabled + this[kNumReturned] = response.cursor?.firstBatch?.length; + + // TODO: NODE-2882 + return { server: findOperation.server, session, response }; + } + + /** @internal */ + override async getMore(batchSize: number): Promise { + const numReturned = this[kNumReturned]; + if (numReturned) { + // TODO(DRIVERS-1448): Remove logic to enforce `limit` in the driver + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + + if (batchSize <= 0) { + // this is an optimization for the special case of a limit for a find command to avoid an + // extra getMore when the limit has been reached and the limit is a multiple of the batchSize. + // This is a consequence of the new query engine in 5.0 having no knowledge of the limit as it + // produces results for the find command. Once a batch is filled up, it is returned and only + // on the subsequent getMore will the query framework consider the limit, determine the cursor + // is exhausted and return a cursorId of zero. + // instead, if we determine there are no more documents to request from the server, we preemptively + // close the cursor + await this.close().catch(() => null); + return { cursor: { id: Long.ZERO, nextBatch: [] } }; + } + } + + const response = await super.getMore(batchSize); + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + + return response; + } + + /** + * Get the count of documents for this cursor + * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead + */ + async count(options?: CountOptions): Promise { + emitWarningOnce( + 'cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead ' + ); + if (typeof options === 'boolean') { + throw new MongoInvalidArgumentError('Invalid first parameter to count'); + } + return executeOperation( + this.client, + new CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + ...options + }) + ); + } + + /** Execute the explain for the cursor */ + async explain(verbosity?: ExplainVerbosityLike): Promise { + return executeOperation( + this.client, + new FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], // NOTE: order matters here, we may need to refine this + ...this.cursorOptions, + explain: verbosity ?? true + }) + ); + } + + /** Set the cursor query */ + filter(filter: Document): this { + assertUninitialized(this); + this[kFilter] = filter; + return this; + } + + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint: Hint): this { + assertUninitialized(this); + this[kBuiltOptions].hint = hint; + return this; + } + + /** + * Set the cursor min + * + * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + */ + min(min: Document): this { + assertUninitialized(this); + this[kBuiltOptions].min = min; + return this; + } + + /** + * Set the cursor max + * + * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + */ + max(max: Document): this { + assertUninitialized(this); + this[kBuiltOptions].max = max; + return this; + } + + /** + * Set the cursor returnKey. + * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. + * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * + * @param value - the returnKey value. + */ + returnKey(value: boolean): this { + assertUninitialized(this); + this[kBuiltOptions].returnKey = value; + return this; + } + + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value: boolean): this { + assertUninitialized(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name: string, value: string | boolean | number | Document): this { + assertUninitialized(this); + if (name[0] !== '$') { + throw new MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + + // Strip of the $ + const field = name.substr(1); + + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value as string | Document; + break; + + case 'explain': + this[kBuiltOptions].explain = value as boolean; + break; + + case 'hint': + this[kBuiltOptions].hint = value as string | Document; + break; + + case 'max': + this[kBuiltOptions].max = value as Document; + break; + + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value as number; + break; + + case 'min': + this[kBuiltOptions].min = value as Document; + break; + + case 'orderby': + this[kBuiltOptions].sort = formatSort(value as string | Document); + break; + + case 'query': + this[kFilter] = value as Document; + break; + + case 'returnKey': + this[kBuiltOptions].returnKey = value as boolean; + break; + + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value as boolean; + break; + + default: + throw new MongoInvalidArgumentError(`Invalid query modifier: ${name}`); + } + + return this; + } + + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value: string): this { + assertUninitialized(this); + this[kBuiltOptions].comment = value; + return this; + } + + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + + this[kBuiltOptions].maxAwaitTimeMS = value; + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + override maxTimeMS(value: number): this { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + + this[kBuiltOptions].maxTimeMS = value; + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value: Document): FindCursor { + assertUninitialized(this); + this[kBuiltOptions].projection = value; + return this as unknown as FindCursor; + } + + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort: Sort | string, direction?: SortDirection): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support sorting'); + } + + this[kBuiltOptions].sort = formatSort(sort, direction); + return this; + } + + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse(allow = true): this { + assertUninitialized(this); + + if (!this[kBuiltOptions].sort) { + throw new MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + + // As of 6.0 the default is true. This allows users to get back to the old behavior. + if (!allow) { + this[kBuiltOptions].allowDiskUse = false; + return this; + } + + this[kBuiltOptions].allowDiskUse = true; + return this; + } + + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value: CollationOptions): this { + assertUninitialized(this); + this[kBuiltOptions].collation = value; + return this; + } + + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value: number): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support limit'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + + this[kBuiltOptions].limit = value; + return this; + } + + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value: number): this { + assertUninitialized(this); + if (this[kBuiltOptions].tailable) { + throw new MongoTailableCursorError('Tailable cursor does not support skip'); + } + + if (typeof value !== 'number') { + throw new MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + + this[kBuiltOptions].skip = value; + return this; + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/list_collections_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/list_collections_cursor.ts new file mode 100644 index 00000000..6cefbd0d --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/list_collections_cursor.ts @@ -0,0 +1,49 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import { + type CollectionInfo, + ListCollectionsOperation, + type ListCollectionsOptions +} from '../operations/list_collections'; +import type { ClientSession } from '../sessions'; +import { AbstractCursor } from './abstract_cursor'; + +/** @public */ +export class ListCollectionsCursor< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo +> extends AbstractCursor { + parent: Db; + filter: Document; + options?: ListCollectionsOptions; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(db.client, db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + + clone(): ListCollectionsCursor { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + + /** @internal */ + async _initialize(session: ClientSession | undefined): Promise { + const operation = new ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + + const response = await executeOperation(this.parent.client, operation); + + // TODO: NODE-2882 + return { server: operation.server, session, response }; + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/list_indexes_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/list_indexes_cursor.ts new file mode 100644 index 00000000..7d75edb9 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/list_indexes_cursor.ts @@ -0,0 +1,38 @@ +import type { Collection } from '../collection'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import { ListIndexesOperation, type ListIndexesOptions } from '../operations/indexes'; +import type { ClientSession } from '../sessions'; +import { AbstractCursor } from './abstract_cursor'; + +/** @public */ +export class ListIndexesCursor extends AbstractCursor { + parent: Collection; + options?: ListIndexesOptions; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(collection.client, collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + + clone(): ListIndexesCursor { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + + /** @internal */ + async _initialize(session: ClientSession | undefined): Promise { + const operation = new ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + + const response = await executeOperation(this.parent.client, operation); + + // TODO: NODE-2882 + return { server: operation.server, session, response }; + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/list_search_indexes_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/list_search_indexes_cursor.ts new file mode 100644 index 00000000..bf5a0b56 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/list_search_indexes_cursor.ts @@ -0,0 +1,20 @@ +import type { Collection } from '../collection'; +import type { AggregateOptions } from '../operations/aggregate'; +import { AggregationCursor } from './aggregation_cursor'; + +/** @public */ +export type ListSearchIndexesOptions = AggregateOptions; + +/** @public */ +export class ListSearchIndexesCursor extends AggregationCursor<{ name: string }> { + /** @internal */ + constructor( + { fullNamespace: ns, client }: Collection, + name: string | null, + options: ListSearchIndexesOptions = {} + ) { + const pipeline = + name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }]; + super(client, ns, pipeline, options); + } +} diff --git a/nodejs/node_modules/mongodb/src/cursor/run_command_cursor.ts b/nodejs/node_modules/mongodb/src/cursor/run_command_cursor.ts new file mode 100644 index 00000000..f3fcedec --- /dev/null +++ b/nodejs/node_modules/mongodb/src/cursor/run_command_cursor.ts @@ -0,0 +1,133 @@ +import type { BSONSerializeOptions, Document, Long } from '../bson'; +import type { Db } from '../db'; +import { MongoAPIError, MongoUnexpectedServerResponseError } from '../error'; +import { executeOperation, type ExecutionResult } from '../operations/execute_operation'; +import { GetMoreOperation } from '../operations/get_more'; +import { RunCommandOperation } from '../operations/run_command'; +import type { ReadConcernLike } from '../read_concern'; +import type { ReadPreferenceLike } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import { ns } from '../utils'; +import { AbstractCursor } from './abstract_cursor'; + +/** @public */ +export type RunCursorCommandOptions = { + readPreference?: ReadPreferenceLike; + session?: ClientSession; +} & BSONSerializeOptions; + +/** @internal */ +type RunCursorCommandResponse = { + cursor: { id: bigint | Long | number; ns: string; firstBatch: Document[] }; + ok: 1; +}; + +/** @public */ +export class RunCommandCursor extends AbstractCursor { + public readonly command: Readonly>; + public readonly getMoreOptions: { + comment?: any; + maxAwaitTimeMS?: number; + batchSize?: number; + } = {}; + + /** + * Controls the `getMore.comment` field + * @param comment - any BSON value + */ + public setComment(comment: any): this { + this.getMoreOptions.comment = comment; + return this; + } + + /** + * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await + * @param maxTimeMS - the number of milliseconds to wait for new data + */ + public setMaxTimeMS(maxTimeMS: number): this { + this.getMoreOptions.maxAwaitTimeMS = maxTimeMS; + return this; + } + + /** + * Controls the `getMore.batchSize` field + * @param maxTimeMS - the number documents to return in the `nextBatch` + */ + public setBatchSize(batchSize: number): this { + this.getMoreOptions.batchSize = batchSize; + return this; + } + + /** Unsupported for RunCommandCursor */ + public override clone(): never { + throw new MongoAPIError('Clone not supported, create a new cursor with db.runCursorCommand'); + } + + /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */ + public override withReadConcern(_: ReadConcernLike): never { + throw new MongoAPIError( + 'RunCommandCursor does not support readConcern it must be attached to the command being run' + ); + } + + /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */ + public override addCursorFlag(_: string, __: boolean): never { + throw new MongoAPIError( + 'RunCommandCursor does not support cursor flags, they must be attached to the command being run' + ); + } + + /** Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document */ + public override maxTimeMS(_: number): never { + throw new MongoAPIError( + 'maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()' + ); + } + + /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */ + public override batchSize(_: number): never { + throw new MongoAPIError( + 'batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()' + ); + } + + /** @internal */ + private db: Db; + + /** @internal */ + constructor(db: Db, command: Document, options: RunCursorCommandOptions = {}) { + super(db.client, ns(db.namespace), options); + this.db = db; + this.command = Object.freeze({ ...command }); + } + + /** @internal */ + protected async _initialize(session: ClientSession): Promise { + const operation = new RunCommandOperation(this.db, this.command, { + ...this.cursorOptions, + session: session, + readPreference: this.cursorOptions.readPreference + }); + const response = await executeOperation(this.client, operation); + if (response.cursor == null) { + throw new MongoUnexpectedServerResponseError('Expected server to respond with cursor'); + } + return { + server: operation.server, + session, + response + }; + } + + /** @internal */ + override async getMore(_batchSize: number): Promise { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new GetMoreOperation(this.namespace, this.id!, this.server!, { + ...this.cursorOptions, + session: this.session, + ...this.getMoreOptions + }); + + return executeOperation(this.client, getMoreOperation); + } +} diff --git a/nodejs/node_modules/mongodb/src/db.ts b/nodejs/node_modules/mongodb/src/db.ts new file mode 100644 index 00000000..c12c22c7 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/db.ts @@ -0,0 +1,529 @@ +import { Admin } from './admin'; +import { type BSONSerializeOptions, type Document, resolveBSONOptions } from './bson'; +import { ChangeStream, type ChangeStreamDocument, type ChangeStreamOptions } from './change_stream'; +import { Collection, type CollectionOptions } from './collection'; +import * as CONSTANTS from './constants'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { ListCollectionsCursor } from './cursor/list_collections_cursor'; +import { RunCommandCursor, type RunCursorCommandOptions } from './cursor/run_command_cursor'; +import { MongoInvalidArgumentError } from './error'; +import type { MongoClient, PkFactory } from './mongo_client'; +import type { TODO_NODE_3286 } from './mongo_types'; +import type { AggregateOptions } from './operations/aggregate'; +import { CollectionsOperation } from './operations/collections'; +import type { IndexInformationOptions } from './operations/common_functions'; +import { + CreateCollectionOperation, + type CreateCollectionOptions +} from './operations/create_collection'; +import { + DropCollectionOperation, + type DropCollectionOptions, + DropDatabaseOperation, + type DropDatabaseOptions +} from './operations/drop'; +import { executeOperation } from './operations/execute_operation'; +import { + type CreateIndexesOptions, + CreateIndexOperation, + IndexInformationOperation, + type IndexSpecification +} from './operations/indexes'; +import type { CollectionInfo, ListCollectionsOptions } from './operations/list_collections'; +import { ProfilingLevelOperation, type ProfilingLevelOptions } from './operations/profiling_level'; +import { RemoveUserOperation, type RemoveUserOptions } from './operations/remove_user'; +import { RenameOperation, type RenameOptions } from './operations/rename'; +import { RunCommandOperation, type RunCommandOptions } from './operations/run_command'; +import { + type ProfilingLevel, + SetProfilingLevelOperation, + type SetProfilingLevelOptions +} from './operations/set_profiling_level'; +import { DbStatsOperation, type DbStatsOptions } from './operations/stats'; +import { ReadConcern } from './read_concern'; +import { ReadPreference, type ReadPreferenceLike } from './read_preference'; +import { DEFAULT_PK_FACTORY, filterOptions, MongoDBNamespace, resolveOptions } from './utils'; +import { WriteConcern, type WriteConcernOptions } from './write_concern'; + +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'useBigInt64', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** @internal */ +export interface DbPrivate { + options?: DbOptions; + readPreference?: ReadPreference; + pkFactory: PkFactory; + readConcern?: ReadConcern; + bsonOptions: BSONSerializeOptions; + writeConcern?: WriteConcern; + namespace: MongoDBNamespace; +} + +/** @public */ +export interface DbOptions extends BSONSerializeOptions, WriteConcernOptions { + /** If the database authentication is dependent on another databaseName. */ + authSource?: string; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; + /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */ + readPreference?: ReadPreferenceLike; + /** A primary key factory object for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcern; + /** Should retry failed writes */ + retryWrites?: boolean; +} + +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +export class Db { + /** @internal */ + s: DbPrivate; + + /** @internal */ + readonly client: MongoClient; + + public static SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; + public static SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; + public static SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; + public static SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; + public static SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; + public static SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + + /** + * Creates a new Db instance. + * + * Db name cannot contain a dot, the server may apply more restrictions when an operation is run. + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction. + */ + constructor(client: MongoClient, databaseName: string, options?: DbOptions) { + options = options ?? {}; + + // Filter the options + options = filterOptions(options, DB_OPTIONS_ALLOW_LIST); + + // Ensure there are no dots in database name + if (typeof databaseName === 'string' && databaseName.includes('.')) { + throw new MongoInvalidArgumentError(`Database names cannot contain the character '.'`); + } + + // Internal state of the db object + this.s = { + // Options + options, + // Unpack read preference + readPreference: ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: resolveBSONOptions(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: options?.pkFactory ?? DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + // Namespace + namespace: new MongoDBNamespace(databaseName) + }; + + this.client = client; + } + + get databaseName(): string { + return this.s.namespace.db; + } + + // Options + get options(): DbOptions | undefined { + return this.s.options; + } + + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk(): boolean { + return this.s.readPreference?.preference !== 'primary' || false; + } + + get readConcern(): ReadConcern | undefined { + return this.s.readConcern; + } + + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference(): ReadPreference { + if (this.s.readPreference == null) { + return this.client.readPreference; + } + + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + // get the write Concern + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get namespace(): string { + return this.s.namespace.toString(); + } + + /** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/ + * + * Collection namespace validation is performed server-side. + * + * @param name - The name of the collection to create + * @param options - Optional settings for the command + */ + async createCollection( + name: string, + options?: CreateCollectionOptions + ): Promise> { + return executeOperation( + this.client, + new CreateCollectionOperation(this, name, resolveOptions(this, options)) as TODO_NODE_3286 + ); + } + + /** + * Execute a command + * + * @remarks + * This command does not inherit options from the MongoClient. + * + * The driver will ensure the following fields are attached to the command sent to the server: + * - `lsid` - sourced from an implicit session or options.session + * - `$readPreference` - defaults to primary or can be configured by options.readPreference + * - `$db` - sourced from the name of this database + * + * If the client has a serverApi setting: + * - `apiVersion` + * - `apiStrict` + * - `apiDeprecationErrors` + * + * When in a transaction: + * - `readConcern` - sourced from readConcern set on the TransactionOptions + * - `writeConcern` - sourced from writeConcern set on the TransactionOptions + * + * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value. + * + * @param command - The command to run + * @param options - Optional settings for the command + */ + async command(command: Document, options?: RunCommandOptions): Promise { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.client, + new RunCommandOperation(this, command, { + ...resolveBSONOptions(options), + session: options?.session, + readPreference: options?.readPreference + }) + ); + } + + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate( + pipeline: Document[] = [], + options?: AggregateOptions + ): AggregationCursor { + return new AggregationCursor( + this.client, + this.s.namespace, + pipeline, + resolveOptions(this, options) + ); + } + + /** Return the Admin db instance */ + admin(): Admin { + return new Admin(this); + } + + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * Collection namespace validation is performed server-side. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection( + name: string, + options: CollectionOptions = {} + ): Collection { + if (typeof options === 'function') { + throw new MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + return new Collection(this, name, resolveOptions(this, options)); + } + + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + async stats(options?: DbStatsOptions): Promise { + return executeOperation(this.client, new DbStatsOperation(this, resolveOptions(this, options))); + } + + /** + * List all collections of this database with optional filter + * + * @param filter - Query to filter collections by + * @param options - Optional settings for the command + */ + listCollections( + filter: Document, + options: Exclude & { nameOnly: true } + ): ListCollectionsCursor>; + listCollections( + filter: Document, + options: Exclude & { nameOnly: false } + ): ListCollectionsCursor; + listCollections< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo + >(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor; + listCollections< + T extends Pick | CollectionInfo = + | Pick + | CollectionInfo + >(filter: Document = {}, options: ListCollectionsOptions = {}): ListCollectionsCursor { + return new ListCollectionsCursor(this, filter, resolveOptions(this, options)); + } + + /** + * Rename a collection. + * + * @remarks + * This operation does not inherit options from the MongoClient. + * + * @param fromCollection - Name of current collection to rename + * @param toCollection - New name of of the collection + * @param options - Optional settings for the command + */ + async renameCollection( + fromCollection: string, + toCollection: string, + options?: RenameOptions + ): Promise> { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.client, + new RenameOperation( + this.collection(fromCollection) as TODO_NODE_3286, + toCollection, + { ...options, new_collection: true, readPreference: ReadPreference.primary } + ) as TODO_NODE_3286 + ); + } + + /** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param name - Name of collection to drop + * @param options - Optional settings for the command + */ + async dropCollection(name: string, options?: DropCollectionOptions): Promise { + return executeOperation( + this.client, + new DropCollectionOperation(this, name, resolveOptions(this, options)) + ); + } + + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + async dropDatabase(options?: DropDatabaseOptions): Promise { + return executeOperation( + this.client, + new DropDatabaseOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + async collections(options?: ListCollectionsOptions): Promise { + return executeOperation( + this.client, + new CollectionsOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Creates an index on the db and collection. + * + * @param name - Name of the collection to create the index on. + * @param indexSpec - Specify the field to index, or an index specification + * @param options - Optional settings for the command + */ + async createIndex( + name: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.client, + new CreateIndexOperation(this, name, indexSpec, resolveOptions(this, options)) + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username: string, options?: RemoveUserOptions): Promise { + return executeOperation( + this.client, + new RemoveUserOperation(this, username, resolveOptions(this, options)) + ); + } + + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + async setProfilingLevel( + level: ProfilingLevel, + options?: SetProfilingLevelOptions + ): Promise { + return executeOperation( + this.client, + new SetProfilingLevelOperation(this, level, resolveOptions(this, options)) + ); + } + + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + async profilingLevel(options?: ProfilingLevelOptions): Promise { + return executeOperation( + this.client, + new ProfilingLevelOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + async indexInformation(name: string, options?: IndexInformationOptions): Promise { + return executeOperation( + this.client, + new IndexInformationOperation(this, name, resolveOptions(this, options)) + ); + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this database. Will ignore all + * changes to system collections. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to provide the schema that may be defined for all the collections within this database + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument + >(pipeline: Document[] = [], options: ChangeStreamOptions = {}): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } + + /** + * A low level cursor API providing basic driver functionality: + * - ClientSession management + * - ReadPreference for server selection + * - Running getMores automatically when a local batch is exhausted + * + * @param command - The command that will start a cursor on the server. + * @param options - Configurations for running the command, bson options will apply to getMores + */ + runCursorCommand(command: Document, options?: RunCursorCommandOptions): RunCommandCursor { + return new RunCommandCursor(this, command, options); + } +} diff --git a/nodejs/node_modules/mongodb/src/deps.ts b/nodejs/node_modules/mongodb/src/deps.ts new file mode 100644 index 00000000..7a3c121f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/deps.ts @@ -0,0 +1,268 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import { type Stream } from './cmap/connect'; +import { MongoMissingDependencyError } from './error'; +import type { Callback } from './utils'; + +function makeErrorModule(error: any) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_: any, key: any) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; + } + }); +} + +export let Kerberos: typeof import('kerberos') | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `kerberos` not found. Please install it to enable kerberos authentication' + ) + ); + +export function getKerberos(): typeof Kerberos | { kModuleError: MongoMissingDependencyError } { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + Kerberos = require('kerberos'); + return Kerberos; + } catch { + return Kerberos; + } +} + +export interface KerberosClient { + step(challenge: string): Promise; + step(challenge: string, callback: Callback): void; + wrap(challenge: string, options: { user: string }): Promise; + wrap(challenge: string, options: { user: string }, callback: Callback): void; + unwrap(challenge: string): Promise; + unwrap(challenge: string, callback: Callback): void; +} + +type ZStandardLib = { + /** + * Compress using zstd. + * @param buf - Buffer to be compressed. + */ + compress(buf: Buffer, level?: number): Promise; + + /** + * Decompress using zstd. + */ + decompress(buf: Buffer): Promise; +}; + +export let ZStandard: ZStandardLib | { kModuleError: MongoMissingDependencyError } = + makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression' + ) + ); + +export function getZstdLibrary(): typeof ZStandard | { kModuleError: MongoMissingDependencyError } { + try { + ZStandard = require('@mongodb-js/zstd'); + return ZStandard; + } catch { + return ZStandard; + } +} + +/** + * @internal + * Copy of the AwsCredentialIdentityProvider interface from [`smithy/types`](https://socket.dev/npm/package/\@smithy/types/files/1.1.1/dist-types/identity/awsCredentialIdentity.d.ts), + * the return type of the aws-sdk's `fromNodeProviderChain().provider()`. + */ +export interface AWSCredentials { + accessKeyId: string; + secretAccessKey: string; + sessionToken: string; + expiration?: Date; +} + +type CredentialProvider = { + fromNodeProviderChain( + this: void, + options: { clientConfig: { region: string } } + ): () => Promise; + fromNodeProviderChain(this: void): () => Promise; +}; + +export function getAwsCredentialProvider(): + | CredentialProvider + | { kModuleError: MongoMissingDependencyError } { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('@aws-sdk/credential-providers'); + return credentialProvider; + } catch { + return makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `@aws-sdk/credential-providers` not found.' + + ' Please install it to enable getting aws credentials via the official sdk.' + ) + ); + } +} + +/** @internal */ +export type GcpMetadata = + | typeof import('gcp-metadata') + | { kModuleError: MongoMissingDependencyError }; + +export function getGcpMetadata(): GcpMetadata { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('gcp-metadata'); + return credentialProvider; + } catch { + return makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `gcp-metadata` not found.' + + ' Please install it to enable getting gcp credentials via the official sdk.' + ) + ); + } +} + +/** @internal */ +export type SnappyLib = { + /** + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + */ + compress(buf: Buffer): Promise; + + /** + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + */ + uncompress(buf: Buffer, opt: { asBuffer: true }): Promise; +}; + +export function getSnappy(): SnappyLib | { kModuleError: MongoMissingDependencyError } { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const value = require('snappy'); + return value; + } catch (cause) { + const kModuleError = new MongoMissingDependencyError( + 'Optional module `snappy` not found. Please install it to enable snappy compression', + { cause } + ); + return { kModuleError }; + } +} + +export type SocksLib = { + SocksClient: { + createConnection(options: { + command: 'connect'; + destination: { host: string; port: number }; + proxy: { + /** host and port are ignored because we pass existing_socket */ + host: 'iLoveJavaScript'; + port: 0; + type: 5; + userId?: string; + password?: string; + }; + timeout?: number; + /** We always create our own socket, and pass it to this API for proxy negotiation */ + existing_socket: Stream; + }): Promise<{ socket: Stream }>; + }; +}; + +export function getSocks(): SocksLib | { kModuleError: MongoMissingDependencyError } { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const value = require('socks'); + return value; + } catch (cause) { + const kModuleError = new MongoMissingDependencyError( + 'Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy', + { cause } + ); + return { kModuleError }; + } +} + +interface AWS4 { + /** + * Created these inline types to better assert future usage of this API + * @param options - options for request + * @param credentials - AWS credential details, sessionToken should be omitted entirely if its false-y + */ + sign( + this: void, + options: { + path: '/'; + body: string; + host: string; + method: 'POST'; + headers: { + 'Content-Type': 'application/x-www-form-urlencoded'; + 'Content-Length': number; + 'X-MongoDB-Server-Nonce': string; + 'X-MongoDB-GS2-CB-Flag': 'n'; + }; + service: string; + region: string; + }, + credentials: + | { + accessKeyId: string; + secretAccessKey: string; + sessionToken: string; + } + | { + accessKeyId: string; + secretAccessKey: string; + } + | undefined + ): { + headers: { + Authorization: string; + 'X-Amz-Date': string; + }; + }; +} + +export let aws4: AWS4 | { kModuleError: MongoMissingDependencyError } = makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `aws4` not found. Please install it to enable AWS authentication' + ) +); + +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + aws4 = require('aws4'); +} catch {} // eslint-disable-line + +/** A utility function to get the instance of mongodb-client-encryption, if it exists. */ +export function getMongoDBClientEncryption(): + | typeof import('mongodb-client-encryption') + | { kModuleError: MongoMissingDependencyError } { + let mongodbClientEncryption = null; + + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require('mongodb-client-encryption'); + } catch (cause) { + const kModuleError = new MongoMissingDependencyError( + 'Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.', + { cause } + ); + return { kModuleError }; + } + + return mongodbClientEncryption; +} diff --git a/nodejs/node_modules/mongodb/src/encrypter.ts b/nodejs/node_modules/mongodb/src/encrypter.ts new file mode 100644 index 00000000..db3413ba --- /dev/null +++ b/nodejs/node_modules/mongodb/src/encrypter.ts @@ -0,0 +1,130 @@ +import { callbackify } from 'util'; + +import { AutoEncrypter, type AutoEncryptionOptions } from './client-side-encryption/auto_encrypter'; +import { MONGO_CLIENT_EVENTS } from './constants'; +import { getMongoDBClientEncryption } from './deps'; +import { MongoInvalidArgumentError, MongoMissingDependencyError } from './error'; +import { MongoClient, type MongoClientOptions } from './mongo_client'; +import { type Callback } from './utils'; + +/** @internal */ +const kInternalClient = Symbol('internalClient'); + +/** @internal */ +export interface EncrypterOptions { + autoEncryption: AutoEncryptionOptions; + maxPoolSize?: number; +} + +/** @internal */ +export class Encrypter { + [kInternalClient]: MongoClient | null; + bypassAutoEncryption: boolean; + needsConnecting: boolean; + autoEncrypter: AutoEncrypter; + + constructor(client: MongoClient, uri: string, options: MongoClientOptions) { + if (typeof options.autoEncryption !== 'object') { + throw new MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + // initialize to null, if we call getInternalClient, we may set this it is important to not overwrite those function calls. + this[kInternalClient] = null; + + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; + } else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); + } + + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; + } else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + + if (options.proxyHost) { + options.autoEncryption.proxyOptions = { + proxyHost: options.proxyHost, + proxyPort: options.proxyPort, + proxyUsername: options.proxyUsername, + proxyPassword: options.proxyPassword + }; + } + + this.autoEncrypter = new AutoEncrypter(client, options.autoEncryption); + } + + getInternalClient(client: MongoClient, uri: string, options: MongoClientOptions): MongoClient { + // TODO(NODE-4144): Remove new variable for type narrowing + let internalClient = this[kInternalClient]; + if (internalClient == null) { + const clonedOptions: MongoClientOptions = {}; + + for (const key of [ + ...Object.getOwnPropertyNames(options), + ...Object.getOwnPropertySymbols(options) + ] as string[]) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); + } + + clonedOptions.minPoolSize = 0; + + internalClient = new MongoClient(uri, clonedOptions); + this[kInternalClient] = internalClient; + + for (const eventName of MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + internalClient.on(eventName, listener); + } + } + + client.on('newListener', (eventName, listener) => { + internalClient?.on(eventName, listener); + }); + + this.needsConnecting = true; + } + return internalClient; + } + + async connectInternalClient(): Promise { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + await internalClient.connect(); + } + } + + closeCallback(client: MongoClient, force: boolean, callback: Callback) { + callbackify(this.close.bind(this))(client, force, callback); + } + + async close(client: MongoClient, force: boolean): Promise { + const maybeError: Error | void = await this.autoEncrypter.teardown(!!force).catch(e => e); + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + return internalClient.close(force); + } + if (maybeError) { + throw maybeError; + } + } + + static checkForMongoCrypt(): void { + const mongodbClientEncryption = getMongoDBClientEncryption(); + if ('kModuleError' in mongodbClientEncryption) { + throw new MongoMissingDependencyError( + 'Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project' + ); + } + } +} diff --git a/nodejs/node_modules/mongodb/src/error.ts b/nodejs/node_modules/mongodb/src/error.ts new file mode 100644 index 00000000..6f91f246 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/error.ts @@ -0,0 +1,1330 @@ +import type { Document } from './bson'; +import type { TopologyVersion } from './sdam/server_description'; +import type { TopologyDescription } from './sdam/topology_description'; + +/** @public */ +export type AnyError = MongoError | Error; + +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); + +/** + * @internal + * The legacy error message from the server that indicates the node is not a writable primary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +export const LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp('not master', 'i'); + +/** + * @internal + * The legacy error message from the server that indicates the node is not a primary or secondary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +export const LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp( + 'not master or secondary', + 'i' +); + +/** + * @internal + * The error message from the server that indicates the node is recovering + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +export const NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp('node is recovering', 'i'); + +/** @internal MongoDB Error Codes */ +export const MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotWritablePrimary: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotPrimaryNoSecondaryOk: 13435, + NotPrimaryOrSecondary: 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, + Reauthenticate: 391 +} as const); + +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +export const GET_MORE_RESUMABLE_CODES = new Set([ + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.ExceededTimeLimit, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.NotWritablePrimary, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + MONGODB_ERROR_CODES.StaleShardVersion, + MONGODB_ERROR_CODES.StaleEpoch, + MONGODB_ERROR_CODES.StaleConfig, + MONGODB_ERROR_CODES.RetryChangeStream, + MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + MONGODB_ERROR_CODES.CursorNotFound +]); + +/** @public */ +export const MongoErrorLabel = Object.freeze({ + RetryableWriteError: 'RetryableWriteError', + TransientTransactionError: 'TransientTransactionError', + UnknownTransactionCommitResult: 'UnknownTransactionCommitResult', + ResumableChangeStreamError: 'ResumableChangeStreamError', + HandshakeError: 'HandshakeError', + ResetPool: 'ResetPool', + PoolRequstedRetry: 'PoolRequstedRetry', + InterruptInUseConnections: 'InterruptInUseConnections', + NoWritesPerformed: 'NoWritesPerformed' +} as const); + +/** @public */ +export type MongoErrorLabel = (typeof MongoErrorLabel)[keyof typeof MongoErrorLabel]; + +/** @public */ +export interface ErrorDescription extends Document { + message?: string; + errmsg?: string; + $err?: string; + errorLabels?: string[]; + errInfo?: Document; +} + +function isAggregateError(e: unknown): e is Error & { errors: Error[] } { + return e != null && typeof e === 'object' && 'errors' in e && Array.isArray(e.errors); +} + +/** + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument + */ +export class MongoError extends Error { + /** @internal */ + [kErrorLabels]: Set; + /** + * This is a number in MongoServerError and a string in MongoDriverError + * @privateRemarks + * Define the type override on the subclasses when we can use the override keyword + */ + code?: number | string; + topologyVersion?: TopologyVersion; + connectionGeneration?: number; + override cause?: Error; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { cause?: Error }) { + super(message, options); + this[kErrorLabels] = new Set(); + } + + /** @internal */ + static buildErrorMessage(e: unknown): string { + if (typeof e === 'string') { + return e; + } + if (isAggregateError(e) && e.message.length === 0) { + return e.errors.length === 0 + ? 'AggregateError has an empty errors array. Please check the `cause` property for more information.' + : e.errors.map(({ message }) => message).join(', '); + } + + return e != null && typeof e === 'object' && 'message' in e && typeof e.message === 'string' + ? e.message + : 'empty error message'; + } + + override get name(): string { + return 'MongoError'; + } + + /** Legacy name for server error responses */ + get errmsg(): string { + return this.message; + } + + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns returns true if the error has the provided error label + */ + hasErrorLabel(label: string): boolean { + return this[kErrorLabels].has(label); + } + + addErrorLabel(label: string): void { + this[kErrorLabels].add(label); + } + + get errorLabels(): string[] { + return Array.from(this[kErrorLabels]); + } +} + +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +export class MongoServerError extends MongoError { + /** Raw error result document returned by server. */ + errorResponse: ErrorDescription; + codeName?: string; + writeConcernError?: Document; + errInfo?: Document; + ok?: number; + [key: string]: any; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: ErrorDescription) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + + this.errorResponse = message; + + for (const name in message) { + if ( + name !== 'errorLabels' && + name !== 'errmsg' && + name !== 'message' && + name !== 'errorResponse' + ) { + this[name] = message[name]; + } + } + } + + override get name(): string { + return 'MongoServerError'; + } +} + +/** + * An error generated by the driver + * + * @public + * @category Error + */ +export class MongoDriverError extends MongoError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { cause?: Error }) { + super(message, options); + } + + override get name(): string { + return 'MongoDriverError'; + } +} + +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ + +export class MongoAPIError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { cause?: Error }) { + super(message, options); + } + + override get name(): string { + return 'MongoAPIError'; + } +} + +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +export class MongoRuntimeError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: { cause?: Error }) { + super(message, options); + } + + override get name(): string { + return 'MongoRuntimeError'; + } +} + +/** + * An error generated when a batch command is re-executed after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +export class MongoBatchReExecutionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + + override get name(): string { + return 'MongoBatchReExecutionError'; + } +} + +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +export class MongoDecompressionError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoDecompressionError'; + } +} + +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +export class MongoNotConnectedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoNotConnectedError'; + } +} + +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +export class MongoTransactionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoTransactionError'; + } +} + +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +export class MongoExpiredSessionError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + + override get name(): string { + return 'MongoExpiredSessionError'; + } +} + +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +export class MongoKerberosError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoKerberosError'; + } +} + +/** + * A error generated when the user attempts to authenticate + * via AWS, but fails + * + * @public + * @category Error + */ +export class MongoAWSError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoAWSError'; + } +} + +/** + * A error generated when the user attempts to authenticate + * via Azure, but fails. + * + * @public + * @category Error + */ +export class MongoAzureError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoAzureError'; + } +} + +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +export class MongoChangeStreamError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoChangeStreamError'; + } +} + +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +export class MongoTailableCursorError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + + override get name(): string { + return 'MongoTailableCursorError'; + } +} + +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +export class MongoGridFSStreamError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoGridFSStreamError'; + } +} + +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +export class MongoGridFSChunkError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoGridFSChunkError'; + } +} + +/** + * An error generated when a **parsable** unexpected response comes from the server. + * This is generally an error where the driver in a state expecting a certain behavior to occur in + * the next message from MongoDB but it receives something else. + * This error **does not** represent an issue with wire message formatting. + * + * #### Example + * When an operation fails, it is the driver's job to retry it. It must perform serverSelection + * again to make sure that it attempts the operation against a server in a good state. If server + * selection returns a server that does not support retryable operations, this error is used. + * This scenario is unlikely as retryable support would also have been determined on the first attempt + * but it is possible the state change could report a selectable server that does not support retries. + * + * @public + * @category Error + */ +export class MongoUnexpectedServerResponseError extends MongoRuntimeError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoUnexpectedServerResponseError'; + } +} + +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +export class MongoCursorInUseError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Cursor is already initialized') { + super(message); + } + + override get name(): string { + return 'MongoCursorInUseError'; + } +} + +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +export class MongoServerClosedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Server is closed') { + super(message); + } + + override get name(): string { + return 'MongoServerClosedError'; + } +} + +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +export class MongoCursorExhaustedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message?: string) { + super(message || 'Cursor is exhausted'); + } + + override get name(): string { + return 'MongoCursorExhaustedError'; + } +} + +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +export class MongoTopologyClosedError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message = 'Topology is closed') { + super(message); + } + + override get name(): string { + return 'MongoTopologyClosedError'; + } +} + +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +export function isNetworkErrorBeforeHandshake(err: MongoNetworkError): boolean { + return err[kBeforeHandshake] === true; +} + +/** @public */ +export interface MongoNetworkErrorOptions { + /** Indicates the timeout happened before a connection handshake completed */ + beforeHandshake?: boolean; + cause?: Error; +} + +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +export class MongoNetworkError extends MongoError { + /** @internal */ + [kBeforeHandshake]?: boolean; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: MongoNetworkErrorOptions) { + super(message, { cause: options?.cause }); + + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + + override get name(): string { + return 'MongoNetworkError'; + } +} + +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption has a dependency on this error with an instanceof check + */ +export class MongoNetworkTimeoutError extends MongoNetworkError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options?: MongoNetworkErrorOptions) { + super(message, options); + } + + override get name(): string { + return 'MongoNetworkTimeoutError'; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +export class MongoParseError extends MongoDriverError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoParseError'; + } +} + +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +export class MongoInvalidArgumentError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoInvalidArgumentError'; + } +} + +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +export class MongoCompatibilityError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoCompatibilityError'; + } +} + +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +export class MongoMissingCredentialsError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string) { + super(message); + } + + override get name(): string { + return 'MongoMissingCredentialsError'; + } +} + +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +export class MongoMissingDependencyError extends MongoAPIError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, options: { cause?: Error } = {}) { + super(message, options); + } + + override get name(): string { + return 'MongoMissingDependencyError'; + } +} +/** + * An error signifying a general system issue + * @public + * @category Error + */ +export class MongoSystemError extends MongoError { + /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */ + reason?: TopologyDescription; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, reason: TopologyDescription) { + if (reason && reason.error) { + super(MongoError.buildErrorMessage(reason.error.message || reason.error), { + cause: reason.error + }); + } else { + super(message); + } + + if (reason) { + this.reason = reason; + } + + this.code = reason.error?.code; + } + + override get name(): string { + return 'MongoSystemError'; + } +} + +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +export class MongoServerSelectionError extends MongoSystemError { + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: string, reason: TopologyDescription) { + super(message, reason); + } + + override get name(): string { + return 'MongoServerSelectionError'; + } +} + +function makeWriteConcernResultObject(input: any) { + const output = Object.assign({}, input); + + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + + return output; +} + +/** + * An error thrown when the server reports a writeConcernError + * @public + * @category Error + */ +export class MongoWriteConcernError extends MongoServerError { + /** The result document (provided if ok: 1) */ + result?: Document; + + /** + * **Do not use this constructor!** + * + * Meant for internal use only. + * + * @remarks + * This class is only meant to be constructed within the driver. This constructor is + * not subject to semantic versioning compatibility guarantees and may change at any time. + * + * @public + **/ + constructor(message: ErrorDescription, result?: Document) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + + super(message); + this.errInfo = message.errInfo; + + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + + override get name(): string { + return 'MongoWriteConcernError'; + } +} + +// https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst#retryable-error +const RETRYABLE_READ_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.HostUnreachable, + MONGODB_ERROR_CODES.HostNotFound, + MONGODB_ERROR_CODES.NetworkTimeout, + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.SocketException, + MONGODB_ERROR_CODES.NotWritablePrimary, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + MONGODB_ERROR_CODES.ExceededTimeLimit +]); + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES; + +export function needsRetryableWriteLabel(error: Error, maxWireVersion: number): boolean { + // pre-4.4 server, then the driver adds an error label for every valid case + // execute operation will only inspect the label, code/message logic is handled here + if (error instanceof MongoNetworkError) { + return true; + } + + if (error instanceof MongoError) { + if ( + (maxWireVersion >= 9 || isRetryableWriteError(error)) && + !error.hasErrorLabel(MongoErrorLabel.HandshakeError) + ) { + // If we already have the error label no need to add it again. 4.4+ servers add the label. + // In the case where we have a handshake error, need to fall down to the logic checking + // the codes. + return false; + } + } + + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has(error.result?.code ?? error.code ?? 0); + } + + if (error instanceof MongoError && typeof error.code === 'number') { + return RETRYABLE_WRITE_ERROR_CODES.has(error.code); + } + + const isNotWritablePrimaryError = LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + + const isNodeIsRecoveringError = NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + + return false; +} + +export function isRetryableWriteError(error: MongoError): boolean { + return ( + error.hasErrorLabel(MongoErrorLabel.RetryableWriteError) || + error.hasErrorLabel(MongoErrorLabel.PoolRequstedRetry) + ); +} + +/** Determines whether an error is something the driver should attempt to retry */ +export function isRetryableReadError(error: MongoError): boolean { + const hasRetryableErrorCode = + typeof error.code === 'number' ? RETRYABLE_READ_ERROR_CODES.has(error.code) : false; + if (hasRetryableErrorCode) { + return true; + } + + if (error instanceof MongoNetworkError) { + return true; + } + + const isNotWritablePrimaryError = LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message); + if (isNotWritablePrimaryError) { + return true; + } + + const isNodeIsRecoveringError = NODE_IS_RECOVERING_ERROR_MESSAGE.test(error.message); + if (isNodeIsRecoveringError) { + return true; + } + + return false; +} + +const SDAM_RECOVERING_CODES = new Set([ + MONGODB_ERROR_CODES.ShutdownInProgress, + MONGODB_ERROR_CODES.PrimarySteppedDown, + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); + +const SDAM_NOT_PRIMARY_CODES = new Set([ + MONGODB_ERROR_CODES.NotWritablePrimary, + MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + MONGODB_ERROR_CODES.LegacyNotPrimary +]); + +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + MONGODB_ERROR_CODES.InterruptedAtShutdown, + MONGODB_ERROR_CODES.ShutdownInProgress +]); + +function isRecoveringError(err: MongoError) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + + return ( + LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || + NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message) + ); +} + +function isNotWritablePrimaryError(err: MongoError) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOT_PRIMARY_CODES.has(err.code); + } + + if (isRecoveringError(err)) { + return false; + } + + return LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); +} + +export function isNodeShuttingDownError(err: MongoError): boolean { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} + +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +export function isSDAMUnrecoverableError(error: MongoError): boolean { + // NOTE: null check is here for a strictly pre-CMAP world, a timeout or + // close event are considered unrecoverable + if (error instanceof MongoParseError || error == null) { + return true; + } + + return isRecoveringError(error) || isNotWritablePrimaryError(error); +} + +export function isNetworkTimeoutError(err: MongoError): err is MongoNetworkError { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} + +export function isResumableError(error?: Error, wireVersion?: number): boolean { + if (error == null || !(error instanceof MongoError)) { + return false; + } + + if (error instanceof MongoNetworkError) { + return true; + } + + if (wireVersion != null && wireVersion >= 9) { + // DRIVERS-1308: For 4.4 drivers running against 4.4 servers, drivers will add a special case to treat the CursorNotFound error code as resumable + if (error.code === MONGODB_ERROR_CODES.CursorNotFound) { + return true; + } + return error.hasErrorLabel(MongoErrorLabel.ResumableChangeStreamError); + } + + if (typeof error.code === 'number') { + return GET_MORE_RESUMABLE_CODES.has(error.code); + } + + return false; +} diff --git a/nodejs/node_modules/mongodb/src/explain.ts b/nodejs/node_modules/mongodb/src/explain.ts new file mode 100644 index 00000000..0d08e694 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/explain.ts @@ -0,0 +1,52 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export const ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +} as const); + +/** @public */ +export type ExplainVerbosity = string; + +/** + * For backwards compatibility, true is interpreted as "allPlansExecution" + * and false as "queryPlanner". Prior to server version 3.6, aggregate() + * ignores the verbosity parameter and executes in "queryPlanner". + * @public + */ +export type ExplainVerbosityLike = ExplainVerbosity | boolean; + +/** @public */ +export interface ExplainOptions { + /** Specifies the verbosity mode for the explain output. */ + explain?: ExplainVerbosityLike; +} + +/** @internal */ +export class Explain { + verbosity: ExplainVerbosity; + + constructor(verbosity: ExplainVerbosityLike) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? ExplainVerbosity.allPlansExecution + : ExplainVerbosity.queryPlanner; + } else { + this.verbosity = verbosity; + } + } + + static fromOptions(options?: ExplainOptions): Explain | undefined { + if (options?.explain == null) return; + + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); + } + + throw new MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} diff --git a/nodejs/node_modules/mongodb/src/gridfs/download.ts b/nodejs/node_modules/mongodb/src/gridfs/download.ts new file mode 100644 index 00000000..dc2cbfd9 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/gridfs/download.ts @@ -0,0 +1,436 @@ +import { Readable } from 'stream'; + +import type { Document, ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import type { FindCursor } from '../cursor/find_cursor'; +import { + MongoGridFSChunkError, + MongoGridFSStreamError, + MongoInvalidArgumentError, + MongoRuntimeError +} from '../error'; +import type { FindOptions } from '../operations/find'; +import type { ReadPreference } from '../read_preference'; +import type { Sort } from '../sort'; +import type { Callback } from '../utils'; +import type { GridFSChunk } from './upload'; + +/** @public */ +export interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** + * 0-indexed non-negative byte offset from the beginning of the file + */ + start?: number; + /** + * 0-indexed non-negative byte offset to the end of the file contents + * to be returned by the stream. `end` is non-inclusive + */ + end?: number; +} + +/** @public */ +export interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions { + /** The revision number relative to the oldest file with the given filename. 0 + * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the + * newest. */ + revision?: number; +} + +/** @public */ +export interface GridFSFile { + _id: ObjectId; + length: number; + chunkSize: number; + filename: string; + metadata?: Document; + uploadDate: Date; + /** @deprecated Will be removed in the next major version. */ + contentType?: string; + /** @deprecated Will be removed in the next major version. */ + aliases?: string[]; +} + +/** @internal */ +export interface GridFSBucketReadStreamPrivate { + bytesRead: number; + bytesToTrim: number; + bytesToSkip: number; + chunks: Collection; + cursor?: FindCursor; + expected: number; + files: Collection; + filter: Document; + init: boolean; + expectedEnd: number; + file?: GridFSFile; + options: { + sort?: Sort; + skip?: number; + start: number; + end: number; + }; + readPreference?: ReadPreference; +} + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +export class GridFSBucketReadStream extends Readable { + /** @internal */ + s: GridFSBucketReadStreamPrivate; + + /** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ + static readonly FILE = 'file' as const; + + /** + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + * @internal + */ + constructor( + chunks: Collection, + files: Collection, + readPreference: ReadPreference | undefined, + filter: Document, + options?: GridFSBucketReadStreamOptions + ) { + super({ emitClose: true }); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + override _read(): void { + if (this.destroyed) return; + waitForFile(this, () => doRead(this)); + } + + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0): this { + throwIfInitialized(this); + this.s.options.start = start; + return this; + } + + /** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0): this { + throwIfInitialized(this); + this.s.options.end = end; + return this; + } + + /** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + */ + async abort(): Promise { + this.push(null); + this.destroy(); + await this.s.cursor?.close(); + } +} + +function throwIfInitialized(stream: GridFSBucketReadStream): void { + if (stream.s.init) { + throw new MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} + +function doRead(stream: GridFSBucketReadStream): void { + if (stream.destroyed) return; + if (!stream.s.cursor) return; + if (!stream.s.file) return; + + const handleReadResult = ({ + error, + doc + }: { error: Error; doc: null } | { error: null; doc: any }) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.destroy(error); + return; + } + if (!doc) { + stream.push(null); + + stream.s.cursor?.close().then( + () => null, + error => stream.destroy(error) + ); + return; + } + + if (!stream.s.file) return; + + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.destroy( + new MongoGridFSChunkError( + `ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}` + ) + ); + } + + if (doc.n < expectedN) { + return stream.destroy( + new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`) + ); + } + + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.destroy( + new MongoGridFSChunkError( + `ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes` + ) + ); + } + + return stream.destroy( + new MongoGridFSChunkError( + `ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}` + ) + ); + } + + stream.s.bytesRead += buf.byteLength; + + if (buf.byteLength === 0) { + return stream.push(null); + } + + let sliceStart = null; + let sliceEnd = null; + + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; + } + + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; + } else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); + } + + stream.push(buf); + return; + }; + + stream.s.cursor.next().then( + doc => handleReadResult({ error: null, doc }), + error => handleReadResult({ error, doc: null }) + ); +} + +function init(stream: GridFSBucketReadStream): void { + const findOneOptions: FindOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + + const handleReadResult = ({ + error, + doc + }: { error: Error; doc: null } | { error: null; doc: any }) => { + if (error) { + return stream.destroy(error); + } + + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.destroy(err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; + } + + if (stream.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + stream.destroy(); + return; + } + + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } catch (error) { + return stream.destroy(error); + } + + const filter: Document = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.readPreference); + } + + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc as GridFSFile; + + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); + } catch (error) { + return stream.destroy(error); + } + + stream.emit(GridFSBucketReadStream.FILE, doc); + return; + }; + + stream.s.files.findOne(stream.s.filter, findOneOptions).then( + doc => handleReadResult({ error: null, doc }), + error => handleReadResult({ error, doc: null }) + ); +} + +function waitForFile(stream: GridFSBucketReadStream, callback: Callback): void { + if (stream.s.file) { + return callback(); + } + + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + + stream.once('file', () => { + callback(); + }); +} + +function handleStartOption( + stream: GridFSBucketReadStream, + doc: Document, + options: GridFSBucketReadStreamOptions +): number { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new MongoInvalidArgumentError( + `Stream start (${options.start}) must not be more than the length of the file (${doc.length})` + ); + } + if (options.start < 0) { + throw new MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); + } + if (options.end != null && options.end < options.start) { + throw new MongoInvalidArgumentError( + `Stream start (${options.start}) must not be greater than stream end (${options.end})` + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } + throw new MongoInvalidArgumentError('Start option must be defined'); +} + +function handleEndOption( + stream: GridFSBucketReadStream, + doc: Document, + cursor: FindCursor, + options: GridFSBucketReadStreamOptions +) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new MongoInvalidArgumentError( + `Stream end (${options.end}) must not be more than the length of the file (${doc.length})` + ); + } + if (options.start == null || options.start < 0) { + throw new MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + + const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } + throw new MongoInvalidArgumentError('End option must be defined'); +} diff --git a/nodejs/node_modules/mongodb/src/gridfs/index.ts b/nodejs/node_modules/mongodb/src/gridfs/index.ts new file mode 100644 index 00000000..c7611c85 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/gridfs/index.ts @@ -0,0 +1,213 @@ +import type { ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import type { FindCursor } from '../cursor/find_cursor'; +import type { Db } from '../db'; +import { MongoRuntimeError } from '../error'; +import { type Filter, TypedEventEmitter } from '../mongo_types'; +import type { ReadPreference } from '../read_preference'; +import type { Sort } from '../sort'; +import { WriteConcern, type WriteConcernOptions } from '../write_concern'; +import type { FindOptions } from './../operations/find'; +import { + GridFSBucketReadStream, + type GridFSBucketReadStreamOptions, + type GridFSBucketReadStreamOptionsWithRevision, + type GridFSFile +} from './download'; +import { + GridFSBucketWriteStream, + type GridFSBucketWriteStreamOptions, + type GridFSChunk +} from './upload'; + +const DEFAULT_GRIDFS_BUCKET_OPTIONS: { + bucketName: string; + chunkSizeBytes: number; +} = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +/** @public */ +export interface GridFSBucketOptions extends WriteConcernOptions { + /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */ + bucketName?: string; + /** Number of bytes stored in each chunk. Defaults to 255KB */ + chunkSizeBytes?: number; + /** Read preference to be passed to read operations */ + readPreference?: ReadPreference; +} + +/** @internal */ +export interface GridFSBucketPrivate { + db: Db; + options: { + bucketName: string; + chunkSizeBytes: number; + readPreference?: ReadPreference; + writeConcern: WriteConcern | undefined; + }; + _chunksCollection: Collection; + _filesCollection: Collection; + checkedIndexes: boolean; + calledOpenUploadStream: boolean; +} + +/** @public */ +export type GridFSBucketEvents = { + index(): void; +}; + +/** + * Constructor for a streaming GridFS interface + * @public + */ +export class GridFSBucket extends TypedEventEmitter { + /** @internal */ + s: GridFSBucketPrivate; + + /** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * @event + */ + static readonly INDEX = 'index' as const; + + constructor(db: Db, options?: GridFSBucketOptions) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + + openUploadStream( + filename: string, + options?: GridFSBucketWriteStreamOptions + ): GridFSBucketWriteStream { + return new GridFSBucketWriteStream(this, filename, options); + } + + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + */ + openUploadStreamWithId( + id: ObjectId, + filename: string, + options?: GridFSBucketWriteStreamOptions + ): GridFSBucketWriteStream { + return new GridFSBucketWriteStream(this, filename, { ...options, id }); + } + + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream( + id: ObjectId, + options?: GridFSBucketReadStreamOptions + ): GridFSBucketReadStream { + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + { _id: id }, + options + ); + } + + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + async delete(id: ObjectId): Promise { + const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }); + + // Delete orphaned chunks before returning FileNotFound + await this.s._chunksCollection.deleteMany({ files_id: id }); + + if (deletedCount === 0) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + throw new MongoRuntimeError(`File not found for id ${id}`); + } + } + + /** Convenience wrapper around find on the files collection */ + find(filter: Filter = {}, options: FindOptions = {}): FindCursor { + return this.s._filesCollection.find(filter, options); + } + + /** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + */ + openDownloadStreamByName( + filename: string, + options?: GridFSBucketReadStreamOptionsWithRevision + ): GridFSBucketReadStream { + let sort: Sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + { filename }, + { ...options, sort, skip } + ); + } + + /** + * Renames the file with the given _id to the given string + * + * @param id - the id of the file to rename + * @param filename - new name for the file + */ + async rename(id: ObjectId, filename: string): Promise { + const filter = { _id: id }; + const update = { $set: { filename } }; + const { matchedCount } = await this.s._filesCollection.updateOne(filter, update); + if (matchedCount === 0) { + throw new MongoRuntimeError(`File with id ${id} not found`); + } + } + + /** Removes this bucket's files collection, followed by its chunks collection. */ + async drop(): Promise { + await this.s._filesCollection.drop(); + await this.s._chunksCollection.drop(); + } +} diff --git a/nodejs/node_modules/mongodb/src/gridfs/upload.ts b/nodejs/node_modules/mongodb/src/gridfs/upload.ts new file mode 100644 index 00000000..2f3ad9c1 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/gridfs/upload.ts @@ -0,0 +1,453 @@ +import { Writable } from 'stream'; + +import type { Document } from '../bson'; +import { ObjectId } from '../bson'; +import type { Collection } from '../collection'; +import { MongoAPIError, MONGODB_ERROR_CODES, MongoError } from '../error'; +import type { Callback } from '../utils'; +import type { WriteConcernOptions } from '../write_concern'; +import { WriteConcern } from './../write_concern'; +import type { GridFSFile } from './download'; +import type { GridFSBucket } from './index'; + +/** @public */ +export interface GridFSChunk { + _id: ObjectId; + files_id: ObjectId; + n: number; + data: Buffer | Uint8Array; +} + +/** @public */ +export interface GridFSBucketWriteStreamOptions extends WriteConcernOptions { + /** Overwrite this bucket's chunkSizeBytes for this file */ + chunkSizeBytes?: number; + /** Custom file id for the GridFS file. */ + id?: ObjectId; + /** Object to store in the file document's `metadata` field */ + metadata?: Document; + /** + * String to store in the file document's `contentType` field. + * @deprecated Will be removed in the next major version. Add a contentType field to the metadata document instead. + */ + contentType?: string; + /** + * Array of strings to store in the file document's `aliases` field. + * @deprecated Will be removed in the next major version. Add an aliases field to the metadata document instead. + */ + aliases?: string[]; +} + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +export class GridFSBucketWriteStream extends Writable { + bucket: GridFSBucket; + /** A Collection instance where the file's chunks are stored */ + chunks: Collection; + /** A Collection instance where the file's GridFSFile document is stored */ + files: Collection; + /** The name of the file */ + filename: string; + /** Options controlling the metadata inserted along with the file */ + options: GridFSBucketWriteStreamOptions; + /** Indicates the stream is finished uploading */ + done: boolean; + /** The ObjectId used for the `_id` field on the GridFSFile document */ + id: ObjectId; + /** The number of bytes that each chunk will be limited to */ + chunkSizeBytes: number; + /** Space used to store a chunk currently being inserted */ + bufToStore: Buffer; + /** Accumulates the number of bytes inserted as the stream uploads chunks */ + length: number; + /** Accumulates the number of chunks inserted as the stream uploads file contents */ + n: number; + /** Tracks the current offset into the buffered bytes being uploaded */ + pos: number; + /** Contains a number of properties indicating the current state of the stream */ + state: { + /** If set the stream has ended */ + streamEnd: boolean; + /** Indicates the number of chunks that still need to be inserted to exhaust the current buffered data */ + outstandingRequests: number; + /** If set an error occurred during insertion */ + errored: boolean; + /** If set the stream was intentionally aborted */ + aborted: boolean; + }; + /** The write concern setting to be used with every insert operation */ + writeConcern?: WriteConcern; + /** + * The document containing information about the inserted file. + * This property is defined _after_ the finish event has been emitted. + * It will remain `null` if an error occurs. + * + * @example + * ```ts + * fs.createReadStream('file.txt') + * .pipe(bucket.openUploadStream('file.txt')) + * .on('finish', function () { + * console.log(this.gridFSFile) + * }) + * ``` + */ + gridFSFile: GridFSFile | null = null; + + /** + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + * @internal + */ + constructor(bucket: GridFSBucket, filename: string, options?: GridFSBucketWriteStreamOptions) { + super(); + + options = options ?? {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : new ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + checkIndexes(this).then( + () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }, + () => null + ); + } + } + + /** + * @internal + * + * The stream is considered constructed when the indexes are done being created + */ + override _construct(callback: (error?: Error | null) => void): void { + if (this.bucket.s.checkedIndexes) { + return process.nextTick(callback); + } + this.bucket.once('index', callback); + } + + /** + * @internal + * Write a buffer to the stream. + * + * @param chunk - Buffer to write + * @param encoding - Optional encoding for the buffer + * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + */ + override _write( + chunk: Buffer | string, + encoding: BufferEncoding, + callback: Callback + ): void { + doWrite(this, chunk, encoding, callback); + } + + /** @internal */ + override _final(callback: (error?: Error | null) => void): void { + if (this.state.streamEnd) { + return process.nextTick(callback); + } + this.state.streamEnd = true; + writeRemnant(this, callback); + } + + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + async abort(): Promise { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new MongoAPIError('Cannot abort a stream that has already completed'); + } + + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new MongoAPIError('Cannot call abort() on a stream twice'); + } + + this.state.aborted = true; + await this.chunks.deleteMany({ files_id: this.id }); + } +} + +function handleError(stream: GridFSBucketWriteStream, error: Error, callback: Callback): void { + if (stream.state.errored) { + process.nextTick(callback); + return; + } + stream.state.errored = true; + process.nextTick(callback, error); +} + +function createChunkDoc(filesId: ObjectId, n: number, data: Buffer): GridFSChunk { + return { + _id: new ObjectId(), + files_id: filesId, + n, + data + }; +} + +async function checkChunksIndex(stream: GridFSBucketWriteStream): Promise { + const index = { files_id: 1, n: 1 }; + + let indexes; + try { + indexes = await stream.chunks.listIndexes().toArray(); + } catch (error) { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } else { + throw error; + } + } + + const hasChunksIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + return true; + } + return false; + }); + + if (!hasChunksIndex) { + await stream.chunks.createIndex(index, { + ...stream.writeConcern, + background: true, + unique: true + }); + } +} + +function checkDone(stream: GridFSBucketWriteStream, callback: Callback): void { + if (stream.done) { + return process.nextTick(callback); + } + + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const gridFSFile = createFilesDoc( + stream.id, + stream.length, + stream.chunkSizeBytes, + stream.filename, + stream.options.contentType, + stream.options.aliases, + stream.options.metadata + ); + + if (isAborted(stream, callback)) { + return; + } + + stream.files.insertOne(gridFSFile, { writeConcern: stream.writeConcern }).then( + () => { + stream.gridFSFile = gridFSFile; + callback(); + }, + error => handleError(stream, error, callback) + ); + return; + } + + process.nextTick(callback); +} + +async function checkIndexes(stream: GridFSBucketWriteStream): Promise { + const doc = await stream.files.findOne({}, { projection: { _id: 1 } }); + if (doc != null) { + // If at least one document exists assume the collection has the required index + return; + } + + const index = { filename: 1, uploadDate: 1 }; + + let indexes; + try { + indexes = await stream.files.listIndexes().toArray(); + } catch (error) { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } else { + throw error; + } + } + + const hasFileIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + return true; + } + return false; + }); + + if (!hasFileIndex) { + await stream.files.createIndex(index, { background: false }); + } + + await checkChunksIndex(stream); +} + +function createFilesDoc( + _id: ObjectId, + length: number, + chunkSize: number, + filename: string, + contentType?: string, + aliases?: string[], + metadata?: Document +): GridFSFile { + const ret: GridFSFile = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +function doWrite( + stream: GridFSBucketWriteStream, + chunk: Buffer | string, + encoding: BufferEncoding, + callback: Callback +): void { + if (isAborted(stream, callback)) { + return; + } + + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + stream.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.pos += inputBuf.length; + process.nextTick(callback); + return; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + let inputBufRemaining = inputBuf.length; + let spaceRemaining: number = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc: GridFSChunk; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + + if (isAborted(stream, callback)) { + return; + } + + stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then( + () => { + --stream.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + checkDone(stream, callback); + } + }, + error => handleError(stream, error, callback) + ); + + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } +} + +function writeRemnant(stream: GridFSBucketWriteStream, callback: Callback): void { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + + ++stream.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + + // If the stream was aborted, do not write remnant + if (isAborted(stream, callback)) { + return; + } + + stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then( + () => { + --stream.state.outstandingRequests; + checkDone(stream, callback); + }, + error => handleError(stream, error, callback) + ); +} + +function isAborted(stream: GridFSBucketWriteStream, callback: Callback): boolean { + if (stream.state.aborted) { + process.nextTick(callback, new MongoAPIError('Stream has been aborted')); + return true; + } + return false; +} diff --git a/nodejs/node_modules/mongodb/src/index.ts b/nodejs/node_modules/mongodb/src/index.ts new file mode 100644 index 00000000..fa88e463 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/index.ts @@ -0,0 +1,557 @@ +import { Admin } from './admin'; +import { OrderedBulkOperation } from './bulk/ordered'; +import { UnorderedBulkOperation } from './bulk/unordered'; +import { ChangeStream } from './change_stream'; +import { Collection } from './collection'; +import { AbstractCursor } from './cursor/abstract_cursor'; +import { AggregationCursor } from './cursor/aggregation_cursor'; +import { FindCursor } from './cursor/find_cursor'; +import { ListCollectionsCursor } from './cursor/list_collections_cursor'; +import { ListIndexesCursor } from './cursor/list_indexes_cursor'; +import type { RunCommandCursor } from './cursor/run_command_cursor'; +import { Db } from './db'; +import { GridFSBucket } from './gridfs'; +import { GridFSBucketReadStream } from './gridfs/download'; +import { GridFSBucketWriteStream } from './gridfs/upload'; +import { MongoClient } from './mongo_client'; +import { CancellationToken } from './mongo_types'; +import { ClientSession } from './sessions'; + +/** @public */ +export { BSON } from './bson'; +export { + Binary, + BSONRegExp, + BSONSymbol, + BSONType, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + Timestamp, + UUID +} from './bson'; +export { AnyBulkWriteOperation, BulkWriteOptions, MongoBulkWriteError } from './bulk/common'; +export { ClientEncryption } from './client-side-encryption/client_encryption'; +export { ChangeStreamCursor } from './cursor/change_stream_cursor'; +export { + MongoAPIError, + MongoAWSError, + MongoAzureError, + MongoBatchReExecutionError, + MongoChangeStreamError, + MongoCompatibilityError, + MongoCursorExhaustedError, + MongoCursorInUseError, + MongoDecompressionError, + MongoDriverError, + MongoError, + MongoExpiredSessionError, + MongoGridFSChunkError, + MongoGridFSStreamError, + MongoInvalidArgumentError, + MongoKerberosError, + MongoMissingCredentialsError, + MongoMissingDependencyError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoParseError, + MongoRuntimeError, + MongoServerClosedError, + MongoServerError, + MongoServerSelectionError, + MongoSystemError, + MongoTailableCursorError, + MongoTopologyClosedError, + MongoTransactionError, + MongoUnexpectedServerResponseError, + MongoWriteConcernError +} from './error'; +export { + AbstractCursor, + // Actual driver classes exported + Admin, + AggregationCursor, + CancellationToken, + ChangeStream, + ClientSession, + Collection, + Db, + FindCursor, + GridFSBucket, + GridFSBucketReadStream, + GridFSBucketWriteStream, + ListCollectionsCursor, + ListIndexesCursor, + MongoClient, + OrderedBulkOperation, + RunCommandCursor, + UnorderedBulkOperation +}; + +// enums +export { BatchType } from './bulk/common'; +export { AutoEncryptionLoggerLevel } from './client-side-encryption/auto_encrypter'; +export { GSSAPICanonicalizationValue } from './cmap/auth/gssapi'; +export { AuthMechanism } from './cmap/auth/providers'; +export { Compressor } from './cmap/wire_protocol/compression'; +export { CURSOR_FLAGS } from './cursor/abstract_cursor'; +export { MongoErrorLabel } from './error'; +export { ExplainVerbosity } from './explain'; +export { ServerApiVersion } from './mongo_client'; +export { ReturnDocument } from './operations/find_and_modify'; +export { ProfilingLevel } from './operations/set_profiling_level'; +export { ReadConcernLevel } from './read_concern'; +export { ReadPreferenceMode } from './read_preference'; +export { ServerType, TopologyType } from './sdam/common'; + +// Helper classes +export { ReadConcern } from './read_concern'; +export { ReadPreference } from './read_preference'; +export { WriteConcern } from './write_concern'; + +// events +export { + CommandFailedEvent, + CommandStartedEvent, + CommandSucceededEvent +} from './cmap/command_monitoring_events'; +export { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolMonitoringEvent, + ConnectionPoolReadyEvent, + ConnectionReadyEvent +} from './cmap/connection_pool_events'; +export { + ServerClosedEvent, + ServerDescriptionChangedEvent, + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent +} from './sdam/events'; +export { + ServerSelectionEvent, + ServerSelectionFailedEvent, + ServerSelectionStartedEvent, + ServerSelectionSucceededEvent, + WaitingForSuitableServerEvent +} from './sdam/server_selection_events'; +export { SrvPollingEvent } from './sdam/srv_polling'; + +// type only exports below, these are removed from emitted JS +export type { AdminPrivate } from './admin'; +export type { BSONSerializeOptions, Document } from './bson'; +export type { deserialize, serialize } from './bson'; +export type { + BulkResult, + BulkWriteOperationError, + BulkWriteResult, + DeleteManyModel, + DeleteOneModel, + InsertOneModel, + ReplaceOneModel, + UpdateManyModel, + UpdateOneModel, + WriteConcernError, + WriteError +} from './bulk/common'; +export type { + Batch, + BulkOperationBase, + BulkOperationPrivate, + FindOperators, + WriteConcernErrorData +} from './bulk/common'; +export type { + ChangeStreamCollModDocument, + ChangeStreamCreateDocument, + ChangeStreamCreateIndexDocument, + ChangeStreamDeleteDocument, + ChangeStreamDocument, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentOperationDescription, + ChangeStreamDropDatabaseDocument, + ChangeStreamDropDocument, + ChangeStreamDropIndexDocument, + ChangeStreamEvents, + ChangeStreamInsertDocument, + ChangeStreamInvalidateDocument, + ChangeStreamNameSpace, + ChangeStreamOptions, + ChangeStreamRefineCollectionShardKeyDocument, + ChangeStreamRenameDocument, + ChangeStreamReplaceDocument, + ChangeStreamReshardCollectionDocument, + ChangeStreamShardCollectionDocument, + ChangeStreamSplitEvent, + ChangeStreamUpdateDocument, + OperationTime, + ResumeOptions, + ResumeToken, + UpdateDescription +} from './change_stream'; +export type { AutoEncrypter } from './client-side-encryption/auto_encrypter'; +export type { AutoEncryptionOptions } from './client-side-encryption/auto_encrypter'; +export type { AutoEncryptionExtraOptions } from './client-side-encryption/auto_encrypter'; +export type { + AWSEncryptionKeyOptions, + AzureEncryptionKeyOptions, + ClientEncryptionCreateDataKeyProviderOptions, + ClientEncryptionEncryptOptions, + ClientEncryptionOptions, + ClientEncryptionRewrapManyDataKeyProviderOptions, + ClientEncryptionRewrapManyDataKeyResult, + DataKey, + GCPEncryptionKeyOptions, + RangeOptions +} from './client-side-encryption/client_encryption'; +export { + MongoCryptAzureKMSRequestError, + MongoCryptCreateDataKeyError, + MongoCryptCreateEncryptedCollectionError, + MongoCryptError, + MongoCryptInvalidArgumentError, + MongoCryptKMSRequestNetworkTimeoutError +} from './client-side-encryption/errors'; +export type { MongocryptdManager } from './client-side-encryption/mongocryptd_manager'; +export type { + ClientEncryptionDataKeyProvider, + KMSProviders +} from './client-side-encryption/providers/index'; +export type { + ClientEncryptionTlsOptions, + CSFLEKMSTlsOptions, + StateMachineExecutable +} from './client-side-encryption/state_machine'; +export type { AuthContext, AuthProvider } from './cmap/auth/auth_provider'; +export type { + AuthMechanismProperties, + MongoCredentials, + MongoCredentialsOptions +} from './cmap/auth/mongo_credentials'; +export type { + IdPServerInfo, + IdPServerResponse, + OIDCCallbackContext, + OIDCRefreshFunction, + OIDCRequestFunction +} from './cmap/auth/mongodb_oidc'; +export type { + MessageHeader, + OpCompressedRequest, + OpMsgOptions, + OpMsgRequest, + OpMsgResponse, + OpQueryOptions, + OpQueryRequest, + OpQueryResponse, + OpResponseOptions, + WriteProtocolMessageType +} from './cmap/commands'; +export type { HandshakeDocument } from './cmap/connect'; +export type { LEGAL_TCP_SOCKET_OPTIONS, LEGAL_TLS_SOCKET_OPTIONS, Stream } from './cmap/connect'; +export type { + CommandOptions, + Connection, + ConnectionEvents, + ConnectionOptions, + ProxyOptions +} from './cmap/connection'; +export type { + CloseOptions, + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions, + PoolState, + WaitQueueMember, + WithConnectionCallback +} from './cmap/connection_pool'; +export type { ClientMetadata, ClientMetadataOptions } from './cmap/handshake/client_metadata'; +export type { ConnectionPoolMetrics } from './cmap/metrics'; +export type { StreamDescription, StreamDescriptionOptions } from './cmap/stream_description'; +export type { CompressorName } from './cmap/wire_protocol/compression'; +export type { CollectionOptions, CollectionPrivate, ModifyResult } from './collection'; +export type { + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_READY, + MONGO_CLIENT_EVENTS, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + SERVER_HEARTBEAT_FAILED, + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_OPENING, + SERVER_SELECTION_FAILED, + SERVER_SELECTION_STARTED, + SERVER_SELECTION_SUCCEEDED, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING, + WAITING_FOR_SUITABLE_SERVER +} from './constants'; +export type { + AbstractCursorEvents, + AbstractCursorOptions, + CursorFlag, + CursorStreamOptions +} from './cursor/abstract_cursor'; +export type { InternalAbstractCursorOptions } from './cursor/abstract_cursor'; +export type { AggregationCursorOptions } from './cursor/aggregation_cursor'; +export type { + ChangeStreamAggregateRawResult, + ChangeStreamCursorOptions +} from './cursor/change_stream_cursor'; +export type { + ListSearchIndexesCursor, + ListSearchIndexesOptions +} from './cursor/list_search_indexes_cursor'; +export type { RunCursorCommandOptions } from './cursor/run_command_cursor'; +export type { DbOptions, DbPrivate } from './db'; +export type { Encrypter, EncrypterOptions } from './encrypter'; +export type { AnyError, ErrorDescription, MongoNetworkErrorOptions } from './error'; +export type { Explain, ExplainOptions, ExplainVerbosityLike } from './explain'; +export type { + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSBucketReadStreamPrivate, + GridFSFile +} from './gridfs/download'; +export type { GridFSBucketEvents, GridFSBucketOptions, GridFSBucketPrivate } from './gridfs/index'; +export type { GridFSBucketWriteStreamOptions, GridFSChunk } from './gridfs/upload'; +export type { + Auth, + DriverInfo, + MongoClientEvents, + MongoClientOptions, + MongoClientPrivate, + MongoOptions, + PkFactory, + ServerApi, + SupportedNodeConnectionOptions, + SupportedSocketOptions, + SupportedTLSConnectionOptions, + SupportedTLSSocketOptions, + WithSessionCallback +} from './mongo_client'; +export { MongoClientAuthProviders } from './mongo_client_auth_providers'; +export type { + Log, + LogComponentSeveritiesClientOptions, + LogConvertible, + Loggable, + LoggableCommandFailedEvent, + LoggableCommandSucceededEvent, + LoggableEvent, + LoggableServerHeartbeatFailedEvent, + LoggableServerHeartbeatStartedEvent, + LoggableServerHeartbeatSucceededEvent, + MongoDBLogWritable, + MongoLoggableComponent, + MongoLogger, + MongoLoggerEnvOptions, + MongoLoggerMongoClientOptions, + MongoLoggerOptions, + SeverityLevel +} from './mongo_logger'; +export type { + CommonEvents, + EventsDescription, + GenericListener, + TypedEventEmitter +} from './mongo_types'; +export type { + AcceptedFields, + AddToSetOperators, + AlternativeType, + ArrayElement, + ArrayOperator, + BitwiseFilter, + BSONTypeAlias, + Condition, + EnhancedOmit, + Filter, + FilterOperations, + FilterOperators, + Flatten, + InferIdType, + IntegerType, + IsAny, + Join, + KeysOfAType, + KeysOfOtherType, + MatchKeysAndValues, + NestedPaths, + NestedPathsOfType, + NonObjectIdLikeDocument, + NotAcceptedFields, + NumericType, + OneOrMore, + OnlyFieldsOfType, + OptionalId, + OptionalUnlessRequiredId, + PropertyType, + PullAllOperator, + PullOperator, + PushOperator, + RegExpOrString, + RootFilterOperators, + SchemaMember, + SetFields, + StrictFilter, + StrictMatchKeysAndValues, + StrictUpdateFilter, + UpdateFilter, + WithId, + WithoutId +} from './mongo_types'; +export type { + AggregateOperation, + AggregateOptions, + DB_AGGREGATE_COLLECTION +} from './operations/aggregate'; +export type { + CollationOptions, + CommandOperation, + CommandOperationOptions, + OperationParent +} from './operations/command'; +export type { IndexInformationOptions } from './operations/common_functions'; +export type { CountOptions } from './operations/count'; +export type { CountDocumentsOptions } from './operations/count_documents'; +export type { + ClusteredCollectionOptions, + CreateCollectionOptions, + TimeSeriesCollectionOptions +} from './operations/create_collection'; +export type { DeleteOptions, DeleteResult, DeleteStatement } from './operations/delete'; +export type { DistinctOptions } from './operations/distinct'; +export type { DropCollectionOptions, DropDatabaseOptions } from './operations/drop'; +export type { EstimatedDocumentCountOptions } from './operations/estimated_document_count'; +export type { ExecutionResult } from './operations/execute_operation'; +export type { FindOptions } from './operations/find'; +export type { + FindOneAndDeleteOptions, + FindOneAndReplaceOptions, + FindOneAndUpdateOptions +} from './operations/find_and_modify'; +export type { + CreateIndexesOptions, + DropIndexesOptions, + IndexDescription, + IndexDirection, + IndexSpecification, + ListIndexesOptions +} from './operations/indexes'; +export type { InsertManyResult, InsertOneOptions, InsertOneResult } from './operations/insert'; +export type { CollectionInfo, ListCollectionsOptions } from './operations/list_collections'; +export type { ListDatabasesOptions, ListDatabasesResult } from './operations/list_databases'; +export type { AbstractOperation, Hint, OperationOptions } from './operations/operation'; +export type { ProfilingLevelOptions } from './operations/profiling_level'; +export type { RemoveUserOptions } from './operations/remove_user'; +export type { RenameOptions } from './operations/rename'; +export type { RunCommandOptions } from './operations/run_command'; +export type { SearchIndexDescription } from './operations/search_indexes/create'; +export type { SetProfilingLevelOptions } from './operations/set_profiling_level'; +export type { DbStatsOptions } from './operations/stats'; +export type { + ReplaceOptions, + UpdateOptions, + UpdateResult, + UpdateStatement +} from './operations/update'; +export type { ValidateCollectionOptions } from './operations/validate_collection'; +export type { ReadConcernLike } from './read_concern'; +export type { + HedgeOptions, + ReadPreferenceFromOptions, + ReadPreferenceLike, + ReadPreferenceLikeOptions, + ReadPreferenceOptions +} from './read_preference'; +export type { ClusterTime, TimerQueue } from './sdam/common'; +export type { + Monitor, + MonitorEvents, + MonitorInterval, + MonitorIntervalOptions, + MonitorOptions, + MonitorPrivate, + RTTPinger, + RTTPingerOptions, + ServerMonitoringMode +} from './sdam/monitor'; +export type { Server, ServerEvents, ServerOptions, ServerPrivate } from './sdam/server'; +export type { + ServerDescription, + ServerDescriptionOptions, + TagSet, + TopologyVersion +} from './sdam/server_description'; +export type { ServerSelector } from './sdam/server_selection'; +export type { SrvPoller, SrvPollerEvents, SrvPollerOptions } from './sdam/srv_polling'; +export type { + ConnectOptions, + SelectServerOptions, + ServerCapabilities, + ServerSelectionCallback, + ServerSelectionRequest, + Topology, + TopologyEvents, + TopologyOptions, + TopologyPrivate +} from './sdam/topology'; +export type { TopologyDescription, TopologyDescriptionOptions } from './sdam/topology_description'; +export type { + ClientSessionEvents, + ClientSessionOptions, + EndSessionOptions, + ServerSession, + ServerSessionId, + ServerSessionPool, + WithTransactionCallback +} from './sessions'; +export type { Sort, SortDirection, SortDirectionForCmd, SortForCmd } from './sort'; +export type { Transaction, TransactionOptions, TxnState } from './transactions'; +export type { + BufferPool, + Callback, + EventEmitterWithState, + HostAddress, + List, + MongoDBCollectionNamespace, + MongoDBNamespace, + TimeoutController +} from './utils'; +export type { W, WriteConcernOptions, WriteConcernSettings } from './write_concern'; diff --git a/nodejs/node_modules/mongodb/src/mongo_client.ts b/nodejs/node_modules/mongodb/src/mongo_client.ts new file mode 100644 index 00000000..f47558e4 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/mongo_client.ts @@ -0,0 +1,896 @@ +import { promises as fs } from 'fs'; +import type { TcpNetConnectOpts } from 'net'; +import type { ConnectionOptions as TLSConnectionOptions, TLSSocketOptions } from 'tls'; +import { promisify } from 'util'; + +import { type BSONSerializeOptions, type Document, resolveBSONOptions } from './bson'; +import { ChangeStream, type ChangeStreamDocument, type ChangeStreamOptions } from './change_stream'; +import type { AutoEncrypter, AutoEncryptionOptions } from './client-side-encryption/auto_encrypter'; +import { + type AuthMechanismProperties, + DEFAULT_ALLOWED_HOSTS, + type MongoCredentials +} from './cmap/auth/mongo_credentials'; +import { AuthMechanism } from './cmap/auth/providers'; +import type { LEGAL_TCP_SOCKET_OPTIONS, LEGAL_TLS_SOCKET_OPTIONS } from './cmap/connect'; +import type { Connection } from './cmap/connection'; +import type { ClientMetadata } from './cmap/handshake/client_metadata'; +import type { CompressorName } from './cmap/wire_protocol/compression'; +import { parseOptions, resolveSRVRecord } from './connection_string'; +import { MONGO_CLIENT_EVENTS } from './constants'; +import { Db, type DbOptions } from './db'; +import type { Encrypter } from './encrypter'; +import { MongoInvalidArgumentError } from './error'; +import { MongoClientAuthProviders } from './mongo_client_auth_providers'; +import { + type LogComponentSeveritiesClientOptions, + type MongoDBLogWritable, + MongoLogger, + type MongoLoggerOptions, + SeverityLevel +} from './mongo_logger'; +import { TypedEventEmitter } from './mongo_types'; +import { executeOperation } from './operations/execute_operation'; +import { RunAdminCommandOperation } from './operations/run_command'; +import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern'; +import { ReadPreference, type ReadPreferenceMode } from './read_preference'; +import type { ServerMonitoringMode } from './sdam/monitor'; +import type { TagSet } from './sdam/server_description'; +import { readPreferenceServerSelector } from './sdam/server_selection'; +import type { SrvPoller } from './sdam/srv_polling'; +import { Topology, type TopologyEvents } from './sdam/topology'; +import { ClientSession, type ClientSessionOptions, ServerSessionPool } from './sessions'; +import { + COSMOS_DB_CHECK, + COSMOS_DB_MSG, + DOCUMENT_DB_CHECK, + DOCUMENT_DB_MSG, + type HostAddress, + hostMatchesWildcards, + isHostMatch, + type MongoDBNamespace, + ns, + resolveOptions +} from './utils'; +import type { W, WriteConcern, WriteConcernSettings } from './write_concern'; + +/** @public */ +export const ServerApiVersion = Object.freeze({ + v1: '1' +} as const); + +/** @public */ +export type ServerApiVersion = (typeof ServerApiVersion)[keyof typeof ServerApiVersion]; + +/** @public */ +export interface ServerApi { + version: ServerApiVersion; + strict?: boolean; + deprecationErrors?: boolean; +} + +/** @public */ +export interface DriverInfo { + name?: string; + version?: string; + platform?: string; +} + +/** @public */ +export interface Auth { + /** The username for auth */ + username?: string; + /** The password for auth */ + password?: string; +} + +/** @public */ +export interface PkFactory { + createPk(): any; +} + +/** @public */ +export type SupportedTLSConnectionOptions = Pick< + TLSConnectionOptions, + Extract +>; + +/** @public */ +export type SupportedTLSSocketOptions = Pick< + TLSSocketOptions, + Extract +>; + +/** @public */ +export type SupportedSocketOptions = Pick< + TcpNetConnectOpts, + (typeof LEGAL_TCP_SOCKET_OPTIONS)[number] +>; + +/** @public */ +export type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & + SupportedTLSSocketOptions & + SupportedSocketOptions; + +/** + * Describes all possible URI query options for the mongo client + * @public + * @see https://www.mongodb.com/docs/manual/reference/connection-string + */ +export interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions { + /** Specifies the name of the replica set, if the mongod is a member of a replica set. */ + replicaSet?: string; + /** @internal This option is in development and currently has no behaviour. */ + timeoutMS?: number; + /** Enables or disables TLS/SSL for the connection. */ + tls?: boolean; + /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */ + ssl?: boolean; + /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key. */ + tlsCertificateKeyFile?: string; + /** Specifies the password to de-crypt the tlsCertificateKeyFile. */ + tlsCertificateKeyFilePassword?: string; + /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */ + tlsCAFile?: string; + /** Specifies the location of a local CRL .pem file that contains the client revokation list. */ + tlsCRLFile?: string; + /** Bypasses validation of the certificates presented by the mongod/mongos instance */ + tlsAllowInvalidCertificates?: boolean; + /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */ + tlsAllowInvalidHostnames?: boolean; + /** Disables various certificate validations. */ + tlsInsecure?: boolean; + /** The time in milliseconds to attempt a connection before timing out. */ + connectTimeoutMS?: number; + /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */ + socketTimeoutMS?: number; + /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */ + compressors?: CompressorName[] | string; + /** An integer that specifies the compression level if using zlib for network compression. */ + zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; + /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */ + srvMaxHosts?: number; + /** + * Modifies the srv URI to look like: + * + * `_{srvServiceName}._tcp.{hostname}.{domainname}` + * + * Querying this DNS URI is expected to respond with SRV records + */ + srvServiceName?: string; + /** The maximum number of connections in the connection pool. */ + maxPoolSize?: number; + /** The minimum number of connections in the connection pool. */ + minPoolSize?: number; + /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */ + maxConnecting?: number; + /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */ + maxIdleTimeMS?: number; + /** The maximum time in milliseconds that a thread can wait for a connection to become available. */ + waitQueueTimeoutMS?: number; + /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** The level of isolation */ + readConcernLevel?: ReadConcernLevel; + /** Specifies the read preferences for this connection */ + readPreference?: ReadPreferenceMode | ReadPreference; + /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */ + maxStalenessSeconds?: number; + /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */ + readPreferenceTags?: TagSet[]; + /** The auth settings for when connection to server. */ + auth?: Auth; + /** Specify the database name associated with the user’s credentials. */ + authSource?: string; + /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */ + authMechanism?: AuthMechanism; + /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */ + authMechanismProperties?: AuthMechanismProperties; + /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */ + localThresholdMS?: number; + /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */ + serverSelectionTimeoutMS?: number; + /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */ + heartbeatFrequencyMS?: number; + /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */ + minHeartbeatFrequencyMS?: number; + /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */ + appName?: string; + /** Enables retryable reads. */ + retryReads?: boolean; + /** Enable retryable writes. */ + retryWrites?: boolean; + /** Allow a driver to force a Single topology type with a connection string containing one host */ + directConnection?: boolean; + /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */ + loadBalanced?: boolean; + /** + * The write concern w value + * @deprecated Please use the `writeConcern` option instead + */ + w?: W; + /** + * The write concern timeout + * @deprecated Please use the `writeConcern` option instead + */ + wtimeoutMS?: number; + /** + * The journal write concern + * @deprecated Please use the `writeConcern` option instead + */ + journal?: boolean; + /** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * + * @see https://www.mongodb.com/docs/manual/reference/write-concern/ + */ + writeConcern?: WriteConcern | WriteConcernSettings; + /** TCP Connection no delay */ + noDelay?: boolean; + /** Force server to assign `_id` values instead of driver */ + forceServerObjectId?: boolean; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable in-use auto encryption + * + * @remarks + * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error + * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. + * + * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections). + * + * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: + * - AutoEncryptionOptions.keyVaultClient is not passed. + * - AutoEncryptionOptions.bypassAutomaticEncryption is false. + * + * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. + */ + autoEncryption?: AutoEncryptionOptions; + /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */ + driverInfo?: DriverInfo; + /** Configures a Socks5 proxy host used for creating TCP connections. */ + proxyHost?: string; + /** Configures a Socks5 proxy port used for creating TCP connections. */ + proxyPort?: number; + /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */ + proxyUsername?: string; + /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */ + proxyPassword?: string; + /** Instructs the driver monitors to use a specific monitoring mode */ + serverMonitoringMode?: ServerMonitoringMode; + + /** @internal */ + srvPoller?: SrvPoller; + /** @internal */ + connectionType?: typeof Connection; + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogPath?: 'stderr' | 'stdout' | MongoDBLogWritable; + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogComponentSeverities?: LogComponentSeveritiesClientOptions; + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogMaxDocumentLength?: number; + + /** @internal */ + [featureFlag: symbol]: any; +} + +/** @public */ +export type WithSessionCallback = (session: ClientSession) => Promise; + +/** @internal */ +export interface MongoClientPrivate { + url: string; + bsonOptions: BSONSerializeOptions; + namespace: MongoDBNamespace; + hasBeenClosed: boolean; + authProviders: MongoClientAuthProviders; + /** + * We keep a reference to the sessions that are acquired from the pool. + * - used to track and close all sessions in client.close() (which is non-standard behavior) + * - used to notify the leak checker in our tests if test author forgot to clean up explicit sessions + */ + readonly activeSessions: Set; + readonly sessionPool: ServerSessionPool; + readonly options: MongoOptions; + readonly readConcern?: ReadConcern; + readonly writeConcern?: WriteConcern; + readonly readPreference: ReadPreference; + readonly isMongoClient: true; +} + +/** @public */ +export type MongoClientEvents = Pick & { + // In previous versions the open event emitted a topology, in an effort to no longer + // expose internals but continue to expose this useful event API, it now emits a mongoClient + open(mongoClient: MongoClient): void; +}; + +/** @internal */ + +const kOptions = Symbol('options'); + +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +export class MongoClient extends TypedEventEmitter { + /** @internal */ + s: MongoClientPrivate; + /** @internal */ + topology?: Topology; + /** @internal */ + override readonly mongoLogger: MongoLogger | undefined; + /** @internal */ + private connectionLock?: Promise; + + /** + * The consolidate, parsed, transformed and merged options. + * @internal + */ + [kOptions]: MongoOptions; + + constructor(url: string, options?: MongoClientOptions) { + super(); + + this[kOptions] = parseOptions(url, this, options); + + const shouldSetLogger = Object.values( + this[kOptions].mongoLoggerOptions.componentSeverities + ).some(value => value !== SeverityLevel.OFF); + this.mongoLogger = shouldSetLogger + ? new MongoLogger(this[kOptions].mongoLoggerOptions) + : undefined; + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + + // The internal state + this.s = { + url, + bsonOptions: resolveBSONOptions(this[kOptions]), + namespace: ns('admin'), + hasBeenClosed: false, + sessionPool: new ServerSessionPool(this), + activeSessions: new Set(), + authProviders: new MongoClientAuthProviders(), + + get options() { + return client[kOptions]; + }, + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get isMongoClient(): true { + return true; + } + }; + this.checkForNonGenuineHosts(); + } + + /** @internal */ + private checkForNonGenuineHosts() { + const documentDBHostnames = this[kOptions].hosts.filter((hostAddress: HostAddress) => + isHostMatch(DOCUMENT_DB_CHECK, hostAddress.host) + ); + const srvHostIsDocumentDB = isHostMatch(DOCUMENT_DB_CHECK, this[kOptions].srvHost); + + const cosmosDBHostnames = this[kOptions].hosts.filter((hostAddress: HostAddress) => + isHostMatch(COSMOS_DB_CHECK, hostAddress.host) + ); + const srvHostIsCosmosDB = isHostMatch(COSMOS_DB_CHECK, this[kOptions].srvHost); + + if (documentDBHostnames.length !== 0 || srvHostIsDocumentDB) { + this.mongoLogger?.info('client', DOCUMENT_DB_MSG); + } else if (cosmosDBHostnames.length !== 0 || srvHostIsCosmosDB) { + this.mongoLogger?.info('client', COSMOS_DB_MSG); + } + } + + /** @see MongoOptions */ + get options(): Readonly { + return Object.freeze({ ...this[kOptions] }); + } + + get serverApi(): Readonly { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands(): boolean { + return this[kOptions].monitorCommands; + } + set monitorCommands(value: boolean) { + this[kOptions].monitorCommands = value; + } + + /** @internal */ + get autoEncrypter(): AutoEncrypter | undefined { + return this[kOptions].autoEncrypter; + } + + get readConcern(): ReadConcern | undefined { + return this.s.readConcern; + } + + get writeConcern(): WriteConcern | undefined { + return this.s.writeConcern; + } + + get readPreference(): ReadPreference { + return this.s.readPreference; + } + + get bsonOptions(): BSONSerializeOptions { + return this.s.bsonOptions; + } + + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + async connect(): Promise { + if (this.connectionLock) { + return this.connectionLock; + } + + try { + this.connectionLock = this._connect(); + await this.connectionLock; + } finally { + // release + this.connectionLock = undefined; + } + + return this; + } + + /** + * Create a topology to open the connection, must be locked to avoid topology leaks in concurrency scenario. + * Locking is enforced by the connect method. + * + * @internal + */ + private async _connect(): Promise { + if (this.topology && this.topology.isConnected()) { + return this; + } + + const options = this[kOptions]; + + if (options.tls) { + if (typeof options.tlsCAFile === 'string') { + options.ca ??= await fs.readFile(options.tlsCAFile); + } + if (typeof options.tlsCRLFile === 'string') { + options.crl ??= await fs.readFile(options.tlsCRLFile); + } + if (typeof options.tlsCertificateKeyFile === 'string') { + if (!options.key || !options.cert) { + const contents = await fs.readFile(options.tlsCertificateKeyFile); + options.key ??= contents; + options.cert ??= contents; + } + } + } + if (typeof options.srvHost === 'string') { + const hosts = await resolveSRVRecord(options); + + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + } + + // It is important to perform validation of hosts AFTER SRV resolution, to check the real hostname, + // but BEFORE we even attempt connecting with a potentially not allowed hostname + if (options.credentials?.mechanism === AuthMechanism.MONGODB_OIDC) { + const allowedHosts = + options.credentials?.mechanismProperties?.ALLOWED_HOSTS || DEFAULT_ALLOWED_HOSTS; + const isServiceAuth = !!options.credentials?.mechanismProperties?.PROVIDER_NAME; + if (!isServiceAuth) { + for (const host of options.hosts) { + if (!hostMatchesWildcards(host.toHostPort().host, allowedHosts)) { + throw new MongoInvalidArgumentError( + `Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join( + ',' + )}'` + ); + } + } + } + } + + this.topology = new Topology(this, options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + + this.topology.once(Topology.OPEN, () => this.emit('open', this)); + + for (const event of MONGO_CLIENT_EVENTS) { + this.topology.on(event, (...args: any[]) => this.emit(event, ...(args as any))); + } + + const topologyConnect = async () => { + try { + await promisify(callback => this.topology?.connect(options, callback))(); + } catch (error) { + this.topology?.close(); + throw error; + } + }; + + if (this.autoEncrypter) { + await this.autoEncrypter?.init(); + await topologyConnect(); + await options.encrypter.connectInternalClient(); + } else { + await topologyConnect(); + } + + return this; + } + + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + async close(force = false): Promise { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + + await Promise.all(activeSessionEnds); + + if (this.topology == null) { + return; + } + + // If we would attempt to select a server and get nothing back we short circuit + // to avoid the server selection timeout. + const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred); + const topologyDescription = this.topology.description; + const serverDescriptions = Array.from(topologyDescription.servers.values()); + const servers = selector(topologyDescription, serverDescriptions); + if (servers.length !== 0) { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length !== 0) { + await executeOperation( + this, + new RunAdminCommandOperation( + { endSessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true } + ) + ).catch(() => null); // outcome does not matter; + } + } + + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + + topology.close(); + + const { encrypter } = this[kOptions]; + if (encrypter) { + await encrypter.close(this, force); + } + } + + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName?: string, options?: DbOptions): Db { + options = options ?? {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + + // Return the db object + const db = new Db(this, dbName, finalOptions); + + // Return the database + return db; + } + + /** + * Connect to MongoDB using a url + * + * @remarks + * The programmatically provided options take precedence over the URI options. + * + * @see https://www.mongodb.com/docs/manual/reference/connection-string/ + */ + static async connect(url: string, options?: MongoClientOptions): Promise { + const client = new this(url, options); + return client.connect(); + } + + /** + * Creates a new ClientSession. When using the returned session in an operation + * a corresponding ServerSession will be created. + * + * @remarks + * A ClientSession instance may only be passed to operations being performed on the same + * MongoClient it was started from. + */ + startSession(options?: ClientSessionOptions): ClientSession { + const session = new ClientSession( + this, + this.s.sessionPool, + { explicit: true, ...options }, + this[kOptions] + ); + this.s.activeSessions.add(session); + session.once('ended', () => { + this.s.activeSessions.delete(session); + }); + return session; + } + + /** + * A convenience method for creating and handling the clean up of a ClientSession. + * The session will always be ended when the executor finishes. + * + * @param executor - An executor function that all operations using the provided session must be invoked in + * @param options - optional settings for the session + */ + async withSession(executor: WithSessionCallback): Promise; + async withSession( + options: ClientSessionOptions, + executor: WithSessionCallback + ): Promise; + async withSession( + optionsOrExecutor: ClientSessionOptions | WithSessionCallback, + executor?: WithSessionCallback + ): Promise { + const options = { + // Always define an owner + owner: Symbol(), + // If it's an object inherit the options + ...(typeof optionsOrExecutor === 'object' ? optionsOrExecutor : {}) + }; + + const withSessionCallback = + typeof optionsOrExecutor === 'function' ? optionsOrExecutor : executor; + + if (withSessionCallback == null) { + throw new MongoInvalidArgumentError('Missing required callback parameter'); + } + + const session = this.startSession(options); + + try { + return await withSessionCallback(session); + } finally { + try { + await session.endSession(); + } catch { + // We are not concerned with errors from endSession() + } + } + } + + /** + * Create a new Change Stream, watching for new changes (insertions, updates, + * replacements, deletions, and invalidations) in this cluster. Will ignore all + * changes to system collections, as well as the local, admin, and config databases. + * + * @remarks + * watch() accepts two generic arguments for distinct use cases: + * - The first is to provide the schema that may be defined for all the data within the current cluster + * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument + * + * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param options - Optional settings for the command + * @typeParam TSchema - Type of the data being detected by the change stream + * @typeParam TChange - Type of the whole change stream document emitted + */ + watch< + TSchema extends Document = Document, + TChange extends Document = ChangeStreamDocument + >(pipeline: Document[] = [], options: ChangeStreamOptions = {}): ChangeStream { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, resolveOptions(this, options)); + } +} + +/** + * Parsed Mongo Client Options. + * + * User supplied options are documented by `MongoClientOptions`. + * + * **NOTE:** The client's options parsing is subject to change to support new features. + * This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically. + * + * Options are sourced from: + * - connection string + * - options object passed to the MongoClient constructor + * - file system (ex. tls settings) + * - environment variables + * - DNS SRV records and TXT records + * + * Not all options may be present after client construction as some are obtained from asynchronous operations. + * + * @public + */ +export interface MongoOptions + extends Required< + Pick< + MongoClientOptions, + | 'autoEncryption' + | 'connectTimeoutMS' + | 'directConnection' + | 'driverInfo' + | 'forceServerObjectId' + | 'minHeartbeatFrequencyMS' + | 'heartbeatFrequencyMS' + | 'localThresholdMS' + | 'maxConnecting' + | 'maxIdleTimeMS' + | 'maxPoolSize' + | 'minPoolSize' + | 'monitorCommands' + | 'noDelay' + | 'pkFactory' + | 'raw' + | 'replicaSet' + | 'retryReads' + | 'retryWrites' + | 'serverSelectionTimeoutMS' + | 'socketTimeoutMS' + | 'srvMaxHosts' + | 'srvServiceName' + | 'tlsAllowInvalidCertificates' + | 'tlsAllowInvalidHostnames' + | 'tlsInsecure' + | 'waitQueueTimeoutMS' + | 'zlibCompressionLevel' + > + >, + SupportedNodeConnectionOptions { + appName?: string; + hosts: HostAddress[]; + srvHost?: string; + credentials?: MongoCredentials; + readPreference: ReadPreference; + readConcern: ReadConcern; + loadBalanced: boolean; + directConnection: boolean; + serverApi: ServerApi; + compressors: CompressorName[]; + writeConcern: WriteConcern; + dbName: string; + metadata: ClientMetadata; + /** @internal */ + extendedMetadata: Promise; + /** @internal */ + autoEncrypter?: AutoEncrypter; + proxyHost?: string; + proxyPort?: number; + proxyUsername?: string; + proxyPassword?: string; + serverMonitoringMode: ServerMonitoringMode; + /** @internal */ + connectionType?: typeof Connection; + /** @internal */ + authProviders: MongoClientAuthProviders; + /** @internal */ + encrypter: Encrypter; + /** @internal */ + userSpecifiedAuthSource: boolean; + /** @internal */ + userSpecifiedReplicaSet: boolean; + + /** + * # NOTE ABOUT TLS Options + * + * If `tls` is provided as an option, it is equivalent to setting the `ssl` option. + * + * NodeJS native TLS options are passed through to the socket and retain their original types. + * + * ### Additional options: + * + * | nodejs native option | driver spec equivalent option name | driver option type | + * |:----------------------|:----------------------------------------------|:-------------------| + * | `ca` | `tlsCAFile` | `string` | + * | `crl` | `tlsCRLFile` | `string` | + * | `cert` | `tlsCertificateKeyFile` | `string` | + * | `key` | `tlsCertificateKeyFile` | `string` | + * | `passphrase` | `tlsCertificateKeyFilePassword` | `string` | + * | `rejectUnauthorized` | `tlsAllowInvalidCertificates` | `boolean` | + * | `checkServerIdentity` | `tlsAllowInvalidHostnames` | `boolean` | + * | see note below | `tlsInsecure` | `boolean` | + * + * If `tlsInsecure` is set to `true`, then it will set the node native options `checkServerIdentity` + * to a no-op and `rejectUnauthorized` to `false`. + * + * If `tlsInsecure` is set to `false`, then it will set the node native options `checkServerIdentity` + * to a no-op and `rejectUnauthorized` to the inverse value of `tlsAllowInvalidCertificates`. If + * `tlsAllowInvalidCertificates` is not set, then `rejectUnauthorized` will be set to `true`. + * + * ### Note on `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile` + * + * The files specified by the paths passed in to the `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile` + * fields are read lazily on the first call to `MongoClient.connect`. Once these files have been read and + * the `ca`, `cert`, `crl` and `key` fields are populated, they will not be read again on subsequent calls to + * `MongoClient.connect`. As a result, until the first call to `MongoClient.connect`, the `ca`, + * `cert`, `crl` and `key` fields will be undefined. + */ + tls: boolean; + tlsCAFile?: string; + tlsCRLFile?: string; + tlsCertificateKeyFile?: string; + + /** @internal */ + [featureFlag: symbol]: any; + + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongoLoggerOptions: MongoLoggerOptions; + /** + * @internal + * TODO: NODE-5671 - remove internal flag + */ + mongodbLogPath?: 'stderr' | 'stdout' | MongoDBLogWritable; +} diff --git a/nodejs/node_modules/mongodb/src/mongo_client_auth_providers.ts b/nodejs/node_modules/mongodb/src/mongo_client_auth_providers.ts new file mode 100644 index 00000000..557783c4 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/mongo_client_auth_providers.ts @@ -0,0 +1,54 @@ +import { type AuthProvider } from './cmap/auth/auth_provider'; +import { GSSAPI } from './cmap/auth/gssapi'; +import { MongoCR } from './cmap/auth/mongocr'; +import { MongoDBAWS } from './cmap/auth/mongodb_aws'; +import { MongoDBOIDC } from './cmap/auth/mongodb_oidc'; +import { Plain } from './cmap/auth/plain'; +import { AuthMechanism } from './cmap/auth/providers'; +import { ScramSHA1, ScramSHA256 } from './cmap/auth/scram'; +import { X509 } from './cmap/auth/x509'; +import { MongoInvalidArgumentError } from './error'; + +/** @internal */ +const AUTH_PROVIDERS = new Map AuthProvider>([ + [AuthMechanism.MONGODB_AWS, () => new MongoDBAWS()], + [AuthMechanism.MONGODB_CR, () => new MongoCR()], + [AuthMechanism.MONGODB_GSSAPI, () => new GSSAPI()], + [AuthMechanism.MONGODB_OIDC, () => new MongoDBOIDC()], + [AuthMechanism.MONGODB_PLAIN, () => new Plain()], + [AuthMechanism.MONGODB_SCRAM_SHA1, () => new ScramSHA1()], + [AuthMechanism.MONGODB_SCRAM_SHA256, () => new ScramSHA256()], + [AuthMechanism.MONGODB_X509, () => new X509()] +]); + +/** + * Create a set of providers per client + * to avoid sharing the provider's cache between different clients. + * @internal + */ +export class MongoClientAuthProviders { + private existingProviders: Map = new Map(); + + /** + * Get or create an authentication provider based on the provided mechanism. + * We don't want to create all providers at once, as some providers may not be used. + * @param name - The name of the provider to get or create. + * @returns The provider. + * @throws MongoInvalidArgumentError if the mechanism is not supported. + * @internal + */ + getOrCreateProvider(name: AuthMechanism | string): AuthProvider { + const authProvider = this.existingProviders.get(name); + if (authProvider) { + return authProvider; + } + + const provider = AUTH_PROVIDERS.get(name)?.(); + if (!provider) { + throw new MongoInvalidArgumentError(`authMechanism ${name} not supported`); + } + + this.existingProviders.set(name, provider); + return provider; + } +} diff --git a/nodejs/node_modules/mongodb/src/mongo_logger.ts b/nodejs/node_modules/mongodb/src/mongo_logger.ts new file mode 100644 index 00000000..be345eae --- /dev/null +++ b/nodejs/node_modules/mongodb/src/mongo_logger.ts @@ -0,0 +1,925 @@ +import { inspect, promisify } from 'util'; + +import { type Document, EJSON, type EJSONOptions, type ObjectId } from './bson'; +import type { CommandStartedEvent } from './cmap/command_monitoring_events'; +import type { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolReadyEvent, + ConnectionReadyEvent +} from './cmap/connection_pool_events'; +import { + COMMAND_FAILED, + COMMAND_STARTED, + COMMAND_SUCCEEDED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECKED_IN, + CONNECTION_CHECKED_OUT, + CONNECTION_CLOSED, + CONNECTION_CREATED, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_POOL_CREATED, + CONNECTION_POOL_READY, + CONNECTION_READY, + SERVER_CLOSED, + SERVER_HEARTBEAT_FAILED, + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_OPENING, + SERVER_SELECTION_FAILED, + SERVER_SELECTION_STARTED, + SERVER_SELECTION_SUCCEEDED, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING, + WAITING_FOR_SUITABLE_SERVER +} from './constants'; +import type { + ServerClosedEvent, + ServerOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent +} from './sdam/events'; +import type { + ServerSelectionEvent, + ServerSelectionFailedEvent, + ServerSelectionStartedEvent, + ServerSelectionSucceededEvent, + WaitingForSuitableServerEvent +} from './sdam/server_selection_events'; +import { HostAddress, isPromiseLike, parseUnsignedInteger } from './utils'; + +/** @internal */ +export const SeverityLevel = Object.freeze({ + EMERGENCY: 'emergency', + ALERT: 'alert', + CRITICAL: 'critical', + ERROR: 'error', + WARNING: 'warn', + NOTICE: 'notice', + INFORMATIONAL: 'info', + DEBUG: 'debug', + TRACE: 'trace', + OFF: 'off' +} as const); + +/** @internal */ +export const DEFAULT_MAX_DOCUMENT_LENGTH = 1000; +/** @internal */ +export type SeverityLevel = (typeof SeverityLevel)[keyof typeof SeverityLevel]; + +/** @internal */ +class SeverityLevelMap extends Map { + constructor(entries: [SeverityLevel | number, SeverityLevel | number][]) { + const newEntries: [number | SeverityLevel, SeverityLevel | number][] = []; + for (const [level, value] of entries) { + newEntries.push([value, level]); + } + + newEntries.push(...entries); + super(newEntries); + } + + getNumericSeverityLevel(severity: SeverityLevel): number { + return this.get(severity) as number; + } + + getSeverityLevelName(level: number): SeverityLevel | undefined { + return this.get(level) as SeverityLevel | undefined; + } +} + +/** @internal */ +export const SEVERITY_LEVEL_MAP = new SeverityLevelMap([ + [SeverityLevel.OFF, -Infinity], + [SeverityLevel.EMERGENCY, 0], + [SeverityLevel.ALERT, 1], + [SeverityLevel.CRITICAL, 2], + [SeverityLevel.ERROR, 3], + [SeverityLevel.WARNING, 4], + [SeverityLevel.NOTICE, 5], + [SeverityLevel.INFORMATIONAL, 6], + [SeverityLevel.DEBUG, 7], + [SeverityLevel.TRACE, 8] +]); + +/** @internal */ +export const MongoLoggableComponent = Object.freeze({ + COMMAND: 'command', + TOPOLOGY: 'topology', + SERVER_SELECTION: 'serverSelection', + CONNECTION: 'connection', + CLIENT: 'client' +} as const); + +/** @internal */ +export type MongoLoggableComponent = + (typeof MongoLoggableComponent)[keyof typeof MongoLoggableComponent]; + +/** @internal */ +export interface MongoLoggerEnvOptions { + /** Severity level for command component */ + MONGODB_LOG_COMMAND?: string; + /** Severity level for topology component */ + MONGODB_LOG_TOPOLOGY?: string; + /** Severity level for server selection component */ + MONGODB_LOG_SERVER_SELECTION?: string; + /** Severity level for CMAP */ + MONGODB_LOG_CONNECTION?: string; + /** Severity level for client */ + MONGODB_LOG_CLIENT?: string; + /** Default severity level to be if any of the above are unset */ + MONGODB_LOG_ALL?: string; + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + MONGODB_LOG_MAX_DOCUMENT_LENGTH?: string; + /** Destination for log messages. Must be 'stderr', 'stdout'. Defaults to 'stderr'. */ + MONGODB_LOG_PATH?: string; +} + +/** @internal */ +export interface LogComponentSeveritiesClientOptions { + /** Optional severity level for command component */ + command?: SeverityLevel; + /** Optional severity level for topology component */ + topology?: SeverityLevel; + /** Optionsl severity level for server selection component */ + serverSelection?: SeverityLevel; + /** Optional severity level for connection component */ + connection?: SeverityLevel; + /** Optional severity level for client component */ + client?: SeverityLevel; + /** Optional default severity level to be used if any of the above are unset */ + default?: SeverityLevel; +} + +/** @internal */ +export interface MongoLoggerMongoClientOptions { + /** Destination for log messages */ + mongodbLogPath?: 'stdout' | 'stderr' | MongoDBLogWritable; + /** Severity levels for logger components */ + mongodbLogComponentSeverities?: LogComponentSeveritiesClientOptions; + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + mongodbLogMaxDocumentLength?: number; +} + +/** @internal */ +export interface MongoLoggerOptions { + componentSeverities: { + /** Severity level for command component */ + command: SeverityLevel; + /** Severity level for topology component */ + topology: SeverityLevel; + /** Severity level for server selection component */ + serverSelection: SeverityLevel; + /** Severity level for connection component */ + connection: SeverityLevel; + /** Severity level for client component */ + client: SeverityLevel; + /** Default severity level to be used if any of the above are unset */ + default: SeverityLevel; + }; + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + maxDocumentLength: number; + /** Destination for log messages. */ + logDestination: MongoDBLogWritable; + /** For internal check to see if error should stop logging. */ + logDestinationIsStdErr: boolean; +} + +/** + * Parses a string as one of SeverityLevel + * @internal + * + * @param s - the value to be parsed + * @returns one of SeverityLevel if value can be parsed as such, otherwise null + */ +export function parseSeverityFromString(s?: string): SeverityLevel | null { + const validSeverities: string[] = Object.values(SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity as SeverityLevel; + } + + return null; +} + +/** @internal */ +export function createStdioLogger(stream: { + write: NodeJS.WriteStream['write']; +}): MongoDBLogWritable { + return { + write: promisify((log: Log, cb: (error?: Error) => void): unknown => { + const logLine = inspect(log, { compact: true, breakLength: Infinity }); + stream.write(`${logLine}\n`, 'utf-8', cb); + return; + }) + }; +} + +/** + * resolves the MONGODB_LOG_PATH and mongodbLogPath options from the environment and the + * mongo client options respectively. The mongodbLogPath can be either 'stdout', 'stderr', a NodeJS + * Writable or an object which has a `write` method with the signature: + * ```ts + * write(log: Log): void + * ``` + * + * @returns the MongoDBLogWritable object to write logs to + */ +function resolveLogPath( + { MONGODB_LOG_PATH }: MongoLoggerEnvOptions, + { mongodbLogPath }: MongoLoggerMongoClientOptions +): { mongodbLogPath: MongoDBLogWritable; mongodbLogPathIsStdErr: boolean } { + if (typeof mongodbLogPath === 'string' && /^stderr$/i.test(mongodbLogPath)) { + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; + } + if (typeof mongodbLogPath === 'string' && /^stdout$/i.test(mongodbLogPath)) { + return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; + } + + if (typeof mongodbLogPath === 'object' && typeof mongodbLogPath?.write === 'function') { + return { mongodbLogPath: mongodbLogPath, mongodbLogPathIsStdErr: false }; + } + + if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) { + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; + } + if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) { + return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; + } + + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; +} + +function resolveSeverityConfiguration( + clientOption: string | undefined, + environmentOption: string | undefined, + defaultSeverity: SeverityLevel +): SeverityLevel { + return ( + parseSeverityFromString(clientOption) ?? + parseSeverityFromString(environmentOption) ?? + defaultSeverity + ); +} + +/** @internal */ +export interface Log extends Record { + t: Date; + c: MongoLoggableComponent; + s: SeverityLevel; + message?: string; +} + +/** + * @internal + * TODO: NODE-5671 - remove internal flag and add API comments + */ +export interface MongoDBLogWritable { + write(log: Log): PromiseLike | unknown; +} + +function compareSeverity(s0: SeverityLevel, s1: SeverityLevel): 1 | 0 | -1 { + const s0Num = SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0); + const s1Num = SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1); + + return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0; +} + +/** + * @internal + * Must be separate from Events API due to differences in spec requirements for logging a command success + */ +export type LoggableCommandSucceededEvent = { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + reply: Document | undefined; + serviceId?: ObjectId; + name: typeof COMMAND_SUCCEEDED; + serverConnectionId: bigint | null; + databaseName: string; +}; + +/** + * @internal + * Must be separate from Events API due to differences in spec requirements for logging a command failure + */ +export type LoggableCommandFailedEvent = { + address: string; + connectionId?: string | number; + requestId: number; + duration: number; + commandName: string; + failure: Error; + serviceId?: ObjectId; + name: typeof COMMAND_FAILED; + serverConnectionId: bigint | null; + databaseName: string; +}; + +/** + * @internal + * Must be separate from Events API due to differences in spec requirements for logging server heartbeat beginning + */ +export type LoggableServerHeartbeatStartedEvent = { + topologyId: number; + awaited: boolean; + connectionId: string; + name: typeof SERVER_HEARTBEAT_STARTED; +}; + +/** + * @internal + * Must be separate from Events API due to differences in spec requirements for logging server heartbeat success + */ +export type LoggableServerHeartbeatSucceededEvent = { + topologyId: number; + awaited: boolean; + connectionId: string; + reply: Document; + serverConnectionId: number | ''; + duration: number; + name: typeof SERVER_HEARTBEAT_SUCCEEDED; +}; + +/** + * @internal + * Must be separate from Events API due to differences in spec requirements for logging server heartbeat failure + */ +export type LoggableServerHeartbeatFailedEvent = { + topologyId: number; + awaited: boolean; + connectionId: string; + failure: Error; + duration: number; + name: typeof SERVER_HEARTBEAT_FAILED; +}; + +type SDAMLoggableEvent = + | ServerClosedEvent + | LoggableServerHeartbeatFailedEvent + | LoggableServerHeartbeatStartedEvent + | LoggableServerHeartbeatSucceededEvent + | ServerOpeningEvent + | TopologyClosedEvent + | TopologyDescriptionChangedEvent + | TopologyOpeningEvent; + +/** @internal */ +export type LoggableEvent = + | ServerSelectionStartedEvent + | ServerSelectionFailedEvent + | ServerSelectionSucceededEvent + | WaitingForSuitableServerEvent + | CommandStartedEvent + | LoggableCommandSucceededEvent + | LoggableCommandFailedEvent + | ConnectionPoolCreatedEvent + | ConnectionPoolReadyEvent + | ConnectionPoolClosedEvent + | ConnectionPoolClearedEvent + | ConnectionCreatedEvent + | ConnectionReadyEvent + | ConnectionClosedEvent + | ConnectionCheckedInEvent + | ConnectionCheckedOutEvent + | ConnectionCheckOutStartedEvent + | ConnectionCheckOutFailedEvent + | ServerClosedEvent + | LoggableServerHeartbeatFailedEvent + | LoggableServerHeartbeatStartedEvent + | LoggableServerHeartbeatSucceededEvent + | ServerOpeningEvent + | TopologyClosedEvent + | TopologyDescriptionChangedEvent + | TopologyOpeningEvent; + +/** @internal */ +export interface LogConvertible extends Record { + toLog(): Record; +} + +/** @internal */ +export function stringifyWithMaxLen( + value: any, + maxDocumentLength: number, + options: EJSONOptions = {} +): string { + let strToTruncate = ''; + + if (typeof value === 'string') { + strToTruncate = value; + } else if (typeof value === 'function') { + strToTruncate = value.name; + } else { + try { + strToTruncate = EJSON.stringify(value, options); + } catch (e) { + strToTruncate = `Extended JSON serialization failed with: ${e.message}`; + } + } + + // handle truncation that occurs in the middle of multi-byte codepoints + if ( + maxDocumentLength !== 0 && + strToTruncate.length > maxDocumentLength && + strToTruncate.charCodeAt(maxDocumentLength - 1) !== + strToTruncate.codePointAt(maxDocumentLength - 1) + ) { + maxDocumentLength--; + if (maxDocumentLength === 0) { + return ''; + } + } + + return maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength + ? `${strToTruncate.slice(0, maxDocumentLength)}...` + : strToTruncate; +} + +/** @internal */ +export type Loggable = LoggableEvent | LogConvertible; + +function isLogConvertible(obj: Loggable): obj is LogConvertible { + const objAsLogConvertible = obj as LogConvertible; + // eslint-disable-next-line no-restricted-syntax + return objAsLogConvertible.toLog !== undefined && typeof objAsLogConvertible.toLog === 'function'; +} + +function attachServerSelectionFields( + log: Record, + serverSelectionEvent: ServerSelectionEvent, + maxDocumentLength: number = DEFAULT_MAX_DOCUMENT_LENGTH +) { + const { selector, operation, topologyDescription, message } = serverSelectionEvent; + log.selector = stringifyWithMaxLen(selector, maxDocumentLength); + log.operation = operation; + log.topologyDescription = stringifyWithMaxLen(topologyDescription, maxDocumentLength); + log.message = message; + + return log; +} + +function attachCommandFields( + log: Record, + commandEvent: CommandStartedEvent | LoggableCommandSucceededEvent | LoggableCommandFailedEvent +) { + log.commandName = commandEvent.commandName; + log.requestId = commandEvent.requestId; + log.driverConnectionId = commandEvent.connectionId; + const { host, port } = HostAddress.fromString(commandEvent.address).toHostPort(); + log.serverHost = host; + log.serverPort = port; + if (commandEvent?.serviceId) { + log.serviceId = commandEvent.serviceId.toHexString(); + } + log.databaseName = commandEvent.databaseName; + log.serverConnectionId = commandEvent.serverConnectionId; + + return log; +} + +function attachConnectionFields(log: Record, event: any) { + const { host, port } = HostAddress.fromString(event.address).toHostPort(); + log.serverHost = host; + log.serverPort = port; + + return log; +} + +function attachSDAMFields(log: Record, sdamEvent: SDAMLoggableEvent) { + log.topologyId = sdamEvent.topologyId; + return log; +} + +function attachServerHeartbeatFields( + log: Record, + serverHeartbeatEvent: + | LoggableServerHeartbeatFailedEvent + | LoggableServerHeartbeatStartedEvent + | LoggableServerHeartbeatSucceededEvent +) { + const { awaited, connectionId } = serverHeartbeatEvent; + log.awaited = awaited; + log.driverConnectionId = serverHeartbeatEvent.connectionId; + const { host, port } = HostAddress.fromString(connectionId).toHostPort(); + log.serverHost = host; + log.serverPort = port; + return log; +} + +/** @internal */ +export function defaultLogTransform( + logObject: LoggableEvent | Record, + maxDocumentLength: number = DEFAULT_MAX_DOCUMENT_LENGTH +): Omit { + let log: Omit = Object.create(null); + + switch (logObject.name) { + case SERVER_SELECTION_STARTED: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + return log; + case SERVER_SELECTION_FAILED: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + log.failure = logObject.failure?.message; + return log; + case SERVER_SELECTION_SUCCEEDED: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + log.serverHost = logObject.serverHost; + log.serverPort = logObject.serverPort; + return log; + case WAITING_FOR_SUITABLE_SERVER: + log = attachServerSelectionFields(log, logObject, maxDocumentLength); + log.remainingTimeMS = logObject.remainingTimeMS; + return log; + case COMMAND_STARTED: + log = attachCommandFields(log, logObject); + log.message = 'Command started'; + log.command = stringifyWithMaxLen(logObject.command, maxDocumentLength, { relaxed: true }); + log.databaseName = logObject.databaseName; + return log; + case COMMAND_SUCCEEDED: + log = attachCommandFields(log, logObject); + log.message = 'Command succeeded'; + log.durationMS = logObject.duration; + log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); + return log; + case COMMAND_FAILED: + log = attachCommandFields(log, logObject); + log.message = 'Command failed'; + log.durationMS = logObject.duration; + log.failure = logObject.failure?.message ?? '(redacted)'; + return log; + case CONNECTION_POOL_CREATED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool created'; + if (logObject.options) { + const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = + logObject.options; + log = { + ...log, + maxIdleTimeMS, + minPoolSize, + maxPoolSize, + maxConnecting, + waitQueueTimeoutMS + }; + } + return log; + case CONNECTION_POOL_READY: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool ready'; + return log; + case CONNECTION_POOL_CLEARED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool cleared'; + if (logObject.serviceId?._bsontype === 'ObjectId') { + log.serviceId = logObject.serviceId?.toHexString(); + } + return log; + case CONNECTION_POOL_CLOSED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection pool closed'; + return log; + case CONNECTION_CREATED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection created'; + log.driverConnectionId = logObject.connectionId; + return log; + case CONNECTION_READY: + log = attachConnectionFields(log, logObject); + log.message = 'Connection ready'; + log.driverConnectionId = logObject.connectionId; + return log; + case CONNECTION_CLOSED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection closed'; + log.driverConnectionId = logObject.connectionId; + switch (logObject.reason) { + case 'stale': + log.reason = 'Connection became stale because the pool was cleared'; + break; + case 'idle': + log.reason = + 'Connection has been available but unused for longer than the configured max idle time'; + break; + case 'error': + log.reason = 'An error occurred while using the connection'; + if (logObject.error) { + log.error = logObject.error; + } + break; + case 'poolClosed': + log.reason = 'Connection pool was closed'; + break; + default: + log.reason = `Unknown close reason: ${logObject.reason}`; + } + return log; + case CONNECTION_CHECK_OUT_STARTED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checkout started'; + return log; + case CONNECTION_CHECK_OUT_FAILED: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checkout failed'; + switch (logObject.reason) { + case 'poolClosed': + log.reason = 'Connection pool was closed'; + break; + case 'timeout': + log.reason = 'Wait queue timeout elapsed without a connection becoming available'; + break; + case 'connectionError': + log.reason = 'An error occurred while trying to establish a new connection'; + if (logObject.error) { + log.error = logObject.error; + } + break; + default: + log.reason = `Unknown close reason: ${logObject.reason}`; + } + return log; + case CONNECTION_CHECKED_OUT: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checked out'; + log.driverConnectionId = logObject.connectionId; + return log; + case CONNECTION_CHECKED_IN: + log = attachConnectionFields(log, logObject); + log.message = 'Connection checked in'; + log.driverConnectionId = logObject.connectionId; + return log; + case SERVER_OPENING: + log = attachSDAMFields(log, logObject); + log = attachConnectionFields(log, logObject); + log.message = 'Starting server monitoring'; + return log; + case SERVER_CLOSED: + log = attachSDAMFields(log, logObject); + log = attachConnectionFields(log, logObject); + log.message = 'Stopped server monitoring'; + return log; + case SERVER_HEARTBEAT_STARTED: + log = attachSDAMFields(log, logObject); + log = attachServerHeartbeatFields(log, logObject); + log.message = 'Server heartbeat started'; + return log; + case SERVER_HEARTBEAT_SUCCEEDED: + log = attachSDAMFields(log, logObject); + log = attachServerHeartbeatFields(log, logObject); + log.message = 'Server heartbeat succeeded'; + log.durationMS = logObject.duration; + log.serverConnectionId = logObject.serverConnectionId; + log.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); + return log; + case SERVER_HEARTBEAT_FAILED: + log = attachSDAMFields(log, logObject); + log = attachServerHeartbeatFields(log, logObject); + log.message = 'Server heartbeat failed'; + log.durationMS = logObject.duration; + log.failure = logObject.failure?.message; + return log; + case TOPOLOGY_OPENING: + log = attachSDAMFields(log, logObject); + log.message = 'Starting topology monitoring'; + return log; + case TOPOLOGY_CLOSED: + log = attachSDAMFields(log, logObject); + log.message = 'Stopped topology monitoring'; + return log; + case TOPOLOGY_DESCRIPTION_CHANGED: + log = attachSDAMFields(log, logObject); + log.message = 'Topology description changed'; + log.previousDescription = log.reply = stringifyWithMaxLen( + logObject.previousDescription, + maxDocumentLength + ); + log.newDescription = log.reply = stringifyWithMaxLen( + logObject.newDescription, + maxDocumentLength + ); + return log; + default: + for (const [key, value] of Object.entries(logObject)) { + if (value != null) log[key] = value; + } + } + return log; +} + +/** @internal */ +export class MongoLogger { + componentSeverities: Record; + maxDocumentLength: number; + logDestination: MongoDBLogWritable; + logDestinationIsStdErr: boolean; + pendingLog: PromiseLike | unknown = null; + private severities: Record>; + + /** + * This method should be used when logging errors that do not have a public driver API for + * reporting errors. + */ + error = this.log.bind(this, 'error'); + /** + * This method should be used to log situations where undesirable application behaviour might + * occur. For example, failing to end sessions on `MongoClient.close`. + */ + warn = this.log.bind(this, 'warn'); + /** + * This method should be used to report high-level information about normal driver behaviour. + * For example, the creation of a `MongoClient`. + */ + info = this.log.bind(this, 'info'); + /** + * This method should be used to report information that would be helpful when debugging an + * application. For example, a command starting, succeeding or failing. + */ + debug = this.log.bind(this, 'debug'); + /** + * This method should be used to report fine-grained details related to logic flow. For example, + * entering and exiting a function body. + */ + trace = this.log.bind(this, 'trace'); + + constructor(options: MongoLoggerOptions) { + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + this.logDestinationIsStdErr = options.logDestinationIsStdErr; + this.severities = this.createLoggingSeverities(); + } + + createLoggingSeverities(): Record> { + const severities = Object(); + for (const component of Object.values(MongoLoggableComponent)) { + severities[component] = {}; + for (const severityLevel of Object.values(SeverityLevel)) { + severities[component][severityLevel] = + compareSeverity(severityLevel, this.componentSeverities[component]) <= 0; + } + } + return severities; + } + + turnOffSeverities() { + for (const component of Object.values(MongoLoggableComponent)) { + this.componentSeverities[component] = SeverityLevel.OFF; + for (const severityLevel of Object.values(SeverityLevel)) { + this.severities[component][severityLevel] = false; + } + } + } + + private logWriteFailureHandler(error: Error) { + if (this.logDestinationIsStdErr) { + this.turnOffSeverities(); + this.clearPendingLog(); + return; + } + this.logDestination = createStdioLogger(process.stderr); + this.logDestinationIsStdErr = true; + this.clearPendingLog(); + this.error(MongoLoggableComponent.CLIENT, { + toLog: function () { + return { + message: 'User input for mongodbLogPath is now invalid. Logging is halted.', + error: error.message + }; + } + }); + this.turnOffSeverities(); + this.clearPendingLog(); + } + + private clearPendingLog() { + this.pendingLog = null; + } + + willLog(component: MongoLoggableComponent, severity: SeverityLevel): boolean { + if (severity === SeverityLevel.OFF) return false; + return this.severities[component][severity]; + } + + private log( + severity: SeverityLevel, + component: MongoLoggableComponent, + message: Loggable | string + ): void { + if (!this.willLog(component, severity)) return; + + let logMessage: Log = { t: new Date(), c: component, s: severity }; + if (typeof message === 'string') { + logMessage.message = message; + } else if (typeof message === 'object') { + if (isLogConvertible(message)) { + logMessage = { ...logMessage, ...message.toLog() }; + } else { + logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) }; + } + } + + if (isPromiseLike(this.pendingLog)) { + this.pendingLog = this.pendingLog + .then(() => this.logDestination.write(logMessage)) + .then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); + return; + } + + try { + const logResult = this.logDestination.write(logMessage); + if (isPromiseLike(logResult)) { + this.pendingLog = logResult.then( + this.clearPendingLog.bind(this), + this.logWriteFailureHandler.bind(this) + ); + } + } catch (error) { + this.logWriteFailureHandler(error); + } + } + + /** + * Merges options set through environment variables and the MongoClient, preferring environment + * variables when both are set, and substituting defaults for values not set. Options set in + * constructor take precedence over both environment variables and MongoClient options. + * + * @remarks + * When parsing component severity levels, invalid values are treated as unset and replaced with + * the default severity. + * + * @param envOptions - options set for the logger from the environment + * @param clientOptions - options set for the logger in the MongoClient options + * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger + */ + static resolveOptions( + envOptions: MongoLoggerEnvOptions, + clientOptions: MongoLoggerMongoClientOptions + ): MongoLoggerOptions { + // client options take precedence over env options + const resolvedLogPath = resolveLogPath(envOptions, clientOptions); + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolvedLogPath.mongodbLogPath, + mongodbLogPathIsStdErr: resolvedLogPath.mongodbLogPathIsStdErr + }; + const defaultSeverity = resolveSeverityConfiguration( + combinedOptions.mongodbLogComponentSeverities?.default, + combinedOptions.MONGODB_LOG_ALL, + SeverityLevel.OFF + ); + + return { + componentSeverities: { + command: resolveSeverityConfiguration( + combinedOptions.mongodbLogComponentSeverities?.command, + combinedOptions.MONGODB_LOG_COMMAND, + defaultSeverity + ), + topology: resolveSeverityConfiguration( + combinedOptions.mongodbLogComponentSeverities?.topology, + combinedOptions.MONGODB_LOG_TOPOLOGY, + defaultSeverity + ), + serverSelection: resolveSeverityConfiguration( + combinedOptions.mongodbLogComponentSeverities?.serverSelection, + combinedOptions.MONGODB_LOG_SERVER_SELECTION, + defaultSeverity + ), + connection: resolveSeverityConfiguration( + combinedOptions.mongodbLogComponentSeverities?.connection, + combinedOptions.MONGODB_LOG_CONNECTION, + defaultSeverity + ), + client: resolveSeverityConfiguration( + combinedOptions.mongodbLogComponentSeverities?.client, + combinedOptions.MONGODB_LOG_CLIENT, + defaultSeverity + ), + default: defaultSeverity + }, + maxDocumentLength: + combinedOptions.mongodbLogMaxDocumentLength ?? + parseUnsignedInteger(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? + 1000, + logDestination: combinedOptions.mongodbLogPath, + logDestinationIsStdErr: combinedOptions.mongodbLogPathIsStdErr + }; + } +} diff --git a/nodejs/node_modules/mongodb/src/mongo_types.ts b/nodejs/node_modules/mongodb/src/mongo_types.ts new file mode 100644 index 00000000..1924b2af --- /dev/null +++ b/nodejs/node_modules/mongodb/src/mongo_types.ts @@ -0,0 +1,630 @@ +import type { BSONType, ObjectIdLike } from 'bson'; +import { EventEmitter } from 'events'; + +import type { + Binary, + BSONRegExp, + Decimal128, + Document, + Double, + Int32, + Long, + ObjectId, + Timestamp +} from './bson'; +import { type CommandStartedEvent } from './cmap/command_monitoring_events'; +import { + type LoggableCommandFailedEvent, + type LoggableCommandSucceededEvent, + type LoggableServerHeartbeatFailedEvent, + type LoggableServerHeartbeatStartedEvent, + type LoggableServerHeartbeatSucceededEvent, + MongoLoggableComponent, + type MongoLogger +} from './mongo_logger'; +import type { Sort } from './sort'; + +/** @internal */ +export type TODO_NODE_3286 = any; + +/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */ +export type InferIdType = TSchema extends { _id: infer IdType } + ? // user has defined a type for _id + Record extends IdType + ? never // explicitly forbid empty objects as the type of _id + : IdType + : TSchema extends { _id?: infer IdType } + ? // optional _id defined - return ObjectId | IdType + unknown extends IdType + ? ObjectId // infer the _id type as ObjectId if the type of _id is unknown + : IdType + : ObjectId; // user has not defined _id on schema + +/** Add an _id field to an object shaped type @public */ +export type WithId = EnhancedOmit & { _id: InferIdType }; + +/** + * Add an optional _id field to an object shaped type + * @public + */ +export type OptionalId = EnhancedOmit & { _id?: InferIdType }; + +/** + * Adds an optional _id field to an object shaped type, unless the _id field is required on that type. + * In the case _id is required, this method continues to require_id. + * + * @public + * + * @privateRemarks + * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask + * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?" + * we instead ask "Does ObjectId look like (have the same shape) as the _id?" + */ +export type OptionalUnlessRequiredId = TSchema extends { _id: any } + ? TSchema + : OptionalId; + +/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */ +export type EnhancedOmit = string extends keyof TRecordOrUnion + ? TRecordOrUnion // TRecordOrUnion has indexed type e.g. { _id: string; [k: string]: any; } or it is "any" + : TRecordOrUnion extends any + ? Pick> // discriminated unions + : never; + +/** Remove the _id field from an object shaped type @public */ +export type WithoutId = Omit; + +/** A MongoDB filter can be some portion of the schema or a set of operators @public */ +export type Filter = { + [P in keyof WithId]?: Condition[P]>; +} & RootFilterOperators>; + +/** @public */ +export type Condition = AlternativeType | FilterOperators>; + +/** + * It is possible to search using alternative types in mongodb e.g. + * string types can be searched using a regex in mongo + * array types can be searched using their element type + * @public + */ +export type AlternativeType = T extends ReadonlyArray + ? T | RegExpOrString + : RegExpOrString; + +/** @public */ +export type RegExpOrString = T extends string ? BSONRegExp | RegExp | T : T; + +/** @public */ +export interface RootFilterOperators extends Document { + $and?: Filter[]; + $nor?: Filter[]; + $or?: Filter[]; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacriticSensitive?: boolean; + }; + $where?: string | ((this: TSchema) => boolean); + $comment?: string | Document; +} + +/** + * @public + * A type that extends Document but forbids anything that "looks like" an object id. + */ +export type NonObjectIdLikeDocument = { + [key in keyof ObjectIdLike]?: never; +} & Document; + +/** @public */ +export interface FilterOperators extends NonObjectIdLikeDocument { + // Comparison + $eq?: TValue; + $gt?: TValue; + $gte?: TValue; + $in?: ReadonlyArray; + $lt?: TValue; + $lte?: TValue; + $ne?: TValue; + $nin?: ReadonlyArray; + // Logical + $not?: TValue extends string ? FilterOperators | RegExp : FilterOperators; + // Element + /** + * When `true`, `$exists` matches the documents that contain the field, + * including documents where the field value is null. + */ + $exists?: boolean; + $type?: BSONType | BSONTypeAlias; + // Evaluation + $expr?: Record; + $jsonSchema?: Record; + $mod?: TValue extends number ? [number, number] : never; + $regex?: TValue extends string ? RegExp | BSONRegExp | string : never; + $options?: TValue extends string ? string : never; + // Geospatial + $geoIntersects?: { $geometry: Document }; + $geoWithin?: Document; + $near?: Document; + $nearSphere?: Document; + $maxDistance?: number; + // Array + $all?: ReadonlyArray; + $elemMatch?: Document; + $size?: TValue extends ReadonlyArray ? number : never; + // Bitwise + $bitsAllClear?: BitwiseFilter; + $bitsAllSet?: BitwiseFilter; + $bitsAnyClear?: BitwiseFilter; + $bitsAnySet?: BitwiseFilter; + $rand?: Record; +} + +/** @public */ +export type BitwiseFilter = + | number /** numeric bit mask */ + | Binary /** BinData bit mask */ + | ReadonlyArray; /** `[ , , ... ]` */ + +/** @public */ +export type BSONTypeAlias = keyof typeof BSONType; + +/** @public */ +export type IsAny = true extends false & Type + ? ResultIfAny + : ResultIfNotAny; + +/** @public */ +export type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export type ArrayElement = Type extends ReadonlyArray ? Item : never; + +/** @public */ +export type SchemaMember = { [P in keyof T]?: V } | { [key: string]: V }; + +/** @public */ +export type IntegerType = number | Int32 | Long | bigint; + +/** @public */ +export type NumericType = IntegerType | Decimal128 | Double; + +/** @public */ +export type FilterOperations = T extends Record + ? { [key in keyof T]?: FilterOperators } + : FilterOperators; + +/** @public */ +export type KeysOfAType = { + [key in keyof TSchema]: NonNullable extends Type ? key : never; +}[keyof TSchema]; + +/** @public */ +export type KeysOfOtherType = { + [key in keyof TSchema]: NonNullable extends Type ? never : key; +}[keyof TSchema]; + +/** @public */ +export type AcceptedFields = { + readonly [key in KeysOfAType]?: AssignableType; +}; + +/** It avoids using fields with not acceptable types @public */ +export type NotAcceptedFields = { + readonly [key in KeysOfOtherType]?: never; +}; + +/** @public */ +export type OnlyFieldsOfType = IsAny< + TSchema[keyof TSchema], + Record, + AcceptedFields & + NotAcceptedFields & + Record +>; + +/** @public */ +export type MatchKeysAndValues = Readonly> & Record; + +/** @public */ +export type AddToSetOperators = { + $each?: Array>; +}; + +/** @public */ +export type ArrayOperator = { + $each?: Array>; + $slice?: number; + $position?: number; + $sort?: Sort; +}; + +/** @public */ +export type SetFields = ({ + readonly [key in KeysOfAType | undefined>]?: + | OptionalId> + | AddToSetOperators>>>; +} & IsAny< + TSchema[keyof TSchema], + object, + NotAcceptedFields | undefined> +>) & { + readonly [key: string]: AddToSetOperators | any; +}; + +/** @public */ +export type PushOperator = ({ + readonly [key in KeysOfAType>]?: + | Flatten + | ArrayOperator>>; +} & NotAcceptedFields>) & { + readonly [key: string]: ArrayOperator | any; +}; + +/** @public */ +export type PullOperator = ({ + readonly [key in KeysOfAType>]?: + | Partial> + | FilterOperations>; +} & NotAcceptedFields>) & { + readonly [key: string]: FilterOperators | any; +}; + +/** @public */ +export type PullAllOperator = ({ + readonly [key in KeysOfAType>]?: TSchema[key]; +} & NotAcceptedFields>) & { + readonly [key: string]: ReadonlyArray; +}; + +/** @public */ +export type UpdateFilter = { + $currentDate?: OnlyFieldsOfType< + TSchema, + Date | Timestamp, + true | { $type: 'date' | 'timestamp' } + >; + $inc?: OnlyFieldsOfType; + $min?: MatchKeysAndValues; + $max?: MatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: MatchKeysAndValues; + $setOnInsert?: MatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType< + TSchema, + NumericType | undefined, + { and: IntegerType } | { or: IntegerType } | { xor: IntegerType } + >; +} & Document; + +/** @public */ +export type Nullable = AnyType | null | undefined; + +/** @public */ +export type OneOrMore = T | ReadonlyArray; + +/** @public */ +export type GenericListener = (...args: any[]) => void; + +/** + * Event description type + * @public + */ +export type EventsDescription = Record; + +/** @public */ +export type CommonEvents = 'newListener' | 'removeListener'; + +/** + * Typescript type safe event emitter + * @public + */ +export declare interface TypedEventEmitter extends EventEmitter { + addListener(event: EventKey, listener: Events[EventKey]): this; + addListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + addListener(event: string | symbol, listener: GenericListener): this; + + on(event: EventKey, listener: Events[EventKey]): this; + on( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + on(event: string | symbol, listener: GenericListener): this; + + once(event: EventKey, listener: Events[EventKey]): this; + once( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + once(event: string | symbol, listener: GenericListener): this; + + removeListener(event: EventKey, listener: Events[EventKey]): this; + removeListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + removeListener(event: string | symbol, listener: GenericListener): this; + + off(event: EventKey, listener: Events[EventKey]): this; + off( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + off(event: string | symbol, listener: GenericListener): this; + + removeAllListeners( + event?: EventKey | CommonEvents | symbol | string + ): this; + + listeners( + event: EventKey | CommonEvents | symbol | string + ): Events[EventKey][]; + + rawListeners( + event: EventKey | CommonEvents | symbol | string + ): Events[EventKey][]; + + emit( + event: EventKey | symbol, + ...args: Parameters + ): boolean; + + listenerCount( + type: EventKey | CommonEvents | symbol | string + ): number; + + prependListener(event: EventKey, listener: Events[EventKey]): this; + prependListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + prependListener(event: string | symbol, listener: GenericListener): this; + + prependOnceListener( + event: EventKey, + listener: Events[EventKey] + ): this; + prependOnceListener( + event: CommonEvents, + listener: (eventName: string | symbol, listener: GenericListener) => void + ): this; + prependOnceListener(event: string | symbol, listener: GenericListener): this; + + eventNames(): string[]; + getMaxListeners(): number; + setMaxListeners(n: number): this; +} + +/** + * Typescript type safe event emitter + * @public + */ + +export class TypedEventEmitter extends EventEmitter { + /** @internal */ + protected mongoLogger?: MongoLogger; + /** @internal */ + protected component?: MongoLoggableComponent; + /** @internal */ + emitAndLog( + event: EventKey | symbol, + ...args: Parameters + ): void { + this.emit(event, ...args); + if (this.component) this.mongoLogger?.debug(this.component, args[0]); + } + /** @internal */ + emitAndLogHeartbeat( + event: EventKey | symbol, + topologyId: number, + serverConnectionId?: number | '', + ...args: Parameters + ): void { + this.emit(event, ...args); + if (this.component) { + const loggableHeartbeatEvent: + | LoggableServerHeartbeatFailedEvent + | LoggableServerHeartbeatSucceededEvent + | LoggableServerHeartbeatStartedEvent = { + topologyId: topologyId, + serverConnectionId: serverConnectionId ?? null, + ...args[0] + }; + this.mongoLogger?.debug(this.component, loggableHeartbeatEvent); + } + } + /** @internal */ + emitAndLogCommand( + monitorCommands: boolean, + event: EventKey | symbol, + databaseName: string, + connectionEstablished: boolean, + ...args: Parameters + ): void { + if (monitorCommands) { + this.emit(event, ...args); + } + if (connectionEstablished) { + const loggableCommandEvent: + | CommandStartedEvent + | LoggableCommandFailedEvent + | LoggableCommandSucceededEvent = { + databaseName: databaseName, + ...args[0] + }; + this.mongoLogger?.debug(MongoLoggableComponent.COMMAND, loggableCommandEvent); + } + } +} + +/** @public */ +export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {} + +/** + * Helper types for dot-notation filter attributes + */ + +/** @public */ +export type Join = T extends [] + ? '' + : T extends [string | number] + ? `${T[0]}` + : T extends [string | number, ...infer R] + ? `${T[0]}${D}${Join}` + : string; + +/** @public */ +export type PropertyType = string extends Property + ? unknown + : Property extends keyof Type + ? Type[Property] + : Property extends `${number}` + ? Type extends ReadonlyArray + ? ArrayType + : unknown + : Property extends `${infer Key}.${infer Rest}` + ? Key extends `${number}` + ? Type extends ReadonlyArray + ? PropertyType + : unknown + : Key extends keyof Type + ? Type[Key] extends Map + ? MapType + : PropertyType + : unknown + : unknown; + +/** + * @public + * returns tuple of strings (keys to be joined on '.') that represent every path into a schema + * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/ + * + * @remarks + * Through testing we determined that a depth of 8 is safe for the typescript compiler + * and provides reasonable compilation times. This number is otherwise not special and + * should be changed if issues are found with this level of checking. Beyond this + * depth any helpers that make use of NestedPaths should devolve to not asserting any + * type safety on the input. + */ +export type NestedPaths = Depth['length'] extends 8 + ? [] + : Type extends + | string + | number + | bigint + | boolean + | Date + | RegExp + | Buffer + | Uint8Array + | ((...args: any[]) => any) + | { _bsontype: string } + ? [] + : Type extends ReadonlyArray + ? [] | [number, ...NestedPaths] + : Type extends Map + ? [string] + : Type extends object + ? { + [Key in Extract]: Type[Key] extends Type // type of value extends the parent + ? [Key] + : // for a recursive union type, the child will never extend the parent type. + // but the parent will still extend the child + Type extends Type[Key] + ? [Key] + : Type[Key] extends ReadonlyArray // handling recursive types with arrays + ? Type extends ArrayType // is the type of the parent the same as the type of the array? + ? [Key] // yes, it's a recursive array type + : // for unions, the child type extends the parent + ArrayType extends Type + ? [Key] // we have a recursive array union + : // child is an array, but it's not a recursive array + [Key, ...NestedPaths] + : // child is not structured the same as the parent + [Key, ...NestedPaths] | [Key]; + }[Extract] + : []; + +/** + * @public + * returns keys (strings) for every path into a schema with a value of type + * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/ + */ +export type NestedPathsOfType = KeysOfAType< + { + [Property in Join, '.'>]: PropertyType; + }, + Type +>; + +/** + * @public + * @experimental + */ +export type StrictFilter = + | Partial + | ({ + [Property in Join, []>, '.'>]?: Condition< + PropertyType, Property> + >; + } & RootFilterOperators>); + +/** + * @public + * @experimental + */ +export type StrictUpdateFilter = { + $currentDate?: OnlyFieldsOfType< + TSchema, + Date | Timestamp, + true | { $type: 'date' | 'timestamp' } + >; + $inc?: OnlyFieldsOfType; + $min?: StrictMatchKeysAndValues; + $max?: StrictMatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: StrictMatchKeysAndValues; + $setOnInsert?: StrictMatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType< + TSchema, + NumericType | undefined, + { and: IntegerType } | { or: IntegerType } | { xor: IntegerType } + >; +} & Document; + +/** + * @public + * @experimental + */ +export type StrictMatchKeysAndValues = Readonly< + { + [Property in Join, '.'>]?: PropertyType; + } & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement< + PropertyType + >; + } & { + [Property in `${NestedPathsOfType[]>}.$${ + | `[${string}]` + | ''}.${string}`]?: any; // Could be further narrowed + } & Document +>; diff --git a/nodejs/node_modules/mongodb/src/operations/aggregate.ts b/nodejs/node_modules/mongodb/src/operations/aggregate.ts new file mode 100644 index 00000000..93f1cfe1 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/aggregate.ts @@ -0,0 +1,146 @@ +import type { Document } from '../bson'; +import { MongoInvalidArgumentError } from '../error'; +import { type TODO_NODE_3286 } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { maxWireVersion, type MongoDBNamespace } from '../utils'; +import { WriteConcern } from '../write_concern'; +import { type CollationOptions, CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects, type Hint } from './operation'; + +/** @internal */ +export const DB_AGGREGATE_COLLECTION = 1 as const; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8 as const; + +/** @public */ +export interface AggregateOptions extends CommandOperationOptions { + /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */ + allowDiskUse?: boolean; + /** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */ + batchSize?: number; + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */ + cursor?: Document; + /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */ + maxAwaitTimeMS?: number; + /** Specify collation. */ + collation?: CollationOptions; + /** Add an index selection hint to an aggregation command */ + hint?: Hint; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + + out?: string; +} + +/** @internal */ +export class AggregateOperation extends CommandOperation { + override options: AggregateOptions; + target: string | typeof DB_AGGREGATE_COLLECTION; + pipeline: Document[]; + hasWriteStage: boolean; + + constructor(ns: MongoDBNamespace, pipeline: Document[], options?: AggregateOptions) { + super(undefined, { ...options, dbName: ns.db }); + + this.options = { ...options }; + + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || DB_AGGREGATE_COLLECTION; + + this.pipeline = pipeline; + + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options?.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + + if (this.hasWriteStage) { + this.trySecondaryWrite = true; + } else { + delete this.options.writeConcern; + } + + if (this.explain && this.writeConcern) { + throw new MongoInvalidArgumentError( + 'Option "explain" cannot be used on an aggregate call with writeConcern' + ); + } + + if (options?.cursor != null && typeof options.cursor !== 'object') { + throw new MongoInvalidArgumentError('Cursor options must be an object'); + } + } + + override get commandName() { + return 'aggregate' as const; + } + + override get canRetryRead(): boolean { + return !this.hasWriteStage; + } + + addToPipeline(stage: Document): void { + this.pipeline.push(stage); + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const options: AggregateOptions = this.options; + const serverWireVersion = maxWireVersion(server); + const command: Document = { aggregate: this.target, pipeline: this.pipeline }; + + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; + } + + if (this.hasWriteStage && this.writeConcern) { + WriteConcern.apply(command, this.writeConcern); + } + + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + + if (options.hint) { + command.hint = options.hint; + } + + if (options.let) { + command.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + + return super.executeCommand(server, session, command) as TODO_NODE_3286; + } +} + +defineAspects(AggregateOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE, + Aspect.CURSOR_CREATING +]); diff --git a/nodejs/node_modules/mongodb/src/operations/bulk_write.ts b/nodejs/node_modules/mongodb/src/operations/bulk_write.ts new file mode 100644 index 00000000..58a143f2 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/bulk_write.ts @@ -0,0 +1,58 @@ +import type { + AnyBulkWriteOperation, + BulkOperationBase, + BulkWriteOptions, + BulkWriteResult +} from '../bulk/common'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; + +/** @internal */ +export class BulkWriteOperation extends AbstractOperation { + override options: BulkWriteOptions; + collection: Collection; + operations: AnyBulkWriteOperation[]; + + constructor( + collection: Collection, + operations: AnyBulkWriteOperation[], + options: BulkWriteOptions + ) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + + override get commandName() { + return 'bulkWrite' as const; + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + + // Create the bulk operation + const bulk: BulkOperationBase = + options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + + // for each op go through and add to the bulk + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + + // Execute the bulk + const result = await bulk.execute({ ...options, session }); + return result; + } +} + +defineAspects(BulkWriteOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/collections.ts b/nodejs/node_modules/mongodb/src/operations/collections.ts new file mode 100644 index 00000000..5ed96296 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/collections.ts @@ -0,0 +1,47 @@ +import { Collection } from '../collection'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { AbstractOperation, type OperationOptions } from './operation'; + +export interface CollectionsOptions extends OperationOptions { + nameOnly?: boolean; +} + +/** @internal */ +export class CollectionsOperation extends AbstractOperation { + override options: CollectionsOptions; + db: Db; + + constructor(db: Db, options: CollectionsOptions) { + super(options); + this.options = options; + this.db = db; + } + + override get commandName() { + return 'listCollections' as const; + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + // Let's get the collection names + const documents = await this.db + .listCollections( + {}, + { ...this.options, nameOnly: true, readPreference: this.readPreference, session } + ) + .toArray(); + const collections: Collection[] = []; + for (const { name } of documents) { + if (!name.includes('$')) { + // Filter collections removing any illegal ones + collections.push(new Collection(this.db, name, this.db.s.options)); + } + } + // Return the collection objects + return collections; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/command.ts b/nodejs/node_modules/mongodb/src/operations/command.ts new file mode 100644 index 00000000..3767fa86 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/command.ts @@ -0,0 +1,157 @@ +import type { BSONSerializeOptions, Document } from '../bson'; +import { MongoInvalidArgumentError } from '../error'; +import { Explain, type ExplainOptions } from '../explain'; +import { ReadConcern } from '../read_concern'; +import type { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import { MIN_SECONDARY_WRITE_WIRE_VERSION } from '../sdam/server_selection'; +import type { ClientSession } from '../sessions'; +import { + commandSupportsReadConcern, + decorateWithExplain, + maxWireVersion, + MongoDBNamespace +} from '../utils'; +import { WriteConcern, type WriteConcernOptions } from '../write_concern'; +import type { ReadConcernLike } from './../read_concern'; +import { AbstractOperation, Aspect, type OperationOptions } from './operation'; + +/** @public */ +export interface CollationOptions { + locale: string; + caseLevel?: boolean; + caseFirst?: string; + strength?: number; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; +} + +/** @public */ +export interface CommandOperationOptions + extends OperationOptions, + WriteConcernOptions, + ExplainOptions { + /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */ + readConcern?: ReadConcernLike; + /** Collation */ + collation?: CollationOptions; + maxTimeMS?: number; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; + /** Should retry failed writes */ + retryWrites?: boolean; + + // Admin command overrides. + dbName?: string; + authdb?: string; + noResponse?: boolean; +} + +/** @internal */ +export interface OperationParent { + s: { namespace: MongoDBNamespace }; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + readPreference?: ReadPreference; + bsonOptions?: BSONSerializeOptions; +} + +/** @internal */ +export abstract class CommandOperation extends AbstractOperation { + override options: CommandOperationOptions; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + explain?: Explain; + + constructor(parent?: OperationParent, options?: CommandOperationOptions) { + super(options); + this.options = options ?? {}; + + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = options?.dbName || options?.authdb; + if (dbNameOverride) { + this.ns = new MongoDBNamespace(dbNameOverride, '$cmd'); + } else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new MongoDBNamespace('admin', '$cmd'); + } + + this.readConcern = ReadConcern.fromOptions(options); + this.writeConcern = WriteConcern.fromOptions(options); + + if (this.hasAspect(Aspect.EXPLAINABLE)) { + this.explain = Explain.fromOptions(options); + } else if (options?.explain != null) { + throw new MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + + override get canRetryWrite(): boolean { + if (this.hasAspect(Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + + async executeCommand( + server: Server, + session: ClientSession | undefined, + cmd: Document + ): Promise { + // TODO: consider making this a non-enumerable property + this.server = server; + + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + + const serverWireVersion = maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + + if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + + if (this.trySecondaryWrite && serverWireVersion < MIN_SECONDARY_WRITE_WIRE_VERSION) { + options.omitReadPreference = true; + } + + if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION) && !inTransaction) { + WriteConcern.apply(cmd, this.writeConcern); + } + + if ( + options.collation && + typeof options.collation === 'object' && + !this.hasAspect(Aspect.SKIP_COLLATION) + ) { + Object.assign(cmd, { collation: options.collation }); + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + if (this.hasAspect(Aspect.EXPLAINABLE) && this.explain) { + cmd = decorateWithExplain(cmd, this.explain); + } + + return server.command(this.ns, cmd, options); + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/common_functions.ts b/nodejs/node_modules/mongodb/src/operations/common_functions.ts new file mode 100644 index 00000000..785ecbaf --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/common_functions.ts @@ -0,0 +1,79 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import type { ReadPreference } from '../read_preference'; +import type { ClientSession } from '../sessions'; + +/** @public */ +export interface IndexInformationOptions { + full?: boolean; + readPreference?: ReadPreference; + session?: ClientSession; +} +/** + * Retrieves this collections index info. + * + * @param db - The Db instance on which to retrieve the index info. + * @param name - The name of the collection. + */ +export async function indexInformation(db: Db, name: string): Promise; +export async function indexInformation( + db: Db, + name: string, + options?: IndexInformationOptions +): Promise; +export async function indexInformation( + db: Db, + name: string, + options?: IndexInformationOptions +): Promise { + if (options == null) { + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + // Get the list of indexes of the specified collection + const indexes = await db.collection(name).listIndexes(options).toArray(); + if (full) return indexes; + + const info: Record> = {}; + for (const index of indexes) { + info[index.name] = Object.entries(index.key); + } + return info; +} + +export function maybeAddIdToDocuments( + coll: Collection, + docs: Document[], + options: { forceServerObjectId?: boolean } +): Document[]; +export function maybeAddIdToDocuments( + coll: Collection, + docs: Document, + options: { forceServerObjectId?: boolean } +): Document; +export function maybeAddIdToDocuments( + coll: Collection, + docOrDocs: Document[] | Document, + options: { forceServerObjectId?: boolean } +): Document[] | Document { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options?.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docOrDocs; + } + + const transform = (doc: Document): Document => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }; + return Array.isArray(docOrDocs) ? docOrDocs.map(transform) : transform(docOrDocs); +} diff --git a/nodejs/node_modules/mongodb/src/operations/count.ts b/nodejs/node_modules/mongodb/src/operations/count.ts new file mode 100644 index 00000000..00aae501 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/count.ts @@ -0,0 +1,67 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { MongoDBNamespace } from '../utils'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface CountOptions extends CommandOperationOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** An index name hint for the query. */ + hint?: string | Document; +} + +/** @internal */ +export class CountOperation extends CommandOperation { + override options: CountOptions; + collectionName?: string; + query: Document; + + constructor(namespace: MongoDBNamespace, filter: Document, options: CountOptions) { + super({ s: { namespace: namespace } } as unknown as Collection, options); + + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + + override get commandName() { + return 'count' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const options = this.options; + const cmd: Document = { + count: this.collectionName, + query: this.query + }; + + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + + if (options.hint != null) { + cmd.hint = options.hint; + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + const result = await super.executeCommand(server, session, cmd); + return result ? result.n : 0; + } +} + +defineAspects(CountOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]); diff --git a/nodejs/node_modules/mongodb/src/operations/count_documents.ts b/nodejs/node_modules/mongodb/src/operations/count_documents.ts new file mode 100644 index 00000000..11fb0c3d --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/count_documents.ts @@ -0,0 +1,46 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { AggregateOperation, type AggregateOptions } from './aggregate'; + +/** @public */ +export interface CountDocumentsOptions extends AggregateOptions { + /** The number of documents to skip. */ + skip?: number; + /** The maximum amounts to count before aborting. */ + limit?: number; +} + +/** @internal */ +export class CountDocumentsOperation extends AggregateOperation { + constructor(collection: Collection, query: Document, options: CountDocumentsOptions) { + const pipeline = []; + pipeline.push({ $match: query }); + + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + + super(collection.s.namespace, pipeline, options); + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const result = await super.execute(server, session); + + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result as unknown as Document; + if (response.cursor == null || response.cursor.firstBatch == null) { + return 0; + } + + const docs = response.cursor.firstBatch; + return docs.length ? docs[0].n : 0; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/create_collection.ts b/nodejs/node_modules/mongodb/src/operations/create_collection.ts new file mode 100644 index 00000000..9732e879 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/create_collection.ts @@ -0,0 +1,201 @@ +import type { Document } from '../bson'; +import { + MIN_SUPPORTED_QE_SERVER_VERSION, + MIN_SUPPORTED_QE_WIRE_VERSION +} from '../cmap/wire_protocol/constants'; +import { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoCompatibilityError } from '../error'; +import type { PkFactory } from '../mongo_client'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { CreateIndexOperation } from './indexes'; +import { Aspect, defineAspects } from './operation'; + +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'useBigInt64', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'enableUtf8Validation' +]); + +/** @public + * Configuration options for timeseries collections + * @see https://www.mongodb.com/docs/manual/core/timeseries-collections/ + */ +export interface TimeSeriesCollectionOptions extends Document { + timeField: string; + metaField?: string; + granularity?: 'seconds' | 'minutes' | 'hours' | string; + bucketMaxSpanSeconds?: number; + bucketRoundingSeconds?: number; +} + +/** @public + * Configuration options for clustered collections + * @see https://www.mongodb.com/docs/manual/core/clustered-collections/ + */ +export interface ClusteredCollectionOptions extends Document { + name?: string; + key: Document; + unique: boolean; +} + +/** @public */ +export interface CreateCollectionOptions extends CommandOperationOptions { + /** Create a capped collection */ + capped?: boolean; + /** @deprecated Create an index on the _id field of the document. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */ + autoIndexId?: boolean; + /** The size of the capped collection in bytes */ + size?: number; + /** The maximum number of documents in the capped collection */ + max?: number; + /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */ + flags?: number; + /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection */ + indexOptionDefaults?: Document; + /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view (i.e., does not include the database name and implies the same database as the view to create) */ + viewOn?: string; + /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view */ + pipeline?: Document[]; + /** A primary key factory function for generation of custom _id keys. */ + pkFactory?: PkFactory; + /** A document specifying configuration options for timeseries collections. */ + timeseries?: TimeSeriesCollectionOptions; + /** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */ + clusteredIndex?: ClusteredCollectionOptions; + /** The number of seconds after which a document in a timeseries or clustered collection expires. */ + expireAfterSeconds?: number; + /** @experimental */ + encryptedFields?: Document; + /** + * If set, enables pre-update and post-update document events to be included for any + * change streams that listen on this collection. + */ + changeStreamPreAndPostImages?: { enabled: boolean }; +} + +/* @internal */ +const INVALID_QE_VERSION = + 'Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption.'; + +/** @internal */ +export class CreateCollectionOperation extends CommandOperation { + override options: CreateCollectionOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options: CreateCollectionOptions = {}) { + super(db, options); + + this.options = options; + this.db = db; + this.name = name; + } + + override get commandName() { + return 'create' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const db = this.db; + const name = this.name; + const options = this.options; + + const encryptedFields: Document | undefined = + options.encryptedFields ?? + db.client.options.autoEncryption?.encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + + if (encryptedFields) { + // Creating a QE collection required min server of 7.0.0 + // TODO(NODE-5353): Get wire version information from connection. + if ( + !server.loadBalanced && + server.description.maxWireVersion < MIN_SUPPORTED_QE_WIRE_VERSION + ) { + throw new MongoCompatibilityError( + `${INVALID_QE_VERSION} The minimum server version required is ${MIN_SUPPORTED_QE_SERVER_VERSION}` + ); + } + // Create auxilliary collections for queryable encryption support. + const escCollection = encryptedFields.escCollection ?? `enxcol_.${name}.esc`; + const ecocCollection = encryptedFields.ecocCollection ?? `enxcol_.${name}.ecoc`; + + for (const collectionName of [escCollection, ecocCollection]) { + const createOp = new CreateCollectionOperation(db, collectionName, { + clusteredIndex: { + key: { _id: 1 }, + unique: true + } + }); + await createOp.executeWithoutEncryptedFieldsCheck(server, session); + } + + if (!options.encryptedFields) { + this.options = { ...this.options, encryptedFields }; + } + } + + const coll = await this.executeWithoutEncryptedFieldsCheck(server, session); + + if (encryptedFields) { + // Create the required index for queryable encryption support. + const createIndexOp = new CreateIndexOperation(db, name, { __safeContent__: 1 }, {}); + await createIndexOp.execute(server, session); + } + + return coll; + } + + private async executeWithoutEncryptedFieldsCheck( + server: Server, + session: ClientSession | undefined + ): Promise { + const db = this.db; + const name = this.name; + const options = this.options; + + const cmd: Document = { create: name }; + for (const n in options) { + if ( + (options as any)[n] != null && + typeof (options as any)[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n) + ) { + cmd[n] = (options as any)[n]; + } + } + // otherwise just execute the command + await super.executeCommand(server, session, cmd); + return new Collection(db, name, options); + } +} + +defineAspects(CreateCollectionOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/delete.ts b/nodejs/node_modules/mongodb/src/operations/delete.ts new file mode 100644 index 00000000..39f0fde7 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/delete.ts @@ -0,0 +1,174 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoServerError } from '../error'; +import { type TODO_NODE_3286 } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { MongoDBNamespace } from '../utils'; +import type { WriteConcernOptions } from '../write_concern'; +import { type CollationOptions, CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects, type Hint } from './operation'; + +/** @public */ +export interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions { + /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */ + ordered?: boolean; + /** Specifies the collation to use for the operation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @public */ +export interface DeleteResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */ + acknowledged: boolean; + /** The number of documents that were deleted */ + deletedCount: number; +} + +/** @public */ +export interface DeleteStatement { + /** The query that matches documents to delete. */ + q: Document; + /** The number of matching documents to delete. */ + limit: number; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** @internal */ +export class DeleteOperation extends CommandOperation { + override options: DeleteOptions; + statements: DeleteStatement[]; + + constructor(ns: MongoDBNamespace, statements: DeleteStatement[], options: DeleteOptions) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + + override get commandName() { + return 'delete' as const; + } + + override get canRetryWrite(): boolean { + if (super.canRetryWrite === false) { + return false; + } + + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + + if (options.let) { + command.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o: Document) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + throw new MongoCompatibilityError(`hint is not supported with unacknowledged writes`); + } + } + + return super.executeCommand(server, session, command) as TODO_NODE_3286; + } +} + +export class DeleteOneOperation extends DeleteOperation { + constructor(collection: Collection, filter: Document, options: DeleteOptions) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const res = (await super.execute(server, session)) as TODO_NODE_3286; + if (this.explain) return res; + if (res.code) throw new MongoServerError(res); + if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]); + + return { + acknowledged: this.writeConcern?.w !== 0, + deletedCount: res.n + }; + } +} +export class DeleteManyOperation extends DeleteOperation { + constructor(collection: Collection, filter: Document, options: DeleteOptions) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const res = (await super.execute(server, session)) as TODO_NODE_3286; + if (this.explain) return res; + if (res.code) throw new MongoServerError(res); + if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]); + + return { + acknowledged: this.writeConcern?.w !== 0, + deletedCount: res.n + }; + } +} + +export function makeDeleteStatement( + filter: Document, + options: DeleteOptions & { limit?: number } +): DeleteStatement { + const op: DeleteStatement = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + + if (options.collation) { + op.collation = options.collation; + } + + if (options.hint) { + op.hint = options.hint; + } + + return op; +} + +defineAspects(DeleteOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(DeleteOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(DeleteManyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); diff --git a/nodejs/node_modules/mongodb/src/operations/distinct.ts b/nodejs/node_modules/mongodb/src/operations/distinct.ts new file mode 100644 index 00000000..4fda285d --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/distinct.ts @@ -0,0 +1,81 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { decorateWithCollation, decorateWithReadConcern } from '../utils'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export type DistinctOptions = CommandOperationOptions; + +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +export class DistinctOperation extends CommandOperation { + override options: DistinctOptions; + collection: Collection; + /** Field of the document to find distinct values for. */ + key: string; + /** The query for filtering the set of documents to which we apply the distinct filter. */ + query: Document; + + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection: Collection, key: string, query: Document, options?: DistinctOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.key = key; + this.query = query; + } + + override get commandName() { + return 'distinct' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + + // Distinct command + const cmd: Document = { + distinct: coll.collectionName, + key: key, + query: query + }; + + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (typeof options.comment !== 'undefined') { + cmd.comment = options.comment; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + decorateWithCollation(cmd, coll, options); + + const result = await super.executeCommand(server, session, cmd); + + return this.explain ? result : result.values; + } +} + +defineAspects(DistinctOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE, Aspect.EXPLAINABLE]); diff --git a/nodejs/node_modules/mongodb/src/operations/drop.ts b/nodejs/node_modules/mongodb/src/operations/drop.ts new file mode 100644 index 00000000..41cce4b3 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/drop.ts @@ -0,0 +1,106 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import { MONGODB_ERROR_CODES, MongoServerError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface DropCollectionOptions extends CommandOperationOptions { + /** @experimental */ + encryptedFields?: Document; +} + +/** @internal */ +export class DropCollectionOperation extends CommandOperation { + override options: DropCollectionOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options: DropCollectionOptions = {}) { + super(db, options); + this.db = db; + this.options = options; + this.name = name; + } + + override get commandName() { + return 'drop' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const db = this.db; + const options = this.options; + const name = this.name; + + const encryptedFieldsMap = db.client.options.autoEncryption?.encryptedFieldsMap; + let encryptedFields: Document | undefined = + options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + + if (!encryptedFields && encryptedFieldsMap) { + // If the MongoClient was configured with an encryptedFieldsMap, + // and no encryptedFields config was available in it or explicitly + // passed as an argument, the spec tells us to look one up using + // listCollections(). + const listCollectionsResult = await db + .listCollections({ name }, { nameOnly: false }) + .toArray(); + encryptedFields = listCollectionsResult?.[0]?.options?.encryptedFields; + } + + if (encryptedFields) { + const escCollection = encryptedFields.escCollection || `enxcol_.${name}.esc`; + const ecocCollection = encryptedFields.ecocCollection || `enxcol_.${name}.ecoc`; + + for (const collectionName of [escCollection, ecocCollection]) { + // Drop auxilliary collections, ignoring potential NamespaceNotFound errors. + const dropOp = new DropCollectionOperation(db, collectionName); + try { + await dropOp.executeWithoutEncryptedFieldsCheck(server, session); + } catch (err) { + if ( + !(err instanceof MongoServerError) || + err.code !== MONGODB_ERROR_CODES.NamespaceNotFound + ) { + throw err; + } + } + } + } + + return this.executeWithoutEncryptedFieldsCheck(server, session); + } + + private async executeWithoutEncryptedFieldsCheck( + server: Server, + session: ClientSession | undefined + ): Promise { + await super.executeCommand(server, session, { drop: this.name }); + return true; + } +} + +/** @public */ +export type DropDatabaseOptions = CommandOperationOptions; + +/** @internal */ +export class DropDatabaseOperation extends CommandOperation { + override options: DropDatabaseOptions; + + constructor(db: Db, options: DropDatabaseOptions) { + super(db, options); + this.options = options; + } + override get commandName() { + return 'dropDatabase' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + await super.executeCommand(server, session, { dropDatabase: 1 }); + return true; + } +} + +defineAspects(DropCollectionOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropDatabaseOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/estimated_document_count.ts b/nodejs/node_modules/mongodb/src/operations/estimated_document_count.ts new file mode 100644 index 00000000..c1d6c381 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/estimated_document_count.ts @@ -0,0 +1,56 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface EstimatedDocumentCountOptions extends CommandOperationOptions { + /** + * The maximum amount of time to allow the operation to run. + * + * This option is sent only if the caller explicitly provides a value. The default is to not send a value. + */ + maxTimeMS?: number; +} + +/** @internal */ +export class EstimatedDocumentCountOperation extends CommandOperation { + override options: EstimatedDocumentCountOptions; + collectionName: string; + + constructor(collection: Collection, options: EstimatedDocumentCountOptions = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + + override get commandName() { + return 'count' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const cmd: Document = { count: this.collectionName }; + + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + + const response = await super.executeCommand(server, session, cmd); + + return response?.n || 0; + } +} + +defineAspects(EstimatedDocumentCountOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); diff --git a/nodejs/node_modules/mongodb/src/operations/execute_operation.ts b/nodejs/node_modules/mongodb/src/operations/execute_operation.ts new file mode 100644 index 00000000..21d8b7e1 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/execute_operation.ts @@ -0,0 +1,270 @@ +import type { Document } from '../bson'; +import { + isRetryableReadError, + isRetryableWriteError, + MongoCompatibilityError, + MONGODB_ERROR_CODES, + MongoError, + MongoErrorLabel, + MongoExpiredSessionError, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNotConnectedError, + MongoRuntimeError, + MongoServerError, + MongoTransactionError, + MongoUnexpectedServerResponseError +} from '../error'; +import type { MongoClient } from '../mongo_client'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ServerDescription } from '../sdam/server_description'; +import { + sameServerSelector, + secondaryWritableServerSelector, + type ServerSelector +} from '../sdam/server_selection'; +import type { Topology } from '../sdam/topology'; +import type { ClientSession } from '../sessions'; +import { supportsRetryableWrites } from '../utils'; +import { AbstractOperation, Aspect } from './operation'; + +const MMAPv1_RETRY_WRITES_ERROR_CODE = MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = + 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; + +type ResultTypeFromOperation = TOperation extends AbstractOperation + ? K + : never; + +/** @internal */ +export interface ExecutionResult { + /** The server selected for the operation */ + server: Server; + /** The session used for this operation, may be implicitly created */ + session?: ClientSession; + /** The raw server response for the operation */ + response: Document; +} + +/** + * Executes the given operation with provided arguments. + * @internal + * + * @remarks + * Allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided. + * + * The expectation is that this function: + * - Connects the MongoClient if it has not already been connected + * - Creates a session if none is provided and cleans up the session it creates + * - Selects a server based on readPreference or various factors + * - Retries an operation if it fails for certain errors, see {@link retryOperation} + * + * @typeParam T - The operation's type + * @typeParam TResult - The type of the operation's result, calculated from T + * + * @param client - The MongoClient to execute this operation with + * @param operation - The operation to execute + */ +export async function executeOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T): Promise { + if (!(operation instanceof AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new MongoRuntimeError('This method requires a valid operation instance'); + } + + if (client.topology == null) { + // Auto connect on operation + if (client.s.hasBeenClosed) { + throw new MongoNotConnectedError('Client must be connected before running operations'); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + try { + await client.connect(); + } finally { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + } + } + + const { topology } = client; + if (topology == null) { + throw new MongoRuntimeError('client.connect did not create a topology but also did not throw'); + } + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session = operation.session; + let owner: symbol | undefined; + + if (session == null) { + owner = Symbol(); + session = client.startSession({ owner, explicit: false }); + } else if (session.hasEnded) { + throw new MongoExpiredSessionError('Use of expired sessions is not permitted'); + } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw new MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later'); + } else if (session.client !== client) { + throw new MongoInvalidArgumentError('ClientSession must be from the same MongoClient'); + } + + const readPreference = operation.readPreference ?? ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + throw new MongoTransactionError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ); + } + + if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) { + session.unpin(); + } + + let selector: ReadPreference | ServerSelector; + + if (operation.hasAspect(Aspect.MUST_SELECT_SAME_SERVER)) { + // GetMore and KillCursor operations must always select the same server, but run through + // server selection to potentially force monitor checks if the server is + // in an unknown state. + selector = sameServerSelector(operation.server?.description); + } else if (operation.trySecondaryWrite) { + // If operation should try to write to secondary use the custom server selector + // otherwise provide the read preference. + selector = secondaryWritableServerSelector(topology.commonWireVersion, readPreference); + } else { + selector = readPreference; + } + + const server = await topology.selectServerAsync(selector, { + session, + operationName: operation.commandName + }); + + if (session == null) { + // No session also means it is not retryable, early exit + return operation.execute(server, undefined); + } + + if (!operation.hasAspect(Aspect.RETRYABLE)) { + // non-retryable operation, early exit + try { + return await operation.execute(server, session); + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } + } + + const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead; + + const willRetryWrite = + topology.s.options.retryWrites && + !inTransaction && + supportsRetryableWrites(server) && + operation.canRetryWrite; + + const hasReadAspect = operation.hasAspect(Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(Aspect.WRITE_OPERATION); + const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite); + + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + + try { + return await operation.execute(server, session); + } catch (operationError) { + if (willRetry && operationError instanceof MongoError) { + return await retryOperation(operation, operationError, { + session, + topology, + selector, + previousServer: server.description + }); + } + throw operationError; + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } +} + +/** @internal */ +type RetryOptions = { + session: ClientSession; + topology: Topology; + selector: ReadPreference | ServerSelector; + previousServer: ServerDescription; +}; + +async function retryOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>( + operation: T, + originalError: MongoError, + { session, topology, selector, previousServer }: RetryOptions +): Promise { + const isWriteOperation = operation.hasAspect(Aspect.WRITE_OPERATION); + const isReadOperation = operation.hasAspect(Aspect.READ_OPERATION); + + if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + throw new MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }); + } + + if (isWriteOperation && !isRetryableWriteError(originalError)) { + throw originalError; + } + + if (isReadOperation && !isRetryableReadError(originalError)) { + throw originalError; + } + + if ( + originalError instanceof MongoNetworkError && + session.isPinned && + !session.inTransaction() && + operation.hasAspect(Aspect.CURSOR_CREATING) + ) { + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + session.unpin({ force: true, forceClear: true }); + } + + // select a new server, and attempt to retry the operation + const server = await topology.selectServerAsync(selector, { + session, + operationName: operation.commandName, + previousServer + }); + + if (isWriteOperation && !supportsRetryableWrites(server)) { + throw new MongoUnexpectedServerResponseError( + 'Selected server does not support retryable writes' + ); + } + + try { + return await operation.execute(server, session); + } catch (retryError) { + if ( + retryError instanceof MongoError && + retryError.hasErrorLabel(MongoErrorLabel.NoWritesPerformed) + ) { + throw originalError; + } + throw retryError; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/find.ts b/nodejs/node_modules/mongodb/src/operations/find.ts new file mode 100644 index 00000000..abdda7ed --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/find.ts @@ -0,0 +1,257 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError } from '../error'; +import { ReadConcern } from '../read_concern'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { formatSort, type Sort } from '../sort'; +import { decorateWithExplain, type MongoDBNamespace, normalizeHintField } from '../utils'; +import { type CollationOptions, CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects, type Hint } from './operation'; + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export interface FindOptions + extends Omit { + /** Sets the limit of documents returned in the query. */ + limit?: number; + /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */ + sort?: Sort; + /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */ + projection?: Document; + /** Set to skip N documents ahead in your query (useful for pagination). */ + skip?: number; + /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */ + hint?: Hint; + /** Specify if the cursor can timeout. */ + timeout?: boolean; + /** Specify if the cursor is tailable. */ + tailable?: boolean; + /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */ + awaitData?: boolean; + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** If true, returns only the index keys in the resulting documents. */ + returnKey?: boolean; + /** The inclusive lower bound for a specific index */ + min?: Document; + /** The exclusive upper bound for a specific index */ + max?: Document; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */ + maxAwaitTimeMS?: number; + /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */ + noCursorTimeout?: boolean; + /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */ + collation?: CollationOptions; + /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */ + allowDiskUse?: boolean; + /** Determines whether to close the cursor after the first batch. Defaults to false. */ + singleBatch?: boolean; + /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */ + allowPartialResults?: boolean; + /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */ + showRecordId?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true. + * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored. + */ + oplogReplay?: boolean; +} + +/** @internal */ +export class FindOperation extends CommandOperation { + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + override options: FindOptions & { writeConcern?: never }; + filter: Document; + + constructor( + collection: Collection | undefined, + ns: MongoDBNamespace, + filter: Document = {}, + options: FindOptions = {} + ) { + super(collection, options); + + this.options = { ...options }; + delete this.options.writeConcern; + this.ns = ns; + + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectId' ? { _id: filter } : filter; + } + + override get commandName() { + return 'find' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + this.server = server; + + const options = this.options; + + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = decorateWithExplain(findCommand, this.explain); + } + + return server.command(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }); + } +} + +function makeFindCommand(ns: MongoDBNamespace, filter: Document, options: FindOptions): Document { + const findCommand: Document = { + find: ns.collection, + filter + }; + + if (options.sort) { + findCommand.sort = formatSort(options.sort); + } + + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + findCommand.projection = projection; + } + + if (options.hint) { + findCommand.hint = normalizeHintField(options.hint); + } + + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; + } else { + findCommand.limit = options.limit; + } + } + + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if ( + options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit) + ) { + findCommand.limit = -options.batchSize; + } + + findCommand.singleBatch = true; + } else { + findCommand.batchSize = options.batchSize; + } + } + + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + findCommand.comment = options.comment; + } + + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + + const readConcern = ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + + if (options.max) { + findCommand.max = options.max; + } + + if (options.min) { + findCommand.min = options.min; + } + + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + + if (typeof options.oplogReplay === 'boolean') { + findCommand.oplogReplay = options.oplogReplay; + } + + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + + if (options.collation) { + findCommand.collation = options.collation; + } + + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + + if (options.let) { + findCommand.let = options.let; + } + + return findCommand; +} + +defineAspects(FindOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE, + Aspect.CURSOR_CREATING +]); diff --git a/nodejs/node_modules/mongodb/src/operations/find_and_modify.ts b/nodejs/node_modules/mongodb/src/operations/find_and_modify.ts new file mode 100644 index 00000000..68abe51a --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/find_and_modify.ts @@ -0,0 +1,294 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { formatSort, type Sort, type SortForCmd } from '../sort'; +import { decorateWithCollation, hasAtomicOperators, maxWireVersion } from '../utils'; +import type { WriteConcern, WriteConcernSettings } from '../write_concern'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export const ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +} as const); + +/** @public */ +export type ReturnDocument = (typeof ReturnDocument)[keyof typeof ReturnDocument]; + +/** @public */ +export interface FindOneAndDeleteOptions extends CommandOperationOptions { + /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Return the ModifyResult instead of the modified document. Defaults to false + */ + includeResultMetadata?: boolean; +} + +/** @public */ +export interface FindOneAndReplaceOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Return the ModifyResult instead of the modified document. Defaults to false + */ + includeResultMetadata?: boolean; +} + +/** @public */ +export interface FindOneAndUpdateOptions extends CommandOperationOptions { + /** Optional list of array filters referenced in filtered positional operators */ + arrayFilters?: Document[]; + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/ + hint?: Document; + /** Limits the fields to return for all matching documents. */ + projection?: Document; + /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */ + returnDocument?: ReturnDocument; + /** Determines which document the operation modifies if the query selects multiple documents. */ + sort?: Sort; + /** Upsert the document if it does not exist. */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; + /** + * Return the ModifyResult instead of the modified document. Defaults to false + */ + includeResultMetadata?: boolean; +} + +/** @internal */ +interface FindAndModifyCmdBase { + remove: boolean; + new: boolean; + upsert: boolean; + update?: Document; + sort?: SortForCmd; + fields?: Document; + bypassDocumentValidation?: boolean; + arrayFilters?: Document[]; + maxTimeMS?: number; + let?: Document; + writeConcern?: WriteConcern | WriteConcernSettings; + /** + * Comment to apply to the operation. + * + * In server versions pre-4.4, 'comment' must be string. A server + * error will be thrown if any other type is provided. + * + * In server versions 4.4 and above, 'comment' can be any valid BSON type. + */ + comment?: unknown; +} + +function configureFindAndModifyCmdBaseUpdateOpts( + cmdBase: FindAndModifyCmdBase, + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions +): FindAndModifyCmdBase { + cmdBase.new = options.returnDocument === ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} + +/** @internal */ +export class FindAndModifyOperation extends CommandOperation { + override options: FindOneAndReplaceOptions | FindOneAndUpdateOptions | FindOneAndDeleteOptions; + cmdBase: FindAndModifyCmdBase; + collection: Collection; + query: Document; + doc?: Document; + + constructor( + collection: Collection, + query: Document, + options: FindOneAndReplaceOptions | FindOneAndUpdateOptions | FindOneAndDeleteOptions + ) { + super(collection, options); + this.options = options ?? {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + + options.includeResultMetadata ??= false; + + const sort = formatSort(options.sort); + if (sort) { + this.cmdBase.sort = sort; + } + + if (options.projection) { + this.cmdBase.fields = options.projection; + } + + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; + } + + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; + } + + if (options.let) { + this.cmdBase.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + this.cmdBase.comment = options.comment; + } + + // force primary read preference + this.readPreference = ReadPreference.primary; + + this.collection = collection; + this.query = query; + } + + override get commandName() { + return 'findAndModify' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + + // Create findAndModify command object + const cmd: Document = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return err; + } + + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = this.writeConcern?.w === 0; + if (unacknowledgedWrite || maxWireVersion(server) < 8) { + throw new MongoCompatibilityError( + 'The current topology does not support a hint on findAndModify commands' + ); + } + + cmd.hint = options.hint; + } + + // Execute the command + const result = await super.executeCommand(server, session, cmd); + return options.includeResultMetadata ? result : result.value ?? null; + } +} + +/** @internal */ +export class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection: Collection, filter: Document, options: FindOneAndDeleteOptions) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + super(collection, filter, options); + this.cmdBase.remove = true; + } +} + +/** @internal */ +export class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor( + collection: Collection, + filter: Document, + replacement: Document, + options: FindOneAndReplaceOptions + ) { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + if (replacement == null || typeof replacement !== 'object') { + throw new MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} + +/** @internal */ +export class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor( + collection: Collection, + filter: Document, + update: Document, + options: FindOneAndUpdateOptions + ) { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Argument "filter" must be an object'); + } + + if (update == null || typeof update !== 'object') { + throw new MongoInvalidArgumentError('Argument "update" must be an object'); + } + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; + } + } +} + +defineAspects(FindAndModifyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.RETRYABLE, + Aspect.EXPLAINABLE +]); diff --git a/nodejs/node_modules/mongodb/src/operations/get_more.ts b/nodejs/node_modules/mongodb/src/operations/get_more.ts new file mode 100644 index 00000000..5cf01904 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/get_more.ts @@ -0,0 +1,103 @@ +import type { Document, Long } from '../bson'; +import { MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { maxWireVersion, type MongoDBNamespace } from '../utils'; +import { AbstractOperation, Aspect, defineAspects, type OperationOptions } from './operation'; + +/** @internal */ +export interface GetMoreOptions extends OperationOptions { + /** Set the batchSize for the getMoreCommand when iterating over the query results. */ + batchSize?: number; + /** + * Comment to apply to the operation. + * + * getMore only supports 'comment' in server versions 4.4 and above. + */ + comment?: unknown; + /** Number of milliseconds to wait before aborting the query. */ + maxTimeMS?: number; + /** TODO(NODE-4413): Address bug with maxAwaitTimeMS not being passed in from the cursor correctly */ + maxAwaitTimeMS?: number; +} + +/** + * GetMore command: https://www.mongodb.com/docs/manual/reference/command/getMore/ + * @internal + */ +export interface GetMoreCommand { + getMore: Long; + collection: string; + batchSize?: number; + maxTimeMS?: number; + /** Only supported on wire versions 10 or greater */ + comment?: unknown; +} + +/** @internal */ +export class GetMoreOperation extends AbstractOperation { + cursorId: Long; + override options: GetMoreOptions; + + constructor(ns: MongoDBNamespace, cursorId: Long, server: Server, options: GetMoreOptions) { + super(options); + + this.options = options; + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + + override get commandName() { + return 'getMore' as const; + } + /** + * Although there is a server already associated with the get more operation, the signature + * for execute passes a server so we will just use that one. + */ + override async execute(server: Server, _session: ClientSession | undefined): Promise { + if (server !== this.server) { + throw new MongoRuntimeError('Getmore must run on the same server operation began on'); + } + + if (this.cursorId == null || this.cursorId.isZero()) { + throw new MongoRuntimeError('Unable to iterate cursor with no id'); + } + + const collection = this.ns.collection; + if (collection == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + throw new MongoRuntimeError('A collection name must be determined before getMore'); + } + + const getMoreCmd: GetMoreCommand = { + getMore: this.cursorId, + collection + }; + + if (typeof this.options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + + if (typeof this.options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined && maxWireVersion(server) >= 9) { + getMoreCmd.comment = this.options.comment; + } + + const commandOptions = { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch', + ...this.options + }; + + return server.command(this.ns, getMoreCmd, commandOptions); + } +} + +defineAspects(GetMoreOperation, [Aspect.READ_OPERATION, Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/nodejs/node_modules/mongodb/src/operations/indexes.ts b/nodejs/node_modules/mongodb/src/operations/indexes.ts new file mode 100644 index 00000000..cbeb82ff --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/indexes.ts @@ -0,0 +1,475 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoCompatibilityError, MONGODB_ERROR_CODES, MongoError } from '../error'; +import { type OneOrMore } from '../mongo_types'; +import { ReadPreference } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { isObject, maxWireVersion, type MongoDBNamespace } from '../utils'; +import { + type CollationOptions, + CommandOperation, + type CommandOperationOptions, + type OperationParent +} from './command'; +import { indexInformation, type IndexInformationOptions } from './common_functions'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; + +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + + // 2d-sphere indexes + '2dsphereIndexVersion', + + // 2d indexes + 'bits', + 'min', + 'max', + + // geoHaystack Indexes + 'bucketSize', + + // wildcard indexes + 'wildcardProjection' +]); + +/** @public */ +export type IndexDirection = + | -1 + | 1 + | '2d' + | '2dsphere' + | 'text' + | 'geoHaystack' + | 'hashed' + | number; + +function isIndexDirection(x: unknown): x is IndexDirection { + return ( + typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack' + ); +} +/** @public */ +export type IndexSpecification = OneOrMore< + | string + | [string, IndexDirection] + | { [key: string]: IndexDirection } + | Map +>; + +/** @public */ +export interface IndexDescription + extends Pick< + CreateIndexesOptions, + | 'background' + | 'unique' + | 'partialFilterExpression' + | 'sparse' + | 'hidden' + | 'expireAfterSeconds' + | 'storageEngine' + | 'version' + | 'weights' + | 'default_language' + | 'language_override' + | 'textIndexVersion' + | '2dsphereIndexVersion' + | 'bits' + | 'min' + | 'max' + | 'bucketSize' + | 'wildcardProjection' + > { + collation?: CollationOptions; + name?: string; + key: { [key: string]: IndexDirection } | Map; +} + +/** @public */ +export interface CreateIndexesOptions extends Omit { + /** Creates the index in the background, yielding whenever possible. */ + background?: boolean; + /** Creates an unique index. */ + unique?: boolean; + /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */ + name?: string; + /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ + partialFilterExpression?: Document; + /** Creates a sparse index. */ + sparse?: boolean; + /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */ + expireAfterSeconds?: number; + /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */ + storageEngine?: Document; + /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */ + commitQuorum?: number | string; + /** Specifies the index version number, either 0 or 1. */ + version?: number; + // text indexes + weights?: Document; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + // 2d-sphere indexes + '2dsphereIndexVersion'?: number; + // 2d indexes + bits?: number; + /** For geospatial indexes set the lower bound for the co-ordinates. */ + min?: number; + /** For geospatial indexes set the high bound for the co-ordinates. */ + max?: number; + // geoHaystack Indexes + bucketSize?: number; + // wildcard indexes + wildcardProjection?: Document; + /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */ + hidden?: boolean; +} + +function isSingleIndexTuple(t: unknown): t is [string, IndexDirection] { + return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); +} + +function makeIndexSpec( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions +): IndexDescription { + const key: Map = new Map(); + + const indexSpecs = + !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; + + // Iterate through array and handle different types + for (const spec of indexSpecs) { + if (typeof spec === 'string') { + key.set(spec, 1); + } else if (Array.isArray(spec)) { + key.set(spec[0], spec[1] ?? 1); + } else if (spec instanceof Map) { + for (const [property, value] of spec) { + key.set(property, value); + } + } else if (isObject(spec)) { + for (const [property, value] of Object.entries(spec)) { + key.set(property, value); + } + } + } + + return { ...options, key }; +} + +/** @internal */ +export class IndexesOperation extends AbstractOperation { + override options: IndexInformationOptions; + collection: Collection; + + constructor(collection: Collection, options: IndexInformationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + override get commandName() { + return 'listIndexes' as const; + } + + override async execute(_server: Server, session: ClientSession | undefined): Promise { + const coll = this.collection; + const options = this.options; + + return indexInformation(coll.s.db, coll.collectionName, { + full: true, + ...options, + readPreference: this.readPreference, + session + }); + } +} + +/** @internal */ +export class CreateIndexesOperation< + T extends string | string[] = string[] +> extends CommandOperation { + override options: CreateIndexesOptions; + collectionName: string; + indexes: ReadonlyArray & { key: Map }>; + + constructor( + parent: OperationParent, + collectionName: string, + indexes: IndexDescription[], + options?: CreateIndexesOptions + ) { + super(parent, options); + + this.options = options ?? {}; + this.collectionName = collectionName; + this.indexes = indexes.map(userIndex => { + // Ensure the key is a Map to preserve index key ordering + const key = + userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); + const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join('_'); + const validIndexOptions = Object.fromEntries( + Object.entries({ ...userIndex }).filter(([optionName]) => + VALID_INDEX_OPTIONS.has(optionName) + ) + ); + return { + ...validIndexOptions, + name, + key + }; + }); + } + + override get commandName() { + return 'createIndexes'; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const options = this.options; + const indexes = this.indexes; + + const serverWireVersion = maxWireVersion(server); + + const cmd: Document = { createIndexes: this.collectionName, indexes }; + + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + throw new MongoCompatibilityError( + 'Option `commitQuorum` for `createIndexes` not supported on servers < 4.4' + ); + } + cmd.commitQuorum = options.commitQuorum; + } + + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + + await super.executeCommand(server, session, cmd); + + const indexNames = indexes.map(index => index.name || ''); + return indexNames as T; + } +} + +/** @internal */ +export class CreateIndexOperation extends CreateIndexesOperation { + constructor( + parent: OperationParent, + collectionName: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ) { + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const indexNames = await super.execute(server, session); + return indexNames[0]; + } +} + +/** @internal */ +export class EnsureIndexOperation extends CreateIndexOperation { + db: Db; + + constructor( + db: Db, + collectionName: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ) { + super(db, collectionName, indexSpec, options); + + this.readPreference = ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + + override get commandName() { + return 'listIndexes'; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const indexName = this.indexes[0].name; + const indexes = await this.db + .collection(this.collectionName) + .listIndexes({ session }) + .toArray() + .catch(error => { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) + return []; + throw error; + }); + if (indexName && indexes.some(index => index.name === indexName)) return indexName; + return super.execute(server, session); + } +} + +/** @public */ +export type DropIndexesOptions = CommandOperationOptions; + +/** @internal */ +export class DropIndexOperation extends CommandOperation { + override options: DropIndexesOptions; + collection: Collection; + indexName: string; + + constructor(collection: Collection, indexName: string, options?: DropIndexesOptions) { + super(collection, options); + + this.options = options ?? {}; + this.collection = collection; + this.indexName = indexName; + } + + override get commandName() { + return 'dropIndexes' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + return super.executeCommand(server, session, cmd); + } +} + +/** @public */ +export interface ListIndexesOptions extends Omit { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListIndexesOperation extends CommandOperation { + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + override options: ListIndexesOptions & { writeConcern?: never }; + collectionNamespace: MongoDBNamespace; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(collection, options); + + this.options = { ...options }; + delete this.options.writeConcern; + this.collectionNamespace = collection.s.namespace; + } + + override get commandName() { + return 'listIndexes' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const serverWireVersion = maxWireVersion(server); + + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + + const command: Document = { listIndexes: this.collectionNamespace.collection, cursor }; + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (serverWireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + + return super.executeCommand(server, session, command); + } +} + +/** @internal */ +export class IndexExistsOperation extends AbstractOperation { + override options: IndexInformationOptions; + collection: Collection; + indexes: string | string[]; + + constructor( + collection: Collection, + indexes: string | string[], + options: IndexInformationOptions + ) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + + override get commandName() { + return 'listIndexes' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const coll = this.collection; + const indexes = this.indexes; + + const info = await indexInformation(coll.s.db, coll.collectionName, { + ...this.options, + readPreference: this.readPreference, + session + }); + // Let's check for the index names + if (!Array.isArray(indexes)) return info[indexes] != null; + // All keys found return true + return indexes.every(indexName => info[indexName] != null); + } +} + +/** @internal */ +export class IndexInformationOperation extends AbstractOperation { + override options: IndexInformationOptions; + db: Db; + name: string; + + constructor(db: Db, name: string, options?: IndexInformationOptions) { + super(options); + this.options = options ?? {}; + this.db = db; + this.name = name; + } + + override get commandName() { + return 'listIndexes' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const db = this.db; + const name = this.name; + + return indexInformation(db, name, { + ...this.options, + readPreference: this.readPreference, + session + }); + } +} + +defineAspects(ListIndexesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); +defineAspects(CreateIndexesOperation, [Aspect.WRITE_OPERATION]); +defineAspects(CreateIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(EnsureIndexOperation, [Aspect.WRITE_OPERATION]); +defineAspects(DropIndexOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/insert.ts b/nodejs/node_modules/mongodb/src/operations/insert.ts new file mode 100644 index 00000000..9b3ba4b2 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/insert.ts @@ -0,0 +1,160 @@ +import type { Document } from '../bson'; +import type { BulkWriteOptions } from '../bulk/common'; +import type { Collection } from '../collection'; +import { MongoInvalidArgumentError, MongoServerError } from '../error'; +import type { InferIdType } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { MongoDBNamespace } from '../utils'; +import { WriteConcern } from '../write_concern'; +import { BulkWriteOperation } from './bulk_write'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { maybeAddIdToDocuments } from './common_functions'; +import { AbstractOperation, Aspect, defineAspects } from './operation'; + +/** @internal */ +export class InsertOperation extends CommandOperation { + override options: BulkWriteOptions; + documents: Document[]; + + constructor(ns: MongoDBNamespace, documents: Document[], options: BulkWriteOptions) { + super(undefined, options); + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns; + this.documents = documents; + } + + override get commandName() { + return 'insert' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + return super.executeCommand(server, session, command); + } +} + +/** @public */ +export interface InsertOneOptions extends CommandOperationOptions { + /** Allow driver to bypass schema validation. */ + bypassDocumentValidation?: boolean; + /** Force server to assign _id values instead of driver. */ + forceServerObjectId?: boolean; +} + +/** @public */ +export interface InsertOneResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */ + insertedId: InferIdType; +} + +export class InsertOneOperation extends InsertOperation { + constructor(collection: Collection, doc: Document, options: InsertOneOptions) { + super(collection.s.namespace, maybeAddIdToDocuments(collection, [doc], options), options); + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const res = await super.execute(server, session); + if (res.code) throw new MongoServerError(res); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + throw new MongoServerError(res.writeErrors[0]); + } + + return { + acknowledged: this.writeConcern?.w !== 0, + insertedId: this.documents[0]._id + }; + } +} + +/** @public */ +export interface InsertManyResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of inserted documents for this operations */ + insertedCount: number; + /** Map of the index of the inserted document to the id of the inserted document */ + insertedIds: { [key: number]: InferIdType }; +} + +/** @internal */ +export class InsertManyOperation extends AbstractOperation { + override options: BulkWriteOptions; + collection: Collection; + docs: Document[]; + + constructor(collection: Collection, docs: Document[], options: BulkWriteOptions) { + super(options); + + if (!Array.isArray(docs)) { + throw new MongoInvalidArgumentError('Argument "docs" must be an array of documents'); + } + + this.options = options; + this.collection = collection; + this.docs = docs; + } + + override get commandName() { + return 'insert' as const; + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = WriteConcern.fromOptions(options); + const bulkWriteOperation = new BulkWriteOperation( + coll, + this.docs.map(document => ({ + insertOne: { document } + })), + options + ); + + try { + const res = await bulkWriteOperation.execute(server, session); + return { + acknowledged: writeConcern?.w !== 0, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }; + } catch (err) { + if (err && err.message === 'Operation must be an object with an operation key') { + throw new MongoInvalidArgumentError( + 'Collection.insertMany() cannot be called with an array that has null/undefined values' + ); + } + throw err; + } + } +} + +defineAspects(InsertOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(InsertOneOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION]); +defineAspects(InsertManyOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/is_capped.ts b/nodejs/node_modules/mongodb/src/operations/is_capped.ts new file mode 100644 index 00000000..db52ec3b --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/is_capped.ts @@ -0,0 +1,35 @@ +import type { Collection } from '../collection'; +import { MongoAPIError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { AbstractOperation, type OperationOptions } from './operation'; + +/** @internal */ +export class IsCappedOperation extends AbstractOperation { + override options: OperationOptions; + collection: Collection; + + constructor(collection: Collection, options: OperationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + + override get commandName() { + return 'listCollections' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const coll = this.collection; + const [collection] = await coll.s.db + .listCollections( + { name: coll.collectionName }, + { ...this.options, nameOnly: false, readPreference: this.readPreference, session } + ) + .toArray(); + if (collection == null || collection.options == null) { + throw new MongoAPIError(`collection ${coll.namespace} not found`); + } + return !!collection.options?.capped; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/kill_cursors.ts b/nodejs/node_modules/mongodb/src/operations/kill_cursors.ts new file mode 100644 index 00000000..73cf93cb --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/kill_cursors.ts @@ -0,0 +1,56 @@ +import type { Long } from '../bson'; +import { MongoRuntimeError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { MongoDBNamespace } from '../utils'; +import { AbstractOperation, Aspect, defineAspects, type OperationOptions } from './operation'; + +/** + * https://www.mongodb.com/docs/manual/reference/command/killCursors/ + * @internal + */ +interface KillCursorsCommand { + killCursors: string; + cursors: Long[]; + comment?: unknown; +} + +export class KillCursorsOperation extends AbstractOperation { + cursorId: Long; + + constructor(cursorId: Long, ns: MongoDBNamespace, server: Server, options: OperationOptions) { + super(options); + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + + override get commandName() { + return 'killCursors' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + if (server !== this.server) { + throw new MongoRuntimeError('Killcursor must run on the same server operation began on'); + } + + const killCursors = this.ns.collection; + if (killCursors == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + throw new MongoRuntimeError('A collection name must be determined before killCursors'); + } + + const killCursorsCommand: KillCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + try { + await server.command(this.ns, killCursorsCommand, { session }); + } catch { + // The driver should never emit errors from killCursors, this is spec-ed behavior + } + } +} + +defineAspects(KillCursorsOperation, [Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/nodejs/node_modules/mongodb/src/operations/list_collections.ts b/nodejs/node_modules/mongodb/src/operations/list_collections.ts new file mode 100644 index 00000000..1bdea119 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/list_collections.ts @@ -0,0 +1,94 @@ +import type { Binary, Document } from '../bson'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { maxWireVersion } from '../utils'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface ListCollectionsOptions extends Omit { + /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */ + nameOnly?: boolean; + /** Since 4.0: If true and nameOnly is true, allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced. */ + authorizedCollections?: boolean; + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListCollectionsOperation extends CommandOperation { + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + override options: ListCollectionsOptions & { writeConcern?: never }; + db: Db; + filter: Document; + nameOnly: boolean; + authorizedCollections: boolean; + batchSize?: number; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(db, options); + + this.options = { ...options }; + delete this.options.writeConcern; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + this.authorizedCollections = !!this.options.authorizedCollections; + + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + + override get commandName() { + return 'listCollections' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + return super.executeCommand(server, session, this.generateCommand(maxWireVersion(server))); + } + + /* This is here for the purpose of unit testing the final command that gets sent. */ + generateCommand(wireVersion: number): Document { + const command: Document = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly, + authorizedCollections: this.authorizedCollections + }; + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (wireVersion >= 9 && this.options.comment !== undefined) { + command.comment = this.options.comment; + } + + return command; + } +} + +/** @public */ +export interface CollectionInfo extends Document { + name: string; + type?: string; + options?: Document; + info?: { + readOnly?: false; + uuid?: Binary; + }; + idIndex?: Document; +} + +defineAspects(ListCollectionsOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.CURSOR_CREATING +]); diff --git a/nodejs/node_modules/mongodb/src/operations/list_databases.ts b/nodejs/node_modules/mongodb/src/operations/list_databases.ts new file mode 100644 index 00000000..6b7b269f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/list_databases.ts @@ -0,0 +1,70 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import { type TODO_NODE_3286 } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { maxWireVersion, MongoDBNamespace } from '../utils'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface ListDatabasesResult { + databases: ({ name: string; sizeOnDisk?: number; empty?: boolean } & Document)[]; + totalSize?: number; + totalSizeMb?: number; + ok: 1 | 0; +} + +/** @public */ +export interface ListDatabasesOptions extends CommandOperationOptions { + /** A query predicate that determines which databases are listed */ + filter?: Document; + /** A flag to indicate whether the command should return just the database names, or return both database names and size information */ + nameOnly?: boolean; + /** A flag that determines which databases are returned based on the user privileges when access control is enabled */ + authorizedDatabases?: boolean; +} + +/** @internal */ +export class ListDatabasesOperation extends CommandOperation { + override options: ListDatabasesOptions; + + constructor(db: Db, options?: ListDatabasesOptions) { + super(db, options); + this.options = options ?? {}; + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + override get commandName() { + return 'listDatabases' as const; + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const cmd: Document = { listDatabases: 1 }; + + if (typeof this.options.nameOnly === 'boolean') { + cmd.nameOnly = this.options.nameOnly; + } + + if (this.options.filter) { + cmd.filter = this.options.filter; + } + + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (maxWireVersion(server) >= 9 && this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + + return super.executeCommand(server, session, cmd) as TODO_NODE_3286; + } +} + +defineAspects(ListDatabasesOperation, [Aspect.READ_OPERATION, Aspect.RETRYABLE]); diff --git a/nodejs/node_modules/mongodb/src/operations/operation.ts b/nodejs/node_modules/mongodb/src/operations/operation.ts new file mode 100644 index 00000000..7f564cbc --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/operation.ts @@ -0,0 +1,125 @@ +import { type BSONSerializeOptions, type Document, resolveBSONOptions } from '../bson'; +import { ReadPreference, type ReadPreferenceLike } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import type { MongoDBNamespace } from '../utils'; + +export const Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING'), + MUST_SELECT_SAME_SERVER: Symbol('MUST_SELECT_SAME_SERVER') +} as const; + +/** @public */ +export type Hint = string | Document; + +// eslint-disable-next-line @typescript-eslint/ban-types +export interface OperationConstructor extends Function { + aspects?: Set; +} + +/** @public */ +export interface OperationOptions extends BSONSerializeOptions { + /** Specify ClientSession for this command */ + session?: ClientSession; + willRetryWrite?: boolean; + + /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */ + readPreference?: ReadPreferenceLike; + + /** @internal Hints to `executeOperation` that this operation should not unpin on an ended transaction */ + bypassPinningCheck?: boolean; + omitReadPreference?: boolean; +} + +/** @internal */ +const kSession = Symbol('session'); + +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect. + * @internal + */ +export abstract class AbstractOperation { + ns!: MongoDBNamespace; + readPreference: ReadPreference; + server!: Server; + bypassPinningCheck: boolean; + trySecondaryWrite: boolean; + + // BSON serialization options + bsonOptions?: BSONSerializeOptions; + + options: OperationOptions; + + [kSession]: ClientSession | undefined; + + constructor(options: OperationOptions = {}) { + this.readPreference = this.hasAspect(Aspect.WRITE_OPERATION) + ? ReadPreference.primary + : ReadPreference.fromOptions(options) ?? ReadPreference.primary; + + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = resolveBSONOptions(options); + + this[kSession] = options.session != null ? options.session : undefined; + + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + this.trySecondaryWrite = false; + } + + /** Must match the first key of the command object sent to the server. + Command name should be stateless (should not use 'this' keyword) */ + abstract get commandName(): string; + + abstract execute(server: Server, session: ClientSession | undefined): Promise; + + hasAspect(aspect: symbol): boolean { + const ctor = this.constructor as OperationConstructor; + if (ctor.aspects == null) { + return false; + } + + return ctor.aspects.has(aspect); + } + + get session(): ClientSession | undefined { + return this[kSession]; + } + + clearSession() { + this[kSession] = undefined; + } + + get canRetryRead(): boolean { + return true; + } + + get canRetryWrite(): boolean { + return true; + } +} + +export function defineAspects( + operation: OperationConstructor, + aspects: symbol | symbol[] | Set +): Set { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + + return aspects; +} diff --git a/nodejs/node_modules/mongodb/src/operations/options_operation.ts b/nodejs/node_modules/mongodb/src/operations/options_operation.ts new file mode 100644 index 00000000..c480fe07 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/options_operation.ts @@ -0,0 +1,35 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoAPIError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { AbstractOperation, type OperationOptions } from './operation'; + +/** @internal */ +export class OptionsOperation extends AbstractOperation { + override options: OperationOptions; + collection: Collection; + + constructor(collection: Collection, options: OperationOptions) { + super(options); + this.options = options; + this.collection = collection; + } + override get commandName() { + return 'listCollections' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const coll = this.collection; + const [collection] = await coll.s.db + .listCollections( + { name: coll.collectionName }, + { ...this.options, nameOnly: false, readPreference: this.readPreference, session } + ) + .toArray(); + if (collection == null || collection.options == null) { + throw new MongoAPIError(`collection ${coll.namespace} not found`); + } + return collection.options; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/profiling_level.ts b/nodejs/node_modules/mongodb/src/operations/profiling_level.ts new file mode 100644 index 00000000..383062c2 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/profiling_level.ts @@ -0,0 +1,35 @@ +import type { Db } from '../db'; +import { MongoUnexpectedServerResponseError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; + +/** @public */ +export type ProfilingLevelOptions = CommandOperationOptions; + +/** @internal */ +export class ProfilingLevelOperation extends CommandOperation { + override options: ProfilingLevelOptions; + + constructor(db: Db, options: ProfilingLevelOptions) { + super(db, options); + this.options = options; + } + + override get commandName() { + return 'profile' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const doc = await super.executeCommand(server, session, { profile: -1 }); + if (doc.ok === 1) { + const was = doc.was; + if (was === 0) return 'off'; + if (was === 1) return 'slow_only'; + if (was === 2) return 'all'; + throw new MongoUnexpectedServerResponseError(`Illegal profiling level value ${was}`); + } else { + throw new MongoUnexpectedServerResponseError('Error with profile command'); + } + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/remove_user.ts b/nodejs/node_modules/mongodb/src/operations/remove_user.ts new file mode 100644 index 00000000..ced8e4e1 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/remove_user.ts @@ -0,0 +1,31 @@ +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export type RemoveUserOptions = CommandOperationOptions; + +/** @internal */ +export class RemoveUserOperation extends CommandOperation { + override options: RemoveUserOptions; + username: string; + + constructor(db: Db, username: string, options: RemoveUserOptions) { + super(db, options); + this.options = options; + this.username = username; + } + + override get commandName() { + return 'dropUser' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + await super.executeCommand(server, session, { dropUser: this.username }); + return true; + } +} + +defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/rename.ts b/nodejs/node_modules/mongodb/src/operations/rename.ts new file mode 100644 index 00000000..a27d4afe --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/rename.ts @@ -0,0 +1,50 @@ +import type { Document } from '../bson'; +import { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { MongoDBNamespace } from '../utils'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface RenameOptions extends CommandOperationOptions { + /** Drop the target name collection if it previously exists. */ + dropTarget?: boolean; + /** Unclear */ + new_collection?: boolean; +} + +/** @internal */ +export class RenameOperation extends CommandOperation { + constructor( + public collection: Collection, + public newName: string, + public override options: RenameOptions + ) { + super(collection, options); + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + override get commandName(): string { + return 'renameCollection' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + // Build the command + const renameCollection = this.collection.namespace; + const toCollection = this.collection.s.namespace.withCollection(this.newName).toString(); + const dropTarget = + typeof this.options.dropTarget === 'boolean' ? this.options.dropTarget : false; + + const command = { + renameCollection: renameCollection, + to: toCollection, + dropTarget: dropTarget + }; + + await super.executeCommand(server, session, command); + return new Collection(this.collection.s.db, this.newName, this.collection.s.options); + } +} + +defineAspects(RenameOperation, [Aspect.WRITE_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/run_command.ts b/nodejs/node_modules/mongodb/src/operations/run_command.ts new file mode 100644 index 00000000..c288d266 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/run_command.ts @@ -0,0 +1,63 @@ +import type { BSONSerializeOptions, Document } from '../bson'; +import { type Db } from '../db'; +import { type TODO_NODE_3286 } from '../mongo_types'; +import type { ReadPreferenceLike } from '../read_preference'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { MongoDBNamespace } from '../utils'; +import { AbstractOperation } from './operation'; + +/** @public */ +export type RunCommandOptions = { + /** Specify ClientSession for this command */ + session?: ClientSession; + /** The read preference */ + readPreference?: ReadPreferenceLike; +} & BSONSerializeOptions; + +/** @internal */ +export class RunCommandOperation extends AbstractOperation { + constructor(parent: Db, public command: Document, public override options: RunCommandOptions) { + super(options); + this.ns = parent.s.namespace.withCollection('$cmd'); + } + + override get commandName() { + return 'runCommand' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + this.server = server; + return server.command(this.ns, this.command, { + ...this.options, + readPreference: this.readPreference, + session + }) as TODO_NODE_3286; + } +} + +export class RunAdminCommandOperation extends AbstractOperation { + constructor( + public command: Document, + public override options: RunCommandOptions & { + noResponse?: boolean; + bypassPinningCheck?: boolean; + } + ) { + super(options); + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + override get commandName() { + return 'runCommand' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + this.server = server; + return server.command(this.ns, this.command, { + ...this.options, + readPreference: this.readPreference, + session + }) as TODO_NODE_3286; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/search_indexes/create.ts b/nodejs/node_modules/mongodb/src/operations/search_indexes/create.ts new file mode 100644 index 00000000..054ba026 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/search_indexes/create.ts @@ -0,0 +1,44 @@ +import type { Document } from 'bson'; + +import type { Collection } from '../../collection'; +import type { Server } from '../../sdam/server'; +import type { ClientSession } from '../../sessions'; +import { AbstractOperation } from '../operation'; + +/** + * @public + */ +export interface SearchIndexDescription { + /** The name of the index. */ + name?: string; + + /** The index definition. */ + definition: Document; +} + +/** @internal */ +export class CreateSearchIndexesOperation extends AbstractOperation { + constructor( + private readonly collection: Collection, + private readonly descriptions: ReadonlyArray + ) { + super(); + } + + override get commandName() { + return 'createSearchIndexes' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const namespace = this.collection.fullNamespace; + const command = { + createSearchIndexes: namespace.collection, + indexes: this.descriptions + }; + + const res = await server.command(namespace, command, { session }); + + const indexesCreated: Array<{ name: string }> = res?.indexesCreated ?? []; + return indexesCreated.map(({ name }) => name); + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/search_indexes/drop.ts b/nodejs/node_modules/mongodb/src/operations/search_indexes/drop.ts new file mode 100644 index 00000000..05a56f1c --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/search_indexes/drop.ts @@ -0,0 +1,40 @@ +import type { Document } from 'bson'; + +import type { Collection } from '../../collection'; +import { MONGODB_ERROR_CODES, MongoServerError } from '../../error'; +import type { Server } from '../../sdam/server'; +import type { ClientSession } from '../../sessions'; +import { AbstractOperation } from '../operation'; + +/** @internal */ +export class DropSearchIndexOperation extends AbstractOperation { + constructor(private readonly collection: Collection, private readonly name: string) { + super(); + } + + override get commandName() { + return 'dropSearchIndex' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const namespace = this.collection.fullNamespace; + + const command: Document = { + dropSearchIndex: namespace.collection + }; + + if (typeof this.name === 'string') { + command.name = this.name; + } + + try { + await server.command(namespace, command, { session }); + } catch (error) { + const isNamespaceNotFoundError = + error instanceof MongoServerError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound; + if (!isNamespaceNotFoundError) { + throw error; + } + } + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/search_indexes/update.ts b/nodejs/node_modules/mongodb/src/operations/search_indexes/update.ts new file mode 100644 index 00000000..aad7f935 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/search_indexes/update.ts @@ -0,0 +1,33 @@ +import type { Document } from 'bson'; + +import type { Collection } from '../../collection'; +import type { Server } from '../../sdam/server'; +import type { ClientSession } from '../../sessions'; +import { AbstractOperation } from '../operation'; + +/** @internal */ +export class UpdateSearchIndexOperation extends AbstractOperation { + constructor( + private readonly collection: Collection, + private readonly name: string, + private readonly definition: Document + ) { + super(); + } + + override get commandName() { + return 'updateSearchIndex' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const namespace = this.collection.fullNamespace; + const command = { + updateSearchIndex: namespace.collection, + name: this.name, + definition: this.definition + }; + + await server.command(namespace, command, { session }); + return; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/set_profiling_level.ts b/nodejs/node_modules/mongodb/src/operations/set_profiling_level.ts new file mode 100644 index 00000000..9969b2ea --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/set_profiling_level.ts @@ -0,0 +1,70 @@ +import type { Db } from '../db'; +import { MongoInvalidArgumentError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { enumToString } from '../utils'; +import { CommandOperation, type CommandOperationOptions } from './command'; + +const levelValues = new Set(['off', 'slow_only', 'all']); + +/** @public */ +export const ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +} as const); + +/** @public */ +export type ProfilingLevel = (typeof ProfilingLevel)[keyof typeof ProfilingLevel]; + +/** @public */ +export type SetProfilingLevelOptions = CommandOperationOptions; + +/** @internal */ +export class SetProfilingLevelOperation extends CommandOperation { + override options: SetProfilingLevelOptions; + level: ProfilingLevel; + profile: 0 | 1 | 2; + + constructor(db: Db, level: ProfilingLevel, options: SetProfilingLevelOptions) { + super(db, options); + this.options = options; + switch (level) { + case ProfilingLevel.off: + this.profile = 0; + break; + case ProfilingLevel.slowOnly: + this.profile = 1; + break; + case ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; + } + + this.level = level; + } + + override get commandName() { + return 'profile' as const; + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const level = this.level; + + if (!levelValues.has(level)) { + throw new MongoInvalidArgumentError( + `Profiling level must be one of "${enumToString(ProfilingLevel)}"` + ); + } + + // TODO(NODE-3483): Determine error to put here + await super.executeCommand(server, session, { profile: this.profile }); + return level; + } +} diff --git a/nodejs/node_modules/mongodb/src/operations/stats.ts b/nodejs/node_modules/mongodb/src/operations/stats.ts new file mode 100644 index 00000000..11b87f25 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/stats.ts @@ -0,0 +1,37 @@ +import type { Document } from '../bson'; +import type { Db } from '../db'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects } from './operation'; + +/** @public */ +export interface DbStatsOptions extends CommandOperationOptions { + /** Divide the returned sizes by scale value. */ + scale?: number; +} + +/** @internal */ +export class DbStatsOperation extends CommandOperation { + override options: DbStatsOptions; + + constructor(db: Db, options: DbStatsOptions) { + super(db, options); + this.options = options; + } + + override get commandName() { + return 'dbStats' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const command: Document = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; + } + + return super.executeCommand(server, session, command); + } +} + +defineAspects(DbStatsOperation, [Aspect.READ_OPERATION]); diff --git a/nodejs/node_modules/mongodb/src/operations/update.ts b/nodejs/node_modules/mongodb/src/operations/update.ts new file mode 100644 index 00000000..b1f73f83 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/update.ts @@ -0,0 +1,303 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { MongoCompatibilityError, MongoInvalidArgumentError, MongoServerError } from '../error'; +import type { InferIdType, TODO_NODE_3286 } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { hasAtomicOperators, type MongoDBNamespace } from '../utils'; +import { type CollationOptions, CommandOperation, type CommandOperationOptions } from './command'; +import { Aspect, defineAspects, type Hint } from './operation'; + +/** @public */ +export interface UpdateOptions extends CommandOperationOptions { + /** A set of filters specifying to which array elements an update should apply */ + arrayFilters?: Document[]; + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: Hint; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** + * @public + * `TSchema` is the schema of the collection + */ +export interface UpdateResult { + /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */ + acknowledged: boolean; + /** The number of documents that matched the filter */ + matchedCount: number; + /** The number of documents that were modified */ + modifiedCount: number; + /** The number of documents that were upserted */ + upsertedCount: number; + /** The identifier of the inserted document if an upsert took place */ + upsertedId: InferIdType | null; +} + +/** @public */ +export interface UpdateStatement { + /** The query that matches documents to update. */ + q: Document; + /** The modifications to apply. */ + u: Document | Document[]; + /** If true, perform an insert if no documents match the query. */ + upsert?: boolean; + /** If true, updates all documents that meet the query criteria. */ + multi?: boolean; + /** Specifies the collation to use for the operation. */ + collation?: CollationOptions; + /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */ + arrayFilters?: Document[]; + /** A document or string that specifies the index to use to support the query predicate. */ + hint?: Hint; +} + +/** + * @internal + * UpdateOperation is used in bulk write, while UpdateOneOperation and UpdateManyOperation are only used in the collections API + */ +export class UpdateOperation extends CommandOperation { + override options: UpdateOptions & { ordered?: boolean }; + statements: UpdateStatement[]; + + constructor( + ns: MongoDBNamespace, + statements: UpdateStatement[], + options: UpdateOptions & { ordered?: boolean } + ) { + super(undefined, options); + this.options = options; + this.ns = ns; + + this.statements = statements; + } + + override get commandName() { + return 'update' as const; + } + + override get canRetryWrite(): boolean { + if (super.canRetryWrite === false) { + return false; + } + + return this.statements.every(op => op.multi == null || op.multi === false); + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const options = this.options ?? {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command: Document = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (options.let) { + command.let = options.let; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (options.comment !== undefined) { + command.comment = options.comment; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o: Document) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + throw new MongoCompatibilityError(`hint is not supported with unacknowledged writes`); + } + } + + return super.executeCommand(server, session, command); + } +} + +/** @internal */ +export class UpdateOneOperation extends UpdateOperation { + constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, update, { ...options, multi: false })], + options + ); + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const res = await super.execute(server, session); + if (this.explain != null) return res as TODO_NODE_3286; + if (res.code) throw new MongoServerError(res); + if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]); + + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; + } +} + +/** @internal */ +export class UpdateManyOperation extends UpdateOperation { + constructor(collection: Collection, filter: Document, update: Document, options: UpdateOptions) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, update, { ...options, multi: true })], + options + ); + + if (!hasAtomicOperators(update)) { + throw new MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const res = await super.execute(server, session); + if (this.explain != null) return res as TODO_NODE_3286; + if (res.code) throw new MongoServerError(res); + if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]); + + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; + } +} + +/** @public */ +export interface ReplaceOptions extends CommandOperationOptions { + /** If true, allows the write to opt-out of document level validation */ + bypassDocumentValidation?: boolean; + /** Specifies a collation */ + collation?: CollationOptions; + /** Specify that the update query should only consider plans using the hinted index */ + hint?: string | Document; + /** When true, creates a new document if no document matches the query */ + upsert?: boolean; + /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */ + let?: Document; +} + +/** @internal */ +export class ReplaceOneOperation extends UpdateOperation { + constructor( + collection: Collection, + filter: Document, + replacement: Document, + options: ReplaceOptions + ) { + super( + collection.s.namespace, + [makeUpdateStatement(filter, replacement, { ...options, multi: false })], + options + ); + + if (hasAtomicOperators(replacement)) { + throw new MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + + override async execute( + server: Server, + session: ClientSession | undefined + ): Promise { + const res = await super.execute(server, session); + if (this.explain != null) return res as TODO_NODE_3286; + if (res.code) throw new MongoServerError(res); + if (res.writeErrors) throw new MongoServerError(res.writeErrors[0]); + + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: + Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; + } +} + +export function makeUpdateStatement( + filter: Document, + update: Document | Document[], + options: UpdateOptions & { multi?: boolean } +): UpdateStatement { + if (filter == null || typeof filter !== 'object') { + throw new MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + + if (update == null || typeof update !== 'object') { + throw new MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + + const op: UpdateStatement = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + + if (options.multi) { + op.multi = options.multi; + } + + if (options.hint) { + op.hint = options.hint; + } + + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + + if (options.collation) { + op.collation = options.collation; + } + + return op; +} + +defineAspects(UpdateOperation, [Aspect.RETRYABLE, Aspect.WRITE_OPERATION, Aspect.SKIP_COLLATION]); +defineAspects(UpdateOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(UpdateManyOperation, [ + Aspect.WRITE_OPERATION, + Aspect.EXPLAINABLE, + Aspect.SKIP_COLLATION +]); +defineAspects(ReplaceOneOperation, [ + Aspect.RETRYABLE, + Aspect.WRITE_OPERATION, + Aspect.SKIP_COLLATION +]); diff --git a/nodejs/node_modules/mongodb/src/operations/validate_collection.ts b/nodejs/node_modules/mongodb/src/operations/validate_collection.ts new file mode 100644 index 00000000..4880a703 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/operations/validate_collection.ts @@ -0,0 +1,53 @@ +import type { Admin } from '../admin'; +import type { Document } from '../bson'; +import { MongoUnexpectedServerResponseError } from '../error'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { CommandOperation, type CommandOperationOptions } from './command'; + +/** @public */ +export interface ValidateCollectionOptions extends CommandOperationOptions { + /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */ + background?: boolean; +} + +/** @internal */ +export class ValidateCollectionOperation extends CommandOperation { + override options: ValidateCollectionOptions; + collectionName: string; + command: Document; + + constructor(admin: Admin, collectionName: string, options: ValidateCollectionOptions) { + // Decorate command with extra options + const command: Document = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = (options as Document)[keys[i]]; + } + } + + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + + override get commandName() { + return 'validate' as const; + } + + override async execute(server: Server, session: ClientSession | undefined): Promise { + const collectionName = this.collectionName; + + const doc = await super.executeCommand(server, session, this.command); + if (doc.result != null && typeof doc.result !== 'string') + throw new MongoUnexpectedServerResponseError('Error with validation data'); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + throw new MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`); + if (doc.valid != null && !doc.valid) + throw new MongoUnexpectedServerResponseError(`Invalid collection ${collectionName}`); + + return doc; + } +} diff --git a/nodejs/node_modules/mongodb/src/read_concern.ts b/nodejs/node_modules/mongodb/src/read_concern.ts new file mode 100644 index 00000000..93c5688a --- /dev/null +++ b/nodejs/node_modules/mongodb/src/read_concern.ts @@ -0,0 +1,88 @@ +import type { Document } from './bson'; + +/** @public */ +export const ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +} as const); + +/** @public */ +export type ReadConcernLevel = (typeof ReadConcernLevel)[keyof typeof ReadConcernLevel]; + +/** @public */ +export type ReadConcernLike = ReadConcern | { level: ReadConcernLevel } | ReadConcernLevel; + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html + */ +export class ReadConcern { + level: ReadConcernLevel | string; + + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level: ReadConcernLevel) { + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = ReadConcernLevel[level] ?? level; + } + + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options?: { + readConcern?: ReadConcernLike; + level?: ReadConcernLevel; + }): ReadConcern | undefined { + if (options == null) { + return; + } + + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + + if (options.level) { + return new ReadConcern(options.level); + } + return; + } + + static get MAJORITY(): 'majority' { + return ReadConcernLevel.majority; + } + + static get AVAILABLE(): 'available' { + return ReadConcernLevel.available; + } + + static get LINEARIZABLE(): 'linearizable' { + return ReadConcernLevel.linearizable; + } + + static get SNAPSHOT(): 'snapshot' { + return ReadConcernLevel.snapshot; + } + + toJSON(): Document { + return { level: this.level }; + } +} diff --git a/nodejs/node_modules/mongodb/src/read_preference.ts b/nodejs/node_modules/mongodb/src/read_preference.ts new file mode 100644 index 00000000..cef52ad4 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/read_preference.ts @@ -0,0 +1,262 @@ +import type { Document } from './bson'; +import { MongoInvalidArgumentError } from './error'; +import type { TagSet } from './sdam/server_description'; +import type { ClientSession } from './sessions'; + +/** @public */ +export type ReadPreferenceLike = ReadPreference | ReadPreferenceMode; + +/** @public */ +export const ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +} as const); + +/** @public */ +export type ReadPreferenceMode = (typeof ReadPreferenceMode)[keyof typeof ReadPreferenceMode]; + +/** @public */ +export interface HedgeOptions { + /** Explicitly enable or disable hedged reads. */ + enabled?: boolean; +} + +/** @public */ +export interface ReadPreferenceOptions { + /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/ + maxStalenessSeconds?: number; + /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */ + hedge?: HedgeOptions; +} + +/** @public */ +export interface ReadPreferenceLikeOptions extends ReadPreferenceOptions { + readPreference?: + | ReadPreferenceLike + | { + mode?: ReadPreferenceMode; + preference?: ReadPreferenceMode; + tags?: TagSet[]; + maxStalenessSeconds?: number; + }; +} + +/** @public */ +export interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions { + session?: ClientSession; + readPreferenceTags?: TagSet[]; + hedge?: HedgeOptions; +} + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://www.mongodb.com/docs/manual/core/read-preference/ + */ +export class ReadPreference { + mode: ReadPreferenceMode; + tags?: TagSet[]; + hedge?: HedgeOptions; + maxStalenessSeconds?: number; + minWireVersion?: number; + + public static PRIMARY = ReadPreferenceMode.primary; + public static PRIMARY_PREFERRED = ReadPreferenceMode.primaryPreferred; + public static SECONDARY = ReadPreferenceMode.secondary; + public static SECONDARY_PREFERRED = ReadPreferenceMode.secondaryPreferred; + public static NEAREST = ReadPreferenceMode.nearest; + + public static primary = new ReadPreference(ReadPreferenceMode.primary); + public static primaryPreferred = new ReadPreference(ReadPreferenceMode.primaryPreferred); + public static secondary = new ReadPreference(ReadPreferenceMode.secondary); + public static secondaryPreferred = new ReadPreference(ReadPreferenceMode.secondaryPreferred); + public static nearest = new ReadPreference(ReadPreferenceMode.nearest); + + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions) { + if (!ReadPreference.isValid(mode)) { + throw new MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } else if (tags && !Array.isArray(tags)) { + throw new MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + + this.mode = mode; + this.tags = tags; + this.hedge = options?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + + options = options ?? {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new MongoInvalidArgumentError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new MongoInvalidArgumentError( + 'Primary read preference cannot be combined with maxStalenessSeconds' + ); + } + + if (this.hedge) { + throw new MongoInvalidArgumentError( + 'Primary read preference cannot be combined with hedge' + ); + } + } + } + + // Support the deprecated `preference` property introduced in the porcelain layer + get preference(): ReadPreferenceMode { + return this.mode; + } + + static fromString(mode: string): ReadPreference { + return new ReadPreference(mode as ReadPreferenceMode); + } + + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined { + if (!options) return; + const readPreference = + options.readPreference ?? options.session?.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + + if (readPreference == null) { + return; + } + + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags, { + maxStalenessSeconds: options.maxStalenessSeconds, + hedge: options.hedge + }); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, readPreference.tags ?? readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } + } + + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; + } + + return readPreference as ReadPreference; + } + + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions { + if (options.readPreference == null) return options; + const r = options.readPreference; + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new MongoInvalidArgumentError(`Invalid read preference: ${r}`); + } + + return options; + } + + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode: string): boolean { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + + return VALID_MODES.has(mode as ReadPreferenceMode); + } + + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode?: string): boolean { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + + /** + * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire + * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query + */ + secondaryOk(): boolean { + const NEEDS_SECONDARYOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + + return NEEDS_SECONDARYOK.has(this.mode); + } + + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference: ReadPreference): boolean { + return readPreference.mode === this.mode; + } + + /** Return JSON representation */ + toJSON(): Document { + const readPreference = { mode: this.mode } as Document; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) readPreference.hedge = this.hedge; + return readPreference; + } +} diff --git a/nodejs/node_modules/mongodb/src/sdam/common.ts b/nodejs/node_modules/mongodb/src/sdam/common.ts new file mode 100644 index 00000000..e4b84d83 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/common.ts @@ -0,0 +1,79 @@ +import { clearTimeout } from 'timers'; + +import type { Binary, Long, Timestamp } from '../bson'; +import type { ClientSession } from '../sessions'; +import type { Topology } from './topology'; + +// shared state names +export const STATE_CLOSING = 'closing'; +export const STATE_CLOSED = 'closed'; +export const STATE_CONNECTING = 'connecting'; +export const STATE_CONNECTED = 'connected'; + +/** + * An enumeration of topology types we know about + * @public + */ +export const TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +} as const); + +/** @public */ +export type TopologyType = (typeof TopologyType)[keyof typeof TopologyType]; + +/** + * An enumeration of server types we know about + * @public + */ +export const ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +} as const); + +/** @public */ +export type ServerType = (typeof ServerType)[keyof typeof ServerType]; + +/** @internal */ +export type TimerQueue = Set; + +/** @internal */ +export function drainTimerQueue(queue: TimerQueue): void { + queue.forEach(clearTimeout); + queue.clear(); +} + +/** @public */ +export interface ClusterTime { + clusterTime: Timestamp; + signature: { + hash: Binary; + keyId: Long; + }; +} + +/** Shared function to determine clusterTime for a given topology or session */ +export function _advanceClusterTime( + entity: Topology | ClientSession, + $clusterTime: ClusterTime +): void { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; + } + } +} diff --git a/nodejs/node_modules/mongodb/src/sdam/events.ts b/nodejs/node_modules/mongodb/src/sdam/events.ts new file mode 100644 index 00000000..64cb6ffb --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/events.ts @@ -0,0 +1,219 @@ +import type { Document } from '../bson'; +import { + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + SERVER_HEARTBEAT_FAILED, + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED, + SERVER_OPENING, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING +} from '../constants'; +import type { ServerDescription } from './server_description'; +import type { TopologyDescription } from './topology_description'; + +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +export class ServerDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** The previous server description */ + previousDescription: ServerDescription; + /** The new server description */ + newDescription: ServerDescription; + name = SERVER_DESCRIPTION_CHANGED; + + /** @internal */ + constructor( + topologyId: number, + address: string, + previousDescription: ServerDescription, + newDescription: ServerDescription + ) { + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} + +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +export class ServerOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** @internal */ + name = SERVER_OPENING; + + /** @internal */ + constructor(topologyId: number, address: string) { + this.topologyId = topologyId; + this.address = address; + } +} + +/** + * Emitted when server is closed. + * @public + * @category Event + */ +export class ServerClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The address (host/port pair) of the server */ + address: string; + /** @internal */ + name = SERVER_CLOSED; + + /** @internal */ + constructor(topologyId: number, address: string) { + this.topologyId = topologyId; + this.address = address; + } +} + +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +export class TopologyDescriptionChangedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** The old topology description */ + previousDescription: TopologyDescription; + /** The new topology description */ + newDescription: TopologyDescription; + /** @internal */ + name = TOPOLOGY_DESCRIPTION_CHANGED; + + /** @internal */ + constructor( + topologyId: number, + previousDescription: TopologyDescription, + newDescription: TopologyDescription + ) { + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} + +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +export class TopologyOpeningEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** @internal */ + name = TOPOLOGY_OPENING; + + /** @internal */ + constructor(topologyId: number) { + this.topologyId = topologyId; + } +} + +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +export class TopologyClosedEvent { + /** A unique identifier for the topology */ + topologyId: number; + /** @internal */ + name = TOPOLOGY_CLOSED; + + /** @internal */ + constructor(topologyId: number) { + this.topologyId = topologyId; + } +} + +/** + * Emitted when the server monitor’s hello command is started - immediately before + * the hello command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +export class ServerHeartbeatStartedEvent { + /** The connection id for the command */ + connectionId: string; + /** Is true when using the streaming protocol */ + awaited: boolean; + /** @internal */ + name = SERVER_HEARTBEAT_STARTED; + + /** @internal */ + constructor(connectionId: string, awaited: boolean) { + this.connectionId = connectionId; + this.awaited = awaited; + } +} + +/** + * Emitted when the server monitor’s hello succeeds. + * @public + * @category Event + */ +export class ServerHeartbeatSucceededEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command reply */ + reply: Document; + /** Is true when using the streaming protocol */ + awaited: boolean; + /** @internal */ + name = SERVER_HEARTBEAT_SUCCEEDED; + + /** @internal */ + constructor(connectionId: string, duration: number, reply: Document | null, awaited: boolean) { + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply ?? {}; + this.awaited = awaited; + } +} + +/** + * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +export class ServerHeartbeatFailedEvent { + /** The connection id for the command */ + connectionId: string; + /** The execution time of the event in ms */ + duration: number; + /** The command failure */ + failure: Error; + /** Is true when using the streaming protocol */ + awaited: boolean; + /** @internal */ + name = SERVER_HEARTBEAT_FAILED; + + /** @internal */ + constructor(connectionId: string, duration: number, failure: Error, awaited: boolean) { + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + this.awaited = awaited; + } +} diff --git a/nodejs/node_modules/mongodb/src/sdam/monitor.ts b/nodejs/node_modules/mongodb/src/sdam/monitor.ts new file mode 100644 index 00000000..cdd0a511 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/monitor.ts @@ -0,0 +1,664 @@ +import { clearTimeout, setTimeout } from 'timers'; + +import { type Document, Long } from '../bson'; +import { connect, makeConnection, makeSocket, performInitialHandshake } from '../cmap/connect'; +import type { Connection, ConnectionOptions } from '../cmap/connection'; +import { getFAASEnv } from '../cmap/handshake/client_metadata'; +import { LEGACY_HELLO_COMMAND } from '../constants'; +import { MongoError, MongoErrorLabel, MongoNetworkTimeoutError } from '../error'; +import { MongoLoggableComponent } from '../mongo_logger'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Callback, EventEmitterWithState } from '../utils'; +import { calculateDurationInMs, makeStateMachine, now, ns } from '../utils'; +import { ServerType, STATE_CLOSED, STATE_CLOSING } from './common'; +import { + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent +} from './events'; +import { Server } from './server'; +import type { TopologyVersion } from './server_description'; + +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); + +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = makeStateMachine({ + [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED], + [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] +}); + +const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor: Monitor) { + return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING; +} + +/** @public */ +export const ServerMonitoringMode = Object.freeze({ + auto: 'auto', + poll: 'poll', + stream: 'stream' +} as const); + +/** @public */ +export type ServerMonitoringMode = (typeof ServerMonitoringMode)[keyof typeof ServerMonitoringMode]; + +/** @internal */ +export interface MonitorPrivate { + state: string; +} + +/** @public */ +export interface MonitorOptions + extends Omit { + connectTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + serverMonitoringMode: ServerMonitoringMode; +} + +/** @public */ +export type MonitorEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + resetServer(error?: MongoError): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/** @internal */ +export class Monitor extends TypedEventEmitter { + /** @internal */ + s: MonitorPrivate; + address: string; + options: Readonly< + Pick< + MonitorOptions, + | 'connectTimeoutMS' + | 'heartbeatFrequencyMS' + | 'minHeartbeatFrequencyMS' + | 'serverMonitoringMode' + > + >; + connectOptions: ConnectionOptions; + isRunningInFaasEnv: boolean; + [kServer]: Server; + connection: Connection | null; + [kCancellationToken]: CancellationToken; + /** @internal */ + [kMonitorId]?: MonitorInterval; + rttPinger?: RTTPinger; + /** @internal */ + override component = MongoLoggableComponent.TOPOLOGY; + + constructor(server: Server, options: MonitorOptions) { + super(); + + this[kServer] = server; + this.connection = null; + this[kCancellationToken] = new CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: STATE_CLOSED + }; + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: options.connectTimeoutMS ?? 10000, + heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500, + serverMonitoringMode: options.serverMonitoringMode + }); + this.isRunningInFaasEnv = getFAASEnv() != null; + this.mongoLogger = this[kServer].topology.client?.mongoLogger; + + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = { + id: '' as const, + generation: server.pool.generation, + cancellationToken, + hostAddress: server.description.hostAddress, + ...options, + // force BSON serialization options + raw: false, + useBigInt64: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + }; + + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; + } + + this.connectOptions = Object.freeze(connectOptions); + } + + connect(): void { + if (this.s.state !== STATE_CLOSED) { + return; + } + + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: minHeartbeatFrequencyMS, + immediate: true + }); + } + + requestCheck(): void { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + + this[kMonitorId]?.wake(); + } + + reset(): void { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // restart monitor + stateTransition(this, STATE_IDLE); + + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: minHeartbeatFrequencyMS + }); + } + + close(): void { + if (isInCloseState(this)) { + return; + } + + stateTransition(this, STATE_CLOSING); + resetMonitorState(this); + + // close monitor + this.emit('close'); + stateTransition(this, STATE_CLOSED); + } +} + +function resetMonitorState(monitor: Monitor) { + monitor[kMonitorId]?.stop(); + monitor[kMonitorId] = undefined; + + monitor.rttPinger?.close(); + monitor.rttPinger = undefined; + + monitor[kCancellationToken].emit('cancel'); + + monitor.connection?.destroy(); + monitor.connection = null; +} + +function useStreamingProtocol(monitor: Monitor, topologyVersion: TopologyVersion | null): boolean { + // If we have no topology version we always poll no matter + // what the user provided, since the server does not support + // the streaming protocol. + if (topologyVersion == null) return false; + + const serverMonitoringMode = monitor.options.serverMonitoringMode; + if (serverMonitoringMode === ServerMonitoringMode.poll) return false; + if (serverMonitoringMode === ServerMonitoringMode.stream) return true; + + // If we are in auto mode, we need to figure out if we're in a FaaS + // environment or not and choose the appropriate mode. + if (monitor.isRunningInFaasEnv) return false; + return true; +} + +function checkServer(monitor: Monitor, callback: Callback) { + let start: number; + let awaited: boolean; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = useStreamingProtocol(monitor, topologyVersion); + monitor.emitAndLogHeartbeat( + Server.SERVER_HEARTBEAT_STARTED, + monitor[kServer].topology.s.id, + undefined, + new ServerHeartbeatStartedEvent(monitor.address, isAwaitable) + ); + + function onHeartbeatFailed(err: Error) { + monitor.connection?.destroy(); + monitor.connection = null; + + monitor.emitAndLogHeartbeat( + Server.SERVER_HEARTBEAT_FAILED, + monitor[kServer].topology.s.id, + undefined, + new ServerHeartbeatFailedEvent(monitor.address, calculateDurationInMs(start), err, awaited) + ); + + const error = !(err instanceof MongoError) + ? new MongoError(MongoError.buildErrorMessage(err), { cause: err }) + : err; + error.addErrorLabel(MongoErrorLabel.ResetPool); + if (error instanceof MongoNetworkTimeoutError) { + error.addErrorLabel(MongoErrorLabel.InterruptInUseConnections); + } + + monitor.emit('resetServer', error); + callback(err); + } + + function onHeartbeatSucceeded(hello: Document) { + if (!('isWritablePrimary' in hello)) { + // Provide hello-style response document. + hello.isWritablePrimary = hello[LEGACY_HELLO_COMMAND]; + } + + const duration = + isAwaitable && monitor.rttPinger + ? monitor.rttPinger.roundTripTime + : calculateDurationInMs(start); + + monitor.emitAndLogHeartbeat( + Server.SERVER_HEARTBEAT_SUCCEEDED, + monitor[kServer].topology.s.id, + hello.connectionId, + new ServerHeartbeatSucceededEvent(monitor.address, duration, hello, isAwaitable) + ); + + if (isAwaitable) { + // If we are using the streaming protocol then we immediately issue another 'started' + // event, otherwise the "check" is complete and return to the main monitor loop + monitor.emitAndLogHeartbeat( + Server.SERVER_HEARTBEAT_STARTED, + monitor[kServer].topology.s.id, + undefined, + new ServerHeartbeatStartedEvent(monitor.address, true) + ); + // We have not actually sent an outgoing handshake, but when we get the next response we + // want the duration to reflect the time since we last heard from the server + start = now(); + } else { + monitor.rttPinger?.close(); + monitor.rttPinger = undefined; + + callback(undefined, hello); + } + } + + const { connection } = monitor; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + + const cmd = { + [serverApi?.version || helloOk ? 'hello' : LEGACY_HELLO_COMMAND]: 1, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + + if (isAwaitable && monitor.rttPinger == null) { + monitor.rttPinger = new RTTPinger( + monitor[kCancellationToken], + Object.assign( + { heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, + monitor.connectOptions + ) + ); + } + + // Record new start time before sending handshake + start = now(); + + if (isAwaitable) { + awaited = true; + return connection.exhaustCommand(ns('admin.$cmd'), cmd, options, (error, hello) => { + if (error) return onHeartbeatFailed(error); + return onHeartbeatSucceeded(hello); + }); + } + + awaited = false; + connection + .command(ns('admin.$cmd'), cmd, options) + .then(onHeartbeatSucceeded, onHeartbeatFailed); + + return; + } + + // connecting does an implicit `hello` + (async () => { + const socket = await makeSocket(monitor.connectOptions); + const connection = makeConnection(monitor.connectOptions, socket); + // The start time is after socket creation but before the handshake + start = now(); + try { + await performInitialHandshake(connection, monitor.connectOptions); + return connection; + } catch (error) { + connection.destroy(); + throw error; + } + })().then( + connection => { + if (isInCloseState(monitor)) { + connection.destroy(); + return; + } + + monitor.connection = connection; + monitor.emitAndLogHeartbeat( + Server.SERVER_HEARTBEAT_SUCCEEDED, + monitor[kServer].topology.s.id, + connection.hello?.connectionId, + new ServerHeartbeatSucceededEvent( + monitor.address, + calculateDurationInMs(start), + connection.hello, + useStreamingProtocol(monitor, connection.hello?.topologyVersion) + ) + ); + + callback(undefined, connection.hello); + }, + error => { + monitor.connection = null; + awaited = false; + onHeartbeatFailed(error); + } + ); +} + +function monitorServer(monitor: Monitor) { + return (callback: Callback) => { + if (monitor.s.state === STATE_MONITORING) { + process.nextTick(callback); + return; + } + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + + callback(); + } + + checkServer(monitor, (err, hello) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === ServerType.Unknown) { + return done(); + } + } + + // if the check indicates streaming is supported, immediately reschedule monitoring + if (useStreamingProtocol(monitor, hello?.topologyVersion)) { + setTimeout(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId]?.wake(); + } + }, 0); + } + + done(); + }); + }; +} + +function makeTopologyVersion(tv: TopologyVersion) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + // TODO(NODE-2674): Preserve int64 sent from MongoDB + counter: Long.isLong(tv.counter) ? tv.counter : Long.fromNumber(tv.counter) + }; +} + +/** @internal */ +export interface RTTPingerOptions extends ConnectionOptions { + heartbeatFrequencyMS: number; +} + +/** @internal */ +export class RTTPinger { + connection?: Connection; + /** @internal */ + [kCancellationToken]: CancellationToken; + /** @internal */ + [kRoundTripTime]: number; + /** @internal */ + [kMonitorId]: NodeJS.Timeout; + closed: boolean; + + constructor(cancellationToken: CancellationToken, options: RTTPingerOptions) { + this.connection = undefined; + this[kCancellationToken] = cancellationToken; + this[kRoundTripTime] = 0; + this.closed = false; + + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + this[kMonitorId] = setTimeout(() => measureRoundTripTime(this, options), heartbeatFrequencyMS); + } + + get roundTripTime(): number { + return this[kRoundTripTime]; + } + + close(): void { + this.closed = true; + clearTimeout(this[kMonitorId]); + + this.connection?.destroy(); + this.connection = undefined; + } +} + +function measureRoundTripTime(rttPinger: RTTPinger, options: RTTPingerOptions) { + const start = now(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + + if (rttPinger.closed) { + return; + } + + function measureAndReschedule(conn?: Connection) { + if (rttPinger.closed) { + conn?.destroy(); + return; + } + + if (rttPinger.connection == null) { + rttPinger.connection = conn; + } + + rttPinger[kRoundTripTime] = calculateDurationInMs(start); + rttPinger[kMonitorId] = setTimeout( + () => measureRoundTripTime(rttPinger, options), + heartbeatFrequencyMS + ); + } + + const connection = rttPinger.connection; + if (connection == null) { + connect(options).then( + connection => { + measureAndReschedule(connection); + }, + () => { + rttPinger.connection = undefined; + rttPinger[kRoundTripTime] = 0; + } + ); + return; + } + + const commandName = + connection.serverApi?.version || connection.helloOk ? 'hello' : LEGACY_HELLO_COMMAND; + connection.command(ns('admin.$cmd'), { [commandName]: 1 }, undefined).then( + () => measureAndReschedule(), + () => { + rttPinger.connection?.destroy(); + rttPinger.connection = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + ); +} + +/** + * @internal + */ +export interface MonitorIntervalOptions { + /** The interval to execute a method on */ + heartbeatFrequencyMS: number; + /** A minimum interval that must elapse before the method is called */ + minHeartbeatFrequencyMS: number; + /** Whether the method should be called immediately when the interval is started */ + immediate: boolean; +} + +/** + * @internal + */ +export class MonitorInterval { + fn: (callback: Callback) => void; + timerId: NodeJS.Timeout | undefined; + lastExecutionEnded: number; + isExpeditedCallToFnScheduled = false; + stopped = false; + isExecutionInProgress = false; + hasExecutedOnce = false; + + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + + constructor(fn: (callback: Callback) => void, options: Partial = {}) { + this.fn = fn; + this.lastExecutionEnded = -Infinity; + + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000; + this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; + + if (options.immediate) { + this._executeAndReschedule(); + } else { + this._reschedule(undefined); + } + } + + wake() { + const currentTime = now(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + + // TODO(NODE-4674): Add error handling and logging to the monitor + if (timeSinceLastCall < 0) { + return this._executeAndReschedule(); + } + + if (this.isExecutionInProgress) { + return; + } + + // debounce multiple calls to wake within the `minInterval` + if (this.isExpeditedCallToFnScheduled) { + return; + } + + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { + this.isExpeditedCallToFnScheduled = true; + this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); + return; + } + + this._executeAndReschedule(); + } + + stop() { + this.stopped = true; + if (this.timerId) { + clearTimeout(this.timerId); + this.timerId = undefined; + } + + this.lastExecutionEnded = -Infinity; + this.isExpeditedCallToFnScheduled = false; + } + + toString() { + return JSON.stringify(this); + } + + toJSON() { + const currentTime = now(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + return { + timerId: this.timerId != null ? 'set' : 'cleared', + lastCallTime: this.lastExecutionEnded, + isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, + stopped: this.stopped, + heartbeatFrequencyMS: this.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, + currentTime, + timeSinceLastCall + }; + } + + private _reschedule(ms?: number) { + if (this.stopped) return; + if (this.timerId) { + clearTimeout(this.timerId); + } + + this.timerId = setTimeout(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); + } + + private _executeAndReschedule = () => { + if (this.stopped) return; + if (this.timerId) { + clearTimeout(this.timerId); + } + + this.isExpeditedCallToFnScheduled = false; + this.isExecutionInProgress = true; + + this.fn(() => { + this.lastExecutionEnded = now(); + this.isExecutionInProgress = false; + this._reschedule(this.heartbeatFrequencyMS); + }); + }; +} diff --git a/nodejs/node_modules/mongodb/src/sdam/server.ts b/nodejs/node_modules/mongodb/src/sdam/server.ts new file mode 100644 index 00000000..8d552df3 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/server.ts @@ -0,0 +1,535 @@ +import type { Document } from '../bson'; +import { type AutoEncrypter } from '../client-side-encryption/auto_encrypter'; +import { type CommandOptions, Connection } from '../cmap/connection'; +import { + ConnectionPool, + type ConnectionPoolEvents, + type ConnectionPoolOptions +} from '../cmap/connection_pool'; +import { PoolClearedError } from '../cmap/errors'; +import { + APM_EVENTS, + CLOSED, + CMAP_EVENTS, + CONNECT, + DESCRIPTION_RECEIVED, + ENDED, + HEARTBEAT_EVENTS, + SERVER_HEARTBEAT_FAILED, + SERVER_HEARTBEAT_STARTED, + SERVER_HEARTBEAT_SUCCEEDED +} from '../constants'; +import { + type AnyError, + isNetworkErrorBeforeHandshake, + isNodeShuttingDownError, + isSDAMUnrecoverableError, + MONGODB_ERROR_CODES, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoRuntimeError, + MongoServerClosedError, + type MongoServerError, + needsRetryableWriteLabel +} from '../error'; +import type { ServerApi } from '../mongo_client'; +import { TypedEventEmitter } from '../mongo_types'; +import type { GetMoreOptions } from '../operations/get_more'; +import type { ClientSession } from '../sessions'; +import { isTransactionCommand } from '../transactions'; +import { + type EventEmitterWithState, + makeStateMachine, + maxWireVersion, + type MongoDBNamespace, + supportsRetryableWrites +} from '../utils'; +import { + type ClusterTime, + STATE_CLOSED, + STATE_CLOSING, + STATE_CONNECTED, + STATE_CONNECTING, + TopologyType +} from './common'; +import type { + ServerHeartbeatFailedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent +} from './events'; +import { Monitor, type MonitorOptions } from './monitor'; +import { compareTopologyVersion, ServerDescription } from './server_description'; +import type { Topology } from './topology'; + +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +/** @internal */ +export type ServerOptions = Omit & + MonitorOptions; + +/** @internal */ +export interface ServerPrivate { + /** The server description for this server */ + description: ServerDescription; + /** A copy of the options used to construct this instance */ + options: ServerOptions; + /** The current state of the Server */ + state: string; + /** MongoDB server API version */ + serverApi?: ServerApi; + /** A count of the operations currently running against the server. */ + operationCount: number; +} + +/** @public */ +export type ServerEvents = { + serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void; + serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void; + serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void; + /** Top level MongoClient doesn't emit this so it is marked: @internal */ + connect(server: Server): void; + descriptionReceived(description: ServerDescription): void; + closed(): void; + ended(): void; +} & ConnectionPoolEvents & + EventEmitterWithState; + +/** @internal */ +export class Server extends TypedEventEmitter { + /** @internal */ + s: ServerPrivate; + /** @internal */ + topology: Topology; + /** @internal */ + pool: ConnectionPool; + serverApi?: ServerApi; + hello?: Document; + monitor: Monitor | null; + + /** @event */ + static readonly SERVER_HEARTBEAT_STARTED = SERVER_HEARTBEAT_STARTED; + /** @event */ + static readonly SERVER_HEARTBEAT_SUCCEEDED = SERVER_HEARTBEAT_SUCCEEDED; + /** @event */ + static readonly SERVER_HEARTBEAT_FAILED = SERVER_HEARTBEAT_FAILED; + /** @event */ + static readonly CONNECT = CONNECT; + /** @event */ + static readonly DESCRIPTION_RECEIVED = DESCRIPTION_RECEIVED; + /** @event */ + static readonly CLOSED = CLOSED; + /** @event */ + static readonly ENDED = ENDED; + + /** + * Create a server + */ + constructor(topology: Topology, description: ServerDescription, options: ServerOptions) { + super(); + + this.serverApi = options.serverApi; + + const poolOptions = { hostAddress: description.hostAddress, ...options }; + + this.topology = topology; + this.pool = new ConnectionPool(this, poolOptions); + + this.s = { + description, + options, + state: STATE_CLOSED, + operationCount: 0 + }; + + for (const event of [...CMAP_EVENTS, ...APM_EVENTS]) { + this.pool.on(event, (e: any) => this.emit(event, e)); + } + + this.pool.on(Connection.CLUSTER_TIME_RECEIVED, (clusterTime: ClusterTime) => { + this.clusterTime = clusterTime; + }); + + if (this.loadBalanced) { + this.monitor = null; + // monitoring is disabled in load balancing mode + return; + } + + // create the monitor + this.monitor = new Monitor(this, this.s.options); + + for (const event of HEARTBEAT_EVENTS) { + this.monitor.on(event, (e: any) => this.emit(event, e)); + } + + this.monitor.on('resetServer', (error: MongoServerError) => markServerUnknown(this, error)); + this.monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event: ServerHeartbeatSucceededEvent) => { + this.emit( + Server.DESCRIPTION_RECEIVED, + new ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + }) + ); + + if (this.s.state === STATE_CONNECTING) { + stateTransition(this, STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + }); + } + + get clusterTime(): ClusterTime | undefined { + return this.topology.clusterTime; + } + + set clusterTime(clusterTime: ClusterTime | undefined) { + this.topology.clusterTime = clusterTime; + } + + get description(): ServerDescription { + return this.s.description; + } + + get name(): string { + return this.s.description.address; + } + + get autoEncrypter(): AutoEncrypter | undefined { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return; + } + + get loadBalanced(): boolean { + return this.topology.description.type === TopologyType.LoadBalanced; + } + + /** + * Initiate server connect + */ + connect(): void { + if (this.s.state !== STATE_CLOSED) { + return; + } + + stateTransition(this, STATE_CONNECTING); + + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + this.monitor?.connect(); + } else { + stateTransition(this, STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + + /** Destroy the server connection */ + destroy(): void { + if (this.s.state === STATE_CLOSED) { + return; + } + + stateTransition(this, STATE_CLOSING); + + if (!this.loadBalanced) { + this.monitor?.close(); + } + + this.pool.close(); + stateTransition(this, STATE_CLOSED); + this.emit('closed'); + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + requestCheck(): void { + if (!this.loadBalanced) { + this.monitor?.requestCheck(); + } + } + + /** + * Execute a command + * @internal + */ + async command(ns: MongoDBNamespace, cmd: Document, options: CommandOptions): Promise { + if (ns.db == null || typeof ns === 'string') { + throw new MongoInvalidArgumentError('Namespace must not be a string'); + } + + if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { + throw new MongoServerClosedError(); + } + + // Clone the options + const finalOptions = Object.assign({}, options, { + wireProtocolCommand: false, + directConnection: this.topology.s.options.directConnection + }); + + // There are cases where we need to flag the read preference not to get sent in + // the command, such as pre-5.0 servers attempting to perform an aggregate write + // with a non-primary read preference. In this case the effective read preference + // (primary) is not the same as the provided and must be removed completely. + if (finalOptions.omitReadPreference) { + delete finalOptions.readPreference; + } + + const session = finalOptions.session; + let conn = session?.pinnedConnection; + + this.incrementOperationCount(); + if (conn == null) { + try { + conn = await this.pool.checkOut(); + if (this.loadBalanced && isPinnableCommand(cmd, session)) { + session?.pin(conn); + } + } catch (checkoutError) { + this.decrementOperationCount(); + if (!(checkoutError instanceof PoolClearedError)) this.handleError(checkoutError); + throw checkoutError; + } + } + + try { + try { + return await conn.command(ns, cmd, finalOptions); + } catch (commandError) { + throw this.decorateCommandError(conn, cmd, finalOptions, commandError); + } + } catch (operationError) { + if ( + operationError instanceof MongoError && + operationError.code === MONGODB_ERROR_CODES.Reauthenticate + ) { + await this.pool.reauthenticate(conn); + try { + return await conn.command(ns, cmd, finalOptions); + } catch (commandError) { + throw this.decorateCommandError(conn, cmd, finalOptions, commandError); + } + } else { + throw operationError; + } + } finally { + this.decrementOperationCount(); + if (session?.pinnedConnection !== conn) { + this.pool.checkIn(conn); + } + } + } + + /** + * Handle SDAM error + * @internal + */ + handleError(error: AnyError, connection?: Connection) { + if (!(error instanceof MongoError)) { + return; + } + + const isStaleError = + error.connectionGeneration && error.connectionGeneration < this.pool.generation; + if (isStaleError) { + return; + } + + const isNetworkNonTimeoutError = + error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError); + const isNetworkTimeoutBeforeHandshakeError = isNetworkErrorBeforeHandshake(error); + const isAuthHandshakeError = error.hasErrorLabel(MongoErrorLabel.HandshakeError); + if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + if (!this.loadBalanced) { + error.addErrorLabel(MongoErrorLabel.ResetPool); + markServerUnknown(this, error as MongoServerError); + } else if (connection) { + this.pool.clear({ serviceId: connection.serviceId }); + } + } else { + if (isSDAMUnrecoverableError(error)) { + if (shouldHandleStateChangeError(this, error)) { + const shouldClearPool = maxWireVersion(this) <= 7 || isNodeShuttingDownError(error); + if (this.loadBalanced && connection && shouldClearPool) { + this.pool.clear({ serviceId: connection.serviceId }); + } + + if (!this.loadBalanced) { + if (shouldClearPool) { + error.addErrorLabel(MongoErrorLabel.ResetPool); + } + markServerUnknown(this, error as MongoServerError); + process.nextTick(() => this.requestCheck()); + } + } + } + } + } + + /** + * Ensure that error is properly decorated and internal state is updated before throwing + * @internal + */ + private decorateCommandError( + connection: Connection, + cmd: Document, + options: CommandOptions | GetMoreOptions | undefined, + error: unknown + ): Error { + if (typeof error !== 'object' || error == null || !('name' in error)) { + throw new MongoRuntimeError('An unexpected error type: ' + typeof error); + } + + if (error.name === 'AbortError' && 'cause' in error && error.cause instanceof MongoError) { + error = error.cause; + } + + if (!(error instanceof MongoError)) { + // Node.js or some other error we have not special handling for + return error as Error; + } + + if (connectionIsStale(this.pool, connection)) { + return error; + } + + const session = options?.session; + if (error instanceof MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + + // inActiveTransaction check handles commit and abort. + if ( + inActiveTransaction(session, cmd) && + !error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + error.addErrorLabel(MongoErrorLabel.TransientTransactionError); + } + + if ( + (isRetryableWritesEnabled(this.topology) || isTransactionCommand(cmd)) && + supportsRetryableWrites(this) && + !inActiveTransaction(session, cmd) + ) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + } else { + if ( + (isRetryableWritesEnabled(this.topology) || isTransactionCommand(cmd)) && + needsRetryableWriteLabel(error, maxWireVersion(this)) && + !inActiveTransaction(session, cmd) + ) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + } + + if ( + session && + session.isPinned && + error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + session.unpin({ force: true }); + } + + this.handleError(error, connection); + + return error; + } + + /** + * Decrement the operation count, returning the new count. + */ + private decrementOperationCount(): number { + return (this.s.operationCount -= 1); + } + + /** + * Increment the operation count, returning the new count. + */ + private incrementOperationCount(): number { + return (this.s.operationCount += 1); + } +} + +function calculateRoundTripTime(oldRtt: number, duration: number): number { + if (oldRtt === -1) { + return duration; + } + + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} + +function markServerUnknown(server: Server, error?: MongoServerError) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + + if (error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError)) { + server.monitor?.reset(); + } + + server.emit( + Server.DESCRIPTION_RECEIVED, + new ServerDescription(server.description.hostAddress, undefined, { error }) + ); +} + +function isPinnableCommand(cmd: Document, session?: ClientSession): boolean { + if (session) { + return ( + session.inTransaction() || + (session.transaction.isCommitted && 'commitTransaction' in cmd) || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd + ); + } + + return false; +} + +function connectionIsStale(pool: ConnectionPool, connection: Connection) { + if (connection.serviceId) { + return ( + connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString()) + ); + } + + return connection.generation !== pool.generation; +} + +function shouldHandleStateChangeError(server: Server, err: MongoError) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return compareTopologyVersion(stv, etv) < 0; +} + +function inActiveTransaction(session: ClientSession | undefined, cmd: Document) { + return session && session.inTransaction() && !isTransactionCommand(cmd); +} + +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology: Topology) { + return topology.s.options.retryWrites !== false; +} diff --git a/nodejs/node_modules/mongodb/src/sdam/server_description.ts b/nodejs/node_modules/mongodb/src/sdam/server_description.ts new file mode 100644 index 00000000..62fe0aad --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/server_description.ts @@ -0,0 +1,262 @@ +import { type Document, Long, type ObjectId } from '../bson'; +import { type MongoError, MongoRuntimeError, type MongoServerError } from '../error'; +import { arrayStrictEqual, compareObjectId, errorStrictEqual, HostAddress, now } from '../utils'; +import type { ClusterTime } from './common'; +import { ServerType } from './common'; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos, + ServerType.LoadBalancer +]); + +const DATA_BEARING_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.RSSecondary, + ServerType.Mongos, + ServerType.Standalone, + ServerType.LoadBalancer +]); + +/** @public */ +export interface TopologyVersion { + processId: ObjectId; + counter: Long; +} + +/** @public */ +export type TagSet = { [key: string]: string }; + +/** @internal */ +export interface ServerDescriptionOptions { + /** An Error used for better reporting debugging */ + error?: MongoServerError; + + /** The round trip time to ping this server (in ms) */ + roundTripTime?: number; + + /** If the client is in load balancing mode. */ + loadBalanced?: boolean; +} + +/** + * The client's view of a single server, based on the most recent hello outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +export class ServerDescription { + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error: MongoError | null; + topologyVersion: TopologyVersion | null; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me: string | null; + primary: string | null; + setName: string | null; + setVersion: number | null; + electionId: ObjectId | null; + logicalSessionTimeoutMinutes: number | null; + + // NOTE: does this belong here? It seems we should gossip the cluster time at the CMAP level + $clusterTime?: ClusterTime; + + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param hello - An optional hello response for this server + */ + constructor( + address: HostAddress | string, + hello?: Document, + options: ServerDescriptionOptions = {} + ) { + if (address == null || address === '') { + throw new MongoRuntimeError('ServerDescription must be provided with a non-empty address'); + } + + this.address = + typeof address === 'string' + ? HostAddress.fromString(address).toString() // Use HostAddress to normalize + : address.toString(); + this.type = parseServerType(hello, options); + this.hosts = hello?.hosts?.map((host: string) => host.toLowerCase()) ?? []; + this.passives = hello?.passives?.map((host: string) => host.toLowerCase()) ?? []; + this.arbiters = hello?.arbiters?.map((host: string) => host.toLowerCase()) ?? []; + this.tags = hello?.tags ?? {}; + this.minWireVersion = hello?.minWireVersion ?? 0; + this.maxWireVersion = hello?.maxWireVersion ?? 0; + this.roundTripTime = options?.roundTripTime ?? -1; + this.lastUpdateTime = now(); + this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0; + this.error = options.error ?? null; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; + this.setName = hello?.setName ?? null; + this.setVersion = hello?.setVersion ?? null; + this.electionId = hello?.electionId ?? null; + this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; + this.primary = hello?.primary ?? null; + this.me = hello?.me?.toLowerCase() ?? null; + this.$clusterTime = hello?.$clusterTime ?? null; + } + + get hostAddress(): HostAddress { + return HostAddress.fromString(this.address); + } + + get allHosts(): string[] { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** Is this server available for reads*/ + get isReadable(): boolean { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** Is this server data bearing */ + get isDataBearing(): boolean { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + + /** Is this server available for writes */ + get isWritable(): boolean { + return WRITABLE_SERVER_TYPES.has(this.type); + } + + get host(): string { + const chopLength = `:${this.port}`.length; + return this.address.slice(0, -chopLength); + } + + get port(): number { + const port = this.address.split(':').pop(); + return port ? Number.parseInt(port, 10) : 27017; + } + + /** + * Determines if another `ServerDescription` is equal to this one per the rules defined + * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} + */ + equals(other?: ServerDescription | null): boolean { + // Despite using the comparator that would determine a nullish topologyVersion as greater than + // for equality we should only always perform direct equality comparison + const topologyVersionsEqual = + this.topologyVersion === other?.topologyVersion || + compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; + + const electionIdsEqual = + this.electionId != null && other?.electionId != null + ? compareObjectId(this.electionId, other.electionId) === 0 + : this.electionId === other?.electionId; + + return ( + other != null && + errorStrictEqual(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + arrayStrictEqual(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual + ); + } +} + +// Parses a `hello` message and determines the server type +export function parseServerType(hello?: Document, options?: ServerDescriptionOptions): ServerType { + if (options?.loadBalanced) { + return ServerType.LoadBalancer; + } + + if (!hello || !hello.ok) { + return ServerType.Unknown; + } + + if (hello.isreplicaset) { + return ServerType.RSGhost; + } + + if (hello.msg && hello.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (hello.setName) { + if (hello.hidden) { + return ServerType.RSOther; + } else if (hello.isWritablePrimary) { + return ServerType.RSPrimary; + } else if (hello.secondary) { + return ServerType.RSSecondary; + } else if (hello.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +function tagsStrictEqual(tags: TagSet, tags2: TagSet): boolean { + const tagsKeys = Object.keys(tags); + const tags2Keys = Object.keys(tags2); + + return ( + tagsKeys.length === tags2Keys.length && + tagsKeys.every((key: string) => tags2[key] === tags[key]) + ); +} + +/** + * Compares two topology versions. + * + * 1. If the response topologyVersion is unset or the ServerDescription's + * topologyVersion is null, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is not equal to the + * ServerDescription's, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is equal to the + * ServerDescription's, the client MUST use the counter field to determine + * which topologyVersion is more recent. + * + * ```ts + * currentTv < newTv === -1 + * currentTv === newTv === 0 + * currentTv > newTv === 1 + * ``` + */ +export function compareTopologyVersion( + currentTv?: TopologyVersion | null, + newTv?: TopologyVersion | null +): 0 | -1 | 1 { + if (currentTv == null || newTv == null) { + return -1; + } + + if (!currentTv.processId.equals(newTv.processId)) { + return -1; + } + + // TODO(NODE-2674): Preserve int64 sent from MongoDB + const currentCounter = Long.isLong(currentTv.counter) + ? currentTv.counter + : Long.fromNumber(currentTv.counter); + const newCounter = Long.isLong(newTv.counter) ? newTv.counter : Long.fromNumber(newTv.counter); + + return currentCounter.compare(newCounter); +} diff --git a/nodejs/node_modules/mongodb/src/sdam/server_selection.ts b/nodejs/node_modules/mongodb/src/sdam/server_selection.ts new file mode 100644 index 00000000..8c92f08b --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/server_selection.ts @@ -0,0 +1,332 @@ +import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error'; +import { ReadPreference } from '../read_preference'; +import { ServerType, TopologyType } from './common'; +import type { ServerDescription, TagSet } from './server_description'; +import type { TopologyDescription } from './topology_description'; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +// Minimum version to try writes on secondaries. +export const MIN_SECONDARY_WRITE_WIRE_VERSION = 13; + +/** @internal */ +export type ServerSelector = ( + topologyDescription: TopologyDescription, + servers: ServerDescription[], + deprioritized?: ServerDescription[] +) => ServerDescription[]; + +/** + * Returns a server selector that selects for writable servers + */ +export function writableServerSelector(): ServerSelector { + return function writableServer( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] { + return latencyWindowReducer( + topologyDescription, + servers.filter((s: ServerDescription) => s.isWritable) + ); + }; +} + +/** + * The purpose of this selector is to select the same server, only + * if it is in a state that it can have commands sent to it. + */ +export function sameServerSelector(description?: ServerDescription): ServerSelector { + return function sameServerSelector( + topologyDescription: TopologyDescription, + servers: ServerDescription[] + ): ServerDescription[] { + if (!description) return []; + // Filter the servers to match the provided description only if + // the type is not unknown. + return servers.filter(sd => { + return sd.address === description.address && sd.type !== ServerType.Unknown; + }); + }; +} + +/** + * Returns a server selector that uses a read preference to select a + * server potentially for a write on a secondary. + */ +export function secondaryWritableServerSelector( + wireVersion?: number, + readPreference?: ReadPreference +): ServerSelector { + // If server version < 5.0, read preference always primary. + // If server version >= 5.0... + // - If read preference is supplied, use that. + // - If no read preference is supplied, use primary. + if ( + !readPreference || + !wireVersion || + (wireVersion && wireVersion < MIN_SECONDARY_WRITE_WIRE_VERSION) + ) { + return readPreferenceServerSelector(ReadPreference.primary); + } + return readPreferenceServerSelector(readPreference); +} + +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param readPreference - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer( + readPreference: ReadPreference, + topologyDescription: TopologyDescription, + servers: ServerDescription[] +): ServerDescription[] { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new MongoInvalidArgumentError( + `Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds` + ); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoInvalidArgumentError( + `Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary: ServerDescription = Array.from(topologyDescription.servers.values()).filter( + primaryFilter + )[0]; + + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + + return result; + }, []); + } + + if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; + } + + const sMax = servers.reduce((max: ServerDescription, s: ServerDescription) => + s.lastWriteDate > max.lastWriteDate ? s : max + ); + + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + + return result; + }, []); + } + + return servers; +} + +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param serverTags - The server's tags + */ +function tagSetMatch(tagSet: TagSet, serverTags: TagSet) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns The list of servers matching the requested tags + */ +function tagSetReducer( + readPreference: ReadPreference, + servers: ServerDescription[] +): ServerDescription[] { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce( + (matched: ServerDescription[], server: ServerDescription) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, + [] + ); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param topologyDescription - The topology description + * @param servers - The list of servers to reduce + * @returns The servers which fall within an acceptable latency window + */ +function latencyWindowReducer( + topologyDescription: TopologyDescription, + servers: ServerDescription[] +): ServerDescription[] { + const low = servers.reduce( + (min: number, server: ServerDescription) => + min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result: ServerDescription[], server: ServerDescription) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server: ServerDescription): boolean { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server: ServerDescription): boolean { + return server.type !== ServerType.Unknown; +} + +function loadBalancerFilter(server: ServerDescription): boolean { + return server.type === ServerType.LoadBalancer; +} + +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +export function readPreferenceServerSelector(readPreference: ReadPreference): ServerSelector { + if (!readPreference.isValid()) { + throw new MongoInvalidArgumentError('Invalid read preference specified'); + } + + return function readPreferenceServers( + topologyDescription: TopologyDescription, + servers: ServerDescription[], + deprioritized: ServerDescription[] = [] + ): ServerDescription[] { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion + ) { + throw new MongoCompatibilityError( + `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` + ); + } + + if (topologyDescription.type === TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); + } + + if (topologyDescription.type === TopologyType.Unknown) { + return []; + } + + if (topologyDescription.type === TopologyType.Single) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + if (topologyDescription.type === TopologyType.Sharded) { + const filtered = servers.filter(server => { + return !deprioritized.includes(server); + }); + const selectable = filtered.length > 0 ? filtered : deprioritized; + return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter)); + } + + const mode = readPreference.mode; + if (mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + } + + const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)) + ) + ); + + if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); + } + + return selectedServers; + }; +} diff --git a/nodejs/node_modules/mongodb/src/sdam/server_selection_events.ts b/nodejs/node_modules/mongodb/src/sdam/server_selection_events.ts new file mode 100644 index 00000000..9b171661 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/server_selection_events.ts @@ -0,0 +1,142 @@ +import { HostAddress } from '.././utils'; +import { + SERVER_SELECTION_FAILED, + SERVER_SELECTION_STARTED, + SERVER_SELECTION_SUCCEEDED, + WAITING_FOR_SUITABLE_SERVER +} from '../constants'; +import { type ReadPreference } from '../read_preference'; +import { type ServerSelector } from './server_selection'; +import type { TopologyDescription } from './topology_description'; + +/** + * The base export class for all logs published from server selection + * @internal + * @category Log Type + */ +export abstract class ServerSelectionEvent { + /** String representation of the selector being used to select the server. + * Defaults to 'custom selector' for application-provided custom selector case. + */ + selector: string | ReadPreference | ServerSelector; + /** The name of the operation for which a server is being selected. */ + operation: string; + /** The current topology description. */ + topologyDescription: TopologyDescription; + + /** @internal */ + abstract name: + | typeof SERVER_SELECTION_STARTED + | typeof SERVER_SELECTION_SUCCEEDED + | typeof SERVER_SELECTION_FAILED + | typeof WAITING_FOR_SUITABLE_SERVER; + + abstract message: string; + + /** @internal */ + constructor( + selector: string | ReadPreference | ServerSelector, + topologyDescription: TopologyDescription, + operation: string + ) { + this.selector = selector; + this.operation = operation; + this.topologyDescription = topologyDescription; + } +} + +/** + * An event published when server selection starts + * @internal + * @category Event + */ +export class ServerSelectionStartedEvent extends ServerSelectionEvent { + /** @internal */ + name = SERVER_SELECTION_STARTED; + message = 'Server selection started'; + + /** @internal */ + constructor( + selector: string | ReadPreference | ServerSelector, + topologyDescription: TopologyDescription, + operation: string + ) { + super(selector, topologyDescription, operation); + } +} + +/** + * An event published when a server selection fails + * @internal + * @category Event + */ +export class ServerSelectionFailedEvent extends ServerSelectionEvent { + /** @internal */ + name = SERVER_SELECTION_FAILED; + message = 'Server selection failed'; + /** Representation of the error the driver will throw regarding server selection failing. */ + failure: Error; + + /** @internal */ + constructor( + selector: string | ReadPreference | ServerSelector, + topologyDescription: TopologyDescription, + error: Error, + operation: string + ) { + super(selector, topologyDescription, operation); + this.failure = error; + } +} + +/** + * An event published when server selection succeeds + * @internal + * @category Event + */ +export class ServerSelectionSucceededEvent extends ServerSelectionEvent { + /** @internal */ + name = SERVER_SELECTION_SUCCEEDED; + message = 'Server selection succeeded'; + /** The hostname, IP address, or Unix domain socket path for the selected server. */ + serverHost: string; + /** The port for the selected server. Optional; not present for Unix domain sockets. When the user does not specify a port and the default (27017) is used, the driver SHOULD include it here. */ + serverPort: number | undefined; + + /** @internal */ + constructor( + selector: string | ReadPreference | ServerSelector, + topologyDescription: TopologyDescription, + address: string, + operation: string + ) { + super(selector, topologyDescription, operation); + const { host, port } = HostAddress.fromString(address).toHostPort(); + this.serverHost = host; + this.serverPort = port; + } +} + +/** + * An event published when server selection is waiting for a suitable server to become available + * @internal + * @category Event + */ +export class WaitingForSuitableServerEvent extends ServerSelectionEvent { + /** @internal */ + name = WAITING_FOR_SUITABLE_SERVER; + message = 'Waiting for suitable server to become available'; + /** The remaining time left until server selection will time out. */ + remainingTimeMS: number; + + /** @internal */ + constructor( + selector: string | ReadPreference | ServerSelector, + topologyDescription: TopologyDescription, + remainingTimeMS: number, + operation: string + ) { + super(selector, topologyDescription, operation); + this.remainingTimeMS = remainingTimeMS; + } +} diff --git a/nodejs/node_modules/mongodb/src/sdam/srv_polling.ts b/nodejs/node_modules/mongodb/src/sdam/srv_polling.ts new file mode 100644 index 00000000..8606abc0 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/srv_polling.ts @@ -0,0 +1,142 @@ +import * as dns from 'dns'; +import { clearTimeout, setTimeout } from 'timers'; + +import { MongoRuntimeError } from '../error'; +import { TypedEventEmitter } from '../mongo_types'; +import { HostAddress, matchesParentDomain } from '../utils'; + +/** + * @internal + * @category Event + */ +export class SrvPollingEvent { + srvRecords: dns.SrvRecord[]; + constructor(srvRecords: dns.SrvRecord[]) { + this.srvRecords = srvRecords; + } + + hostnames(): Set { + return new Set(this.srvRecords.map(r => HostAddress.fromSrvRecord(r).toString())); + } +} + +/** @internal */ +export interface SrvPollerOptions { + srvServiceName: string; + srvMaxHosts: number; + srvHost: string; + heartbeatFrequencyMS: number; +} + +/** @internal */ +export type SrvPollerEvents = { + srvRecordDiscovery(event: SrvPollingEvent): void; +}; + +/** @internal */ +export class SrvPoller extends TypedEventEmitter { + srvHost: string; + rescanSrvIntervalMS: number; + heartbeatFrequencyMS: number; + haMode: boolean; + generation: number; + srvMaxHosts: number; + srvServiceName: string; + _timeout?: NodeJS.Timeout; + + /** @event */ + static readonly SRV_RECORD_DISCOVERY = 'srvRecordDiscovery' as const; + + constructor(options: SrvPollerOptions) { + super(); + + if (!options || !options.srvHost) { + throw new MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + + this.srvHost = options.srvHost; + this.srvMaxHosts = options.srvMaxHosts ?? 0; + this.srvServiceName = options.srvServiceName ?? 'mongodb'; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 10000; + + this.haMode = false; + this.generation = 0; + + this._timeout = undefined; + } + + get srvAddress(): string { + return `_${this.srvServiceName}._tcp.${this.srvHost}`; + } + + get intervalMS(): number { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + + start(): void { + if (!this._timeout) { + this.schedule(); + } + } + + stop(): void { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + + // TODO(NODE-4994): implement new logging logic for SrvPoller failures + schedule(): void { + if (this._timeout) { + clearTimeout(this._timeout); + } + + this._timeout = setTimeout(() => { + this._poll().catch(() => null); + }, this.intervalMS); + } + + success(srvRecords: dns.SrvRecord[]): void { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + + failure(): void { + this.haMode = true; + this.schedule(); + } + + async _poll(): Promise { + const generation = this.generation; + let srvRecords; + + try { + srvRecords = await dns.promises.resolveSrv(this.srvAddress); + } catch (dnsError) { + this.failure(); + return; + } + + if (generation !== this.generation) { + return; + } + + const finalAddresses: dns.SrvRecord[] = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + } + + if (!finalAddresses.length) { + this.failure(); + return; + } + + this.success(finalAddresses); + } +} diff --git a/nodejs/node_modules/mongodb/src/sdam/topology.ts b/nodejs/node_modules/mongodb/src/sdam/topology.ts new file mode 100644 index 00000000..92364748 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/topology.ts @@ -0,0 +1,1126 @@ +import { promisify } from 'util'; + +import type { BSONSerializeOptions, Document } from '../bson'; +import type { MongoCredentials } from '../cmap/auth/mongo_credentials'; +import type { ConnectionEvents } from '../cmap/connection'; +import type { ConnectionPoolEvents } from '../cmap/connection_pool'; +import type { ClientMetadata } from '../cmap/handshake/client_metadata'; +import { DEFAULT_OPTIONS, FEATURE_FLAGS } from '../connection_string'; +import { + CLOSE, + CONNECT, + ERROR, + LOCAL_SERVER_EVENTS, + OPEN, + SERVER_CLOSED, + SERVER_DESCRIPTION_CHANGED, + SERVER_OPENING, + SERVER_RELAY_EVENTS, + TIMEOUT, + TOPOLOGY_CLOSED, + TOPOLOGY_DESCRIPTION_CHANGED, + TOPOLOGY_OPENING +} from '../constants'; +import { + MongoCompatibilityError, + type MongoDriverError, + MongoError, + MongoErrorLabel, + MongoRuntimeError, + MongoServerSelectionError, + MongoTopologyClosedError +} from '../error'; +import type { MongoClient, ServerApi } from '../mongo_client'; +import { MongoLoggableComponent, type MongoLogger, SeverityLevel } from '../mongo_logger'; +import { TypedEventEmitter } from '../mongo_types'; +import { ReadPreference, type ReadPreferenceLike } from '../read_preference'; +import type { ClientSession } from '../sessions'; +import type { Transaction } from '../transactions'; +import { + type Callback, + type EventEmitterWithState, + HostAddress, + List, + makeStateMachine, + now, + ns, + shuffle, + TimeoutController +} from '../utils'; +import { + _advanceClusterTime, + type ClusterTime, + drainTimerQueue, + ServerType, + STATE_CLOSED, + STATE_CLOSING, + STATE_CONNECTED, + STATE_CONNECTING, + type TimerQueue, + TopologyType +} from './common'; +import { + ServerClosedEvent, + ServerDescriptionChangedEvent, + ServerOpeningEvent, + TopologyClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent +} from './events'; +import type { ServerMonitoringMode } from './monitor'; +import { Server, type ServerEvents, type ServerOptions } from './server'; +import { compareTopologyVersion, ServerDescription } from './server_description'; +import { readPreferenceServerSelector, type ServerSelector } from './server_selection'; +import { + ServerSelectionFailedEvent, + ServerSelectionStartedEvent, + ServerSelectionSucceededEvent, + WaitingForSuitableServerEvent +} from './server_selection_events'; +import { SrvPoller, type SrvPollingEvent } from './srv_polling'; +import { TopologyDescription } from './topology_description'; + +// Global state +let globalTopologyCounter = 0; + +const stateTransition = makeStateMachine({ + [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], + [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], + [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], + [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] +}); + +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); + +/** @internal */ +export type ServerSelectionCallback = Callback; + +/** @internal */ +export interface ServerSelectionRequest { + serverSelector: ServerSelector; + topologyDescription: TopologyDescription; + mongoLogger: MongoLogger | undefined; + transaction?: Transaction; + startTime: number; + callback: ServerSelectionCallback; + [kCancelled]?: boolean; + timeoutController: TimeoutController; + operationName: string; + waitingLogged: boolean; + previousServer?: ServerDescription; +} + +/** @internal */ +export interface TopologyPrivate { + /** the id of this topology */ + id: number; + /** passed in options */ + options: TopologyOptions; + /** initial seedlist of servers to connect to */ + seedlist: HostAddress[]; + /** initial state */ + state: string; + /** the topology description */ + description: TopologyDescription; + serverSelectionTimeoutMS: number; + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + /** A map of server instances to normalized addresses */ + servers: Map; + credentials?: MongoCredentials; + clusterTime?: ClusterTime; + /** timers created for the initial connect to a server */ + connectionTimers: TimerQueue; + + /** related to srv polling */ + srvPoller?: SrvPoller; + detectShardedTopology: (event: TopologyDescriptionChangedEvent) => void; + detectSrvRecords: (event: SrvPollingEvent) => void; +} + +/** @internal */ +export interface TopologyOptions extends BSONSerializeOptions, ServerOptions { + srvMaxHosts: number; + srvServiceName: string; + hosts: HostAddress[]; + retryWrites: boolean; + retryReads: boolean; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS: number; + /** The name of the replica set to connect to */ + replicaSet?: string; + srvHost?: string; + srvPoller?: SrvPoller; + /** Indicates that a client should directly connect to a node without attempting to discover its topology type */ + directConnection: boolean; + loadBalanced: boolean; + metadata: ClientMetadata; + extendedMetadata: Promise; + serverMonitoringMode: ServerMonitoringMode; + /** MongoDB server API version */ + serverApi?: ServerApi; + [featureFlag: symbol]: any; +} + +/** @public */ +export interface ConnectOptions { + readPreference?: ReadPreference; +} + +/** @public */ +export interface SelectServerOptions { + readPreference?: ReadPreferenceLike; + /** How long to block for server selection before throwing an error */ + serverSelectionTimeoutMS?: number; + session?: ClientSession; + operationName: string; + previousServer?: ServerDescription; +} + +/** @public */ +export type TopologyEvents = { + /** Top level MongoClient doesn't emit this so it is marked: @internal */ + connect(topology: Topology): void; + serverOpening(event: ServerOpeningEvent): void; + serverClosed(event: ServerClosedEvent): void; + serverDescriptionChanged(event: ServerDescriptionChangedEvent): void; + topologyClosed(event: TopologyClosedEvent): void; + topologyOpening(event: TopologyOpeningEvent): void; + topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void; + error(error: Error): void; + /** @internal */ + open(topology: Topology): void; + close(): void; + timeout(): void; +} & Omit & + ConnectionPoolEvents & + ConnectionEvents & + EventEmitterWithState; +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +export class Topology extends TypedEventEmitter { + /** @internal */ + s: TopologyPrivate; + /** @internal */ + [kWaitQueue]: List; + /** @internal */ + hello?: Document; + /** @internal */ + _type?: string; + + client!: MongoClient; + + /** @event */ + static readonly SERVER_OPENING = SERVER_OPENING; + /** @event */ + static readonly SERVER_CLOSED = SERVER_CLOSED; + /** @event */ + static readonly SERVER_DESCRIPTION_CHANGED = SERVER_DESCRIPTION_CHANGED; + /** @event */ + static readonly TOPOLOGY_OPENING = TOPOLOGY_OPENING; + /** @event */ + static readonly TOPOLOGY_CLOSED = TOPOLOGY_CLOSED; + /** @event */ + static readonly TOPOLOGY_DESCRIPTION_CHANGED = TOPOLOGY_DESCRIPTION_CHANGED; + /** @event */ + static readonly ERROR = ERROR; + /** @event */ + static readonly OPEN = OPEN; + /** @event */ + static readonly CONNECT = CONNECT; + /** @event */ + static readonly CLOSE = CLOSE; + /** @event */ + static readonly TIMEOUT = TIMEOUT; + + selectServerAsync: ( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions + ) => Promise; + + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor( + client: MongoClient, + seeds: string | string[] | HostAddress | HostAddress[], + options: TopologyOptions + ) { + super(); + + this.client = client; + this.selectServerAsync = promisify( + ( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions, + callback: (e: Error, r: Server) => void + ) => this.selectServer(selector, options, callback as any) + ); + + // Options should only be undefined in tests, MongoClient will always have defined options + options = options ?? { + hosts: [HostAddress.fromString('localhost:27017')], + ...Object.fromEntries(DEFAULT_OPTIONS.entries()), + ...Object.fromEntries(FEATURE_FLAGS.entries()) + }; + + if (typeof seeds === 'string') { + seeds = [HostAddress.fromString(seeds)]; + } else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + + const seedlist: HostAddress[] = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(HostAddress.fromString(seed)); + } else if (seed instanceof HostAddress) { + seedlist.push(seed); + } else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + + const selectedHosts = + options.srvMaxHosts == null || + options.srvMaxHosts === 0 || + options.srvMaxHosts >= seedlist.length + ? seedlist + : shuffle(seedlist, options.srvMaxHosts); + + const serverDescriptions = new Map(); + for (const hostAddress of selectedHosts) { + serverDescriptions.set(hostAddress.toString(), new ServerDescription(hostAddress)); + } + + this[kWaitQueue] = new List(); + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: STATE_CLOSED, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + undefined, + undefined, + undefined, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + credentials: options?.credentials, + clusterTime: undefined, + + // timer management + connectionTimers: new Set(), + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) + }; + + this.mongoLogger = client.mongoLogger; + this.component = 'topology'; + + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + options.srvPoller ?? + new SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, + srvMaxHosts: options.srvMaxHosts, + srvServiceName: options.srvServiceName + }); + + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + } + } + + private detectShardedTopology(event: TopologyDescriptionChangedEvent) { + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + + const transitionToSharded = + previousType !== TopologyType.Sharded && newType === TopologyType.Sharded; + const srvListeners = this.s.srvPoller?.listeners(SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); + + if (transitionToSharded && !listeningToSrvPolling) { + this.s.srvPoller?.on(SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + this.s.srvPoller?.start(); + } + } + + private detectSrvRecords(ev: SrvPollingEvent) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent( + ev, + this.s.options.srvMaxHosts + ); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + + updateServers(this); + + this.emitAndLog( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + /** + * @returns A `TopologyDescription` for this topology + */ + get description(): TopologyDescription { + return this.s.description; + } + + get loadBalanced(): boolean { + return this.s.options.loadBalanced; + } + + get serverApi(): ServerApi | undefined { + return this.s.options.serverApi; + } + + get capabilities(): ServerCapabilities { + return new ServerCapabilities(this.lastHello()); + } + + /** Initiate server connect */ + connect(callback: Callback): void; + connect(options: ConnectOptions, callback: Callback): void; + connect(options?: ConnectOptions | Callback, callback?: Callback): void { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ?? {}; + if (this.s.state === STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); + } + + return; + } + + stateTransition(this, STATE_CONNECTING); + + // emit SDAM monitoring events + this.emitAndLog(Topology.TOPOLOGY_OPENING, new TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emitAndLog( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + this.s.servers = new Map( + serverDescriptions.map(serverDescription => [ + serverDescription.address, + createAndConnectServer(this, serverDescription) + ]) + ); + + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); + } + } + + const exitWithError = (error: Error) => + callback ? callback(error) : this.emit(Topology.ERROR, error); + + const readPreference = options.readPreference ?? ReadPreference.primary; + const selectServerOptions = { operationName: 'ping', ...options }; + this.selectServer( + readPreferenceServerSelector(readPreference), + selectServerOptions, + (err, server) => { + if (err) { + this.close(); + return exitWithError(err); + } + + const skipPingOnConnect = this.s.options[Symbol.for('@@mdb.skipPingOnConnect')] === true; + if (!skipPingOnConnect && server && this.s.credentials) { + server.command(ns('admin.$cmd'), { ping: 1 }, {}).then(() => { + stateTransition(this, STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + + callback?.(undefined, this); + }, exitWithError); + + return; + } + + stateTransition(this, STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + + callback?.(undefined, this); + } + ); + } + + /** Close this topology */ + close(): void { + if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { + return; + } + + for (const server of this.s.servers.values()) { + destroyServer(server, this); + } + + this.s.servers.clear(); + + stateTransition(this, STATE_CLOSING); + + drainWaitQueue(this[kWaitQueue], new MongoTopologyClosedError()); + drainTimerQueue(this.s.connectionTimers); + + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + + stateTransition(this, STATE_CLOSED); + + // emit an event for close + this.emitAndLog(Topology.TOPOLOGY_CLOSED, new TopologyClosedEvent(this.s.id)); + } + + /** + * Selects a server according to the selection predicate provided + * + * @param selector - An optional selector to select servers by, defaults to a random selection within a latency window + * @param options - Optional settings related to server selection + * @param callback - The callback used to indicate success or failure + * @returns An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions, + callback: Callback + ): void { + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = readPreferenceServerSelector(ReadPreference.fromString(selector)); + } else { + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + ReadPreference.translate(options); + readPreference = options.readPreference || ReadPreference.primary; + } + + serverSelector = readPreferenceServerSelector(readPreference as ReadPreference); + } + } else { + serverSelector = selector; + } + + options = { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS, ...options }; + if ( + this.client.mongoLogger?.willLog(MongoLoggableComponent.SERVER_SELECTION, SeverityLevel.DEBUG) + ) { + this.client.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionStartedEvent(selector, this.description, options.operationName) + ); + } + + const isSharded = this.description.type === TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + + if (isSharded && transaction && transaction.server) { + if ( + this.client.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.DEBUG + ) + ) { + this.client.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionSucceededEvent( + selector, + this.description, + transaction.server.pool.address, + options.operationName + ) + ); + } + callback(undefined, transaction.server); + return; + } + + const waitQueueMember: ServerSelectionRequest = { + serverSelector, + topologyDescription: this.description, + mongoLogger: this.client.mongoLogger, + transaction, + callback, + timeoutController: new TimeoutController(options.serverSelectionTimeoutMS), + startTime: now(), + operationName: options.operationName, + waitingLogged: false, + previousServer: options.previousServer + }; + + waitQueueMember.timeoutController.signal.addEventListener('abort', () => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timeoutController.clear(); + const timeoutError = new MongoServerSelectionError( + `Server selection timed out after ${options.serverSelectionTimeoutMS} ms`, + this.description + ); + if ( + this.client.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.DEBUG + ) + ) { + this.client.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionFailedEvent( + selector, + this.description, + timeoutError, + options.operationName + ) + ); + } + waitQueueMember.callback(timeoutError); + }); + + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param serverDescription - The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription: ServerDescription): void { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // ignore this server update if its from an outdated topologyVersion + if (isStaleServerDescription(this.s.description, serverDescription)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + if (!previousServerDescription) { + return; + } + + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + _advanceClusterTime(this, clusterTime); + } + + // If we already know all the information contained in this updated description, then + // we don't need to emit SDAM events, but still need to update the description, in order + // to keep client-tracked attributes like last update time and round trip time up to date + const equalDescriptions = + previousServerDescription && previousServerDescription.equals(serverDescription); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit(Topology.ERROR, new MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit( + Topology.SERVER_DESCRIPTION_CHANGED, + new ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + newDescription + ) + ); + } + } + + // update server list from updated descriptions + updateServers(this, serverDescription); + + // attempt to resolve any outstanding server selection attempts + if (this[kWaitQueue].length > 0) { + processWaitQueue(this); + } + + if (!equalDescriptions) { + this.emitAndLog( + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + new TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + } + + auth(credentials?: MongoCredentials, callback?: Callback): void { + if (typeof credentials === 'function') (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') callback(undefined, true); + } + + get clientMetadata(): ClientMetadata { + return this.s.options.metadata; + } + + isConnected(): boolean { + return this.s.state === STATE_CONNECTED; + } + + isDestroyed(): boolean { + return this.s.state === STATE_CLOSED; + } + + // NOTE: There are many places in code where we explicitly check the last hello + // to do feature support detection. This should be done any other way, but for + // now we will just return the first hello seen, which should suffice. + lastHello(): Document { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) return {}; + const sd = serverDescriptions.filter( + (sd: ServerDescription) => sd.type !== ServerType.Unknown + )[0]; + + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + + get commonWireVersion(): number | undefined { + return this.description.commonWireVersion; + } + + get logicalSessionTimeoutMinutes(): number | null { + return this.description.logicalSessionTimeoutMinutes; + } + + get clusterTime(): ClusterTime | undefined { + return this.s.clusterTime; + } + + set clusterTime(clusterTime: ClusterTime | undefined) { + this.s.clusterTime = clusterTime; + } +} + +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer(server: Server, topology: Topology) { + for (const event of LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + + server.destroy(); + topology.emitAndLog( + Topology.SERVER_CLOSED, + new ServerClosedEvent(topology.s.id, server.description.address) + ); + + for (const event of SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } +} + +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options?: TopologyOptions) { + if (options?.directConnection) { + return TopologyType.Single; + } + + if (options?.replicaSet) { + return TopologyType.ReplicaSetNoPrimary; + } + + if (options?.loadBalanced) { + return TopologyType.LoadBalanced; + } + + return TopologyType.Unknown; +} + +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + */ +function createAndConnectServer(topology: Topology, serverDescription: ServerDescription) { + topology.emitAndLog( + Topology.SERVER_OPENING, + new ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(topology, serverDescription, topology.s.options); + for (const event of SERVER_RELAY_EVENTS) { + server.on(event, (e: any) => topology.emit(event, e)); + } + + server.on(Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + + server.connect(); + return server; +} + +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +function updateServers(topology: Topology, incomingServerDescription?: ServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + if (server) { + server.s.description = incomingServerDescription; + if ( + incomingServerDescription.error instanceof MongoError && + incomingServerDescription.error.hasErrorLabel(MongoErrorLabel.ResetPool) + ) { + const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel( + MongoErrorLabel.InterruptInUseConnections + ); + + server.pool.clear({ interruptInUseConnections }); + } else if (incomingServerDescription.error == null) { + const newTopologyType = topology.s.description.type; + const shouldMarkPoolReady = + incomingServerDescription.isDataBearing || + (incomingServerDescription.type !== ServerType.Unknown && + newTopologyType === TopologyType.Single); + if (shouldMarkPoolReady) { + server.pool.ready(); + } + } + } + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + if (!topology.s.servers.has(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} + +function drainWaitQueue(queue: List, err?: MongoDriverError) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + + waitQueueMember.timeoutController.clear(); + + if (!waitQueueMember[kCancelled]) { + if (err) { + if ( + waitQueueMember.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.DEBUG + ) + ) { + waitQueueMember.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionFailedEvent( + waitQueueMember.serverSelector, + waitQueueMember.topologyDescription, + err, + waitQueueMember.operationName + ) + ); + } + } + waitQueueMember.callback(err); + } + } +} + +function processWaitQueue(topology: Topology) { + if (topology.s.state === STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new MongoTopologyClosedError()); + return; + } + + const isSharded = topology.description.type === TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + + if (waitQueueMember[kCancelled]) { + continue; + } + + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + const previousServer = waitQueueMember.previousServer; + selectedDescriptions = serverSelector + ? serverSelector( + topology.description, + serverDescriptions, + previousServer ? [previousServer] : [] + ) + : serverDescriptions; + } catch (e) { + waitQueueMember.timeoutController.clear(); + if ( + topology.client.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.DEBUG + ) + ) { + topology.client.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionFailedEvent( + waitQueueMember.serverSelector, + topology.description, + e, + waitQueueMember.operationName + ) + ); + } + waitQueueMember.callback(e); + continue; + } + + let selectedServer: Server | undefined; + if (selectedDescriptions.length === 0) { + if (!waitQueueMember.waitingLogged) { + if ( + topology.client.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.INFORMATIONAL + ) + ) { + topology.client.mongoLogger?.info( + MongoLoggableComponent.SERVER_SELECTION, + new WaitingForSuitableServerEvent( + waitQueueMember.serverSelector, + topology.description, + topology.s.serverSelectionTimeoutMS !== 0 + ? topology.s.serverSelectionTimeoutMS - (now() - waitQueueMember.startTime) + : -1, + waitQueueMember.operationName + ) + ); + } + waitQueueMember.waitingLogged = true; + } + topology[kWaitQueue].push(waitQueueMember); + continue; + } else if (selectedDescriptions.length === 1) { + selectedServer = topology.s.servers.get(selectedDescriptions[0].address); + } else { + const descriptions = shuffle(selectedDescriptions, 2); + const server1 = topology.s.servers.get(descriptions[0].address); + const server2 = topology.s.servers.get(descriptions[1].address); + + selectedServer = + server1 && server2 && server1.s.operationCount < server2.s.operationCount + ? server1 + : server2; + } + + if (!selectedServer) { + const error = new MongoServerSelectionError( + 'server selection returned a server description but the server was not found in the topology', + topology.description + ); + if ( + topology.client.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.DEBUG + ) + ) { + topology.client.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionFailedEvent( + waitQueueMember.serverSelector, + topology.description, + error, + waitQueueMember.operationName + ) + ); + } + waitQueueMember.callback(error); + return; + } + const transaction = waitQueueMember.transaction; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + + waitQueueMember.timeoutController.clear(); + + if ( + topology.client.mongoLogger?.willLog( + MongoLoggableComponent.SERVER_SELECTION, + SeverityLevel.DEBUG + ) + ) { + topology.client.mongoLogger?.debug( + MongoLoggableComponent.SERVER_SELECTION, + new ServerSelectionSucceededEvent( + waitQueueMember.serverSelector, + waitQueueMember.topologyDescription, + selectedServer.pool.address, + waitQueueMember.operationName + ) + ); + } + waitQueueMember.callback(undefined, selectedServer); + } + + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} + +function isStaleServerDescription( + topologyDescription: TopologyDescription, + incomingServerDescription: ServerDescription +) { + const currentServerDescription = topologyDescription.servers.get( + incomingServerDescription.address + ); + const currentTopologyVersion = currentServerDescription?.topologyVersion; + return ( + compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0 + ); +} + +/** @public */ +export class ServerCapabilities { + maxWireVersion: number; + minWireVersion: number; + + constructor(hello: Document) { + this.minWireVersion = hello.minWireVersion || 0; + this.maxWireVersion = hello.maxWireVersion || 0; + } + + get hasAggregationCursor(): boolean { + return this.maxWireVersion >= 1; + } + + get hasWriteCommands(): boolean { + return this.maxWireVersion >= 2; + } + get hasTextSearch(): boolean { + return this.minWireVersion >= 0; + } + + get hasAuthCommands(): boolean { + return this.maxWireVersion >= 1; + } + + get hasListCollectionsCommand(): boolean { + return this.maxWireVersion >= 3; + } + + get hasListIndexesCommand(): boolean { + return this.maxWireVersion >= 3; + } + + get supportsSnapshotReads(): boolean { + return this.maxWireVersion >= 13; + } + + get commandsTakeWriteConcern(): boolean { + return this.maxWireVersion >= 5; + } + + get commandsTakeCollation(): boolean { + return this.maxWireVersion >= 5; + } +} diff --git a/nodejs/node_modules/mongodb/src/sdam/topology_description.ts b/nodejs/node_modules/mongodb/src/sdam/topology_description.ts new file mode 100644 index 00000000..f2fafaf8 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sdam/topology_description.ts @@ -0,0 +1,511 @@ +import type { ObjectId } from '../bson'; +import * as WIRE_CONSTANTS from '../cmap/wire_protocol/constants'; +import { MongoRuntimeError, type MongoServerError } from '../error'; +import { compareObjectId, shuffle } from '../utils'; +import { ServerType, TopologyType } from './common'; +import { ServerDescription } from './server_description'; +import type { SrvPollingEvent } from './srv_polling'; + +// constants related to compatibility checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; + +const MONGOS_OR_UNKNOWN = new Set([ServerType.Mongos, ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([ServerType.Mongos, ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + ServerType.RSSecondary, + ServerType.RSArbiter, + ServerType.RSOther +]); + +/** @public */ +export interface TopologyDescriptionOptions { + heartbeatFrequencyMS?: number; + localThresholdMS?: number; +} + +/** + * Representation of a deployment of servers + * @public + */ +export class TopologyDescription { + type: TopologyType; + setName: string | null; + maxSetVersion: number | null; + maxElectionId: ObjectId | null; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes: number | null; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion: number; + + /** + * Create a TopologyDescription + */ + constructor( + topologyType: TopologyType, + serverDescriptions: Map | null = null, + setName: string | null = null, + maxSetVersion: number | null = null, + maxElectionId: ObjectId | null = null, + commonWireVersion: number | null = null, + options: TopologyDescriptionOptions | null = null + ) { + options = options ?? {}; + + this.type = topologyType ?? TopologyType.Unknown; + this.servers = serverDescriptions ?? new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; + this.localThresholdMS = options.localThresholdMS ?? 15; + this.setName = setName ?? null; + this.maxElectionId = maxElectionId ?? null; + this.maxSetVersion = maxSetVersion ?? null; + this.commonWireVersion = commonWireVersion ?? 0; + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if ( + serverDescription.type === ServerType.Unknown || + serverDescription.type === ServerType.LoadBalancer + ) { + continue; + } + + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from a hello response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + this.logicalSessionTimeoutMinutes = null; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = null; + break; + } + + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min( + this.logicalSessionTimeoutMinutes, + server.logicalSessionTimeoutMinutes + ); + } + } + } + + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev: SrvPollingEvent, srvMaxHosts = 0): TopologyDescription { + /** The SRV addresses defines the set of addresses we should be using */ + const incomingHostnames = ev.hostnames(); + const currentHostnames = new Set(this.servers.keys()); + + const hostnamesToAdd = new Set(incomingHostnames); + const hostnamesToRemove = new Set(); + for (const hostname of currentHostnames) { + // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames + hostnamesToAdd.delete(hostname); + if (!incomingHostnames.has(hostname)) { + // If the SRV Records no longer include this hostname + // we have to stop using it + hostnamesToRemove.add(hostname); + } + } + + if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) { + // No new hosts to add and none to remove + return this; + } + + const serverDescriptions = new Map(this.servers); + for (const removedHost of hostnamesToRemove) { + serverDescriptions.delete(removedHost); + } + + if (hostnamesToAdd.size > 0) { + if (srvMaxHosts === 0) { + // Add all! + for (const hostToAdd of hostnamesToAdd) { + serverDescriptions.set(hostToAdd, new ServerDescription(hostToAdd)); + } + } else if (serverDescriptions.size < srvMaxHosts) { + // Add only the amount needed to get us back to srvMaxHosts + const selectedHosts = shuffle(hostnamesToAdd, srvMaxHosts - serverDescriptions.size); + for (const selectedHostToAdd of selectedHosts) { + serverDescriptions.set(selectedHostToAdd, new ServerDescription(selectedHostToAdd)); + } + } + } + + return new TopologyDescription( + this.type, + serverDescriptions, + this.setName, + this.maxSetVersion, + this.maxElectionId, + this.commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription: ServerDescription): TopologyDescription { + const address = serverDescription.address; + + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + + if ( + typeof serverDescription.setName === 'string' && + typeof setName === 'string' && + serverDescription.setName !== setName + ) { + if (topologyType === TopologyType.Single) { + // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove + serverDescription = new ServerDescription(address); + } else { + serverDescriptions.delete(address); + } + } + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + serverDescription, + setName, + maxSetVersion, + maxElectionId + ); + + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + serverDescription, + setName, + maxSetVersion, + maxElectionId + ); + + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + serverDescription, + setName + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS } + ); + } + + get error(): MongoServerError | null { + const descriptionsWithError = Array.from(this.servers.values()).filter( + (sd: ServerDescription) => sd.error + ); + + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error as MongoServerError; + } + + return null; + } + + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers(): boolean { + return Array.from(this.servers.values()).some( + (sd: ServerDescription) => sd.type !== ServerType.Unknown + ); + } + + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers(): boolean { + return Array.from(this.servers.values()).some((sd: ServerDescription) => sd.isDataBearing); + } + + /** + * Determines if the topology has a definition for the provided address + * @internal + */ + hasServer(address: string): boolean { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType: ServerType): TopologyType { + switch (serverType) { + case ServerType.Standalone: + return TopologyType.Single; + case ServerType.Mongos: + return TopologyType.Sharded; + case ServerType.RSPrimary: + return TopologyType.ReplicaSetWithPrimary; + case ServerType.RSOther: + case ServerType.RSSecondary: + return TopologyType.ReplicaSetNoPrimary; + default: + return TopologyType.Unknown; + } +} + +function updateRsFromPrimary( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName: string | null = null, + maxSetVersion: number | null = null, + maxElectionId: ObjectId | null = null +): [TopologyType, string | null, number | null, ObjectId | null] { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + if (serverDescription.maxWireVersion >= 17) { + const electionIdComparison = compareObjectId(maxElectionId, serverDescription.electionId); + const maxElectionIdIsEqual = electionIdComparison === 0; + const maxElectionIdIsLess = electionIdComparison === -1; + const maxSetVersionIsLessOrEqual = + (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); + + if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) { + // The reported electionId was greater + // or the electionId was equal and reported setVersion was greater + // Always update both values, they are a tuple + maxElectionId = serverDescription.electionId; + maxSetVersion = serverDescription.setVersion; + } else { + // Stale primary + // replace serverDescription with a default ServerDescription of type "Unknown" + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } else { + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if ( + maxSetVersion > serverDescription.setVersion || + compareObjectId(maxElectionId, electionId) > 0 + ) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + } + + // We've heard from the primary. Is it the same primary as before? + for (const [address, server] of serverDescriptions) { + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach((address: string) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses + .filter((addr: string) => responseAddresses.indexOf(addr) === -1) + .forEach((address: string) => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName: string | null = null +): TopologyType { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName: string | null = null +): [TopologyType, string | null] { + const topologyType = TopologyType.ReplicaSetNoPrimary; + setName = setName ?? serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach((address: string) => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions: Map): TopologyType { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} diff --git a/nodejs/node_modules/mongodb/src/sessions.ts b/nodejs/node_modules/mongodb/src/sessions.ts new file mode 100644 index 00000000..e04c802b --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sessions.ts @@ -0,0 +1,1054 @@ +import { promisify } from 'util'; + +import { Binary, type Document, Long, type Timestamp } from './bson'; +import type { CommandOptions, Connection } from './cmap/connection'; +import { ConnectionPoolMetrics } from './cmap/metrics'; +import { isSharded } from './cmap/wire_protocol/shared'; +import { PINNED, UNPINNED } from './constants'; +import type { AbstractCursor } from './cursor/abstract_cursor'; +import { + type AnyError, + isRetryableWriteError, + MongoAPIError, + MongoCompatibilityError, + MONGODB_ERROR_CODES, + type MongoDriverError, + MongoError, + MongoErrorLabel, + MongoExpiredSessionError, + MongoInvalidArgumentError, + MongoRuntimeError, + MongoServerError, + MongoTransactionError, + MongoWriteConcernError +} from './error'; +import type { MongoClient, MongoOptions } from './mongo_client'; +import { TypedEventEmitter } from './mongo_types'; +import { executeOperation } from './operations/execute_operation'; +import { RunAdminCommandOperation } from './operations/run_command'; +import { ReadConcernLevel } from './read_concern'; +import { ReadPreference } from './read_preference'; +import { _advanceClusterTime, type ClusterTime, TopologyType } from './sdam/common'; +import { + isTransactionCommand, + Transaction, + type TransactionOptions, + TxnState +} from './transactions'; +import { + ByteUtils, + calculateDurationInMs, + type Callback, + commandSupportsReadConcern, + isPromiseLike, + List, + maxWireVersion, + now, + uuidV4 +} from './utils'; +import { WriteConcern } from './write_concern'; + +const minWireVersionForShardedTransactions = 8; + +/** @public */ +export interface ClientSessionOptions { + /** Whether causal consistency should be enabled on this session */ + causalConsistency?: boolean; + /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */ + snapshot?: boolean; + /** The default TransactionOptions to use for transactions started on this session. */ + defaultTransactionOptions?: TransactionOptions; + + /** @internal */ + owner?: symbol | AbstractCursor; + /** @internal */ + explicit?: boolean; + /** @internal */ + initialClusterTime?: ClusterTime; +} + +/** @public */ +export type WithTransactionCallback = (session: ClientSession) => Promise; + +/** @public */ +export type ClientSessionEvents = { + ended(session: ClientSession): void; +}; + +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); +/** @internal Accumulates total number of increments to add to txnNumber when applying session to command */ +const kTxnNumberIncrement = Symbol('txnNumberIncrement'); + +/** @public */ +export interface EndSessionOptions { + /** + * An optional error which caused the call to end this session + * @internal + */ + error?: AnyError; + force?: boolean; + forceClear?: boolean; +} + +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +export class ClientSession extends TypedEventEmitter { + /** @internal */ + client: MongoClient; + /** @internal */ + sessionPool: ServerSessionPool; + hasEnded: boolean; + clientOptions?: MongoOptions; + supports: { causalConsistency: boolean }; + clusterTime?: ClusterTime; + operationTime?: Timestamp; + explicit: boolean; + /** @internal */ + owner?: symbol | AbstractCursor; + defaultTransactionOptions: TransactionOptions; + transaction: Transaction; + /** @internal */ + [kServerSession]: ServerSession | null; + /** @internal */ + [kSnapshotTime]?: Timestamp; + /** @internal */ + [kSnapshotEnabled] = false; + /** @internal */ + [kPinnedConnection]?: Connection; + /** @internal */ + [kTxnNumberIncrement]: number; + + /** + * Create a client session. + * @internal + * @param client - The current client + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor( + client: MongoClient, + sessionPool: ServerSessionPool, + options: ClientSessionOptions, + clientOptions?: MongoOptions + ) { + super(); + + if (client == null) { + // TODO(NODE-3483) + throw new MongoRuntimeError('ClientSession requires a MongoClient'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + + options = options ?? {}; + + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new MongoInvalidArgumentError( + 'Properties "causalConsistency" and "snapshot" are mutually exclusive' + ); + } + } + + this.client = client; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + + this.explicit = !!options.explicit; + this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null; + this[kTxnNumberIncrement] = 0; + + const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; + this.supports = { + // if we can enable causal consistency, do so by default + causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue + }; + + this.clusterTime = options.initialClusterTime; + + this.operationTime = undefined; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** The server id associated with this session */ + get id(): ServerSessionId | undefined { + return this[kServerSession]?.id; + } + + get serverSession(): ServerSession { + let serverSession = this[kServerSession]; + if (serverSession == null) { + if (this.explicit) { + throw new MongoRuntimeError('Unexpected null serverSession for an explicit session'); + } + if (this.hasEnded) { + throw new MongoRuntimeError('Unexpected null serverSession for an ended implicit session'); + } + serverSession = this.sessionPool.acquire(); + this[kServerSession] = serverSession; + } + return serverSession; + } + + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled(): boolean { + return this[kSnapshotEnabled]; + } + + get loadBalanced(): boolean { + return this.client.topology?.description.type === TopologyType.LoadBalanced; + } + + /** @internal */ + get pinnedConnection(): Connection | undefined { + return this[kPinnedConnection]; + } + + /** @internal */ + pin(conn: Connection): void { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + + this[kPinnedConnection] = conn; + conn.emit( + PINNED, + this.inTransaction() ? ConnectionPoolMetrics.TXN : ConnectionPoolMetrics.CURSOR + ); + } + + /** @internal */ + unpin(options?: { force?: boolean; forceClear?: boolean; error?: AnyError }): void { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + + this.transaction.unpinServer(); + } + + get isPinned(): boolean { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + */ + async endSession(options?: EndSessionOptions): Promise { + try { + if (this.inTransaction()) { + await this.abortTransaction(); + } + if (!this.hasEnded) { + const serverSession = this[kServerSession]; + if (serverSession != null) { + // release the server session back to the pool + this.sessionPool.release(serverSession); + // Make sure a new serverSession never makes it onto this ClientSession + Object.defineProperty(this, kServerSession, { + value: ServerSession.clone(serverSession), + writable: false + }); + } + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + } + } catch { + // spec indicates that we should ignore all errors for `endSessions` + } finally { + maybeClearPinnedConnection(this, { force: true, ...options }); + } + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime: Timestamp): void { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime: ClusterTime): void { + if (!clusterTime || typeof clusterTime !== 'object') { + throw new MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new MongoInvalidArgumentError( + 'input cluster time "clusterTime" property must be a valid BSON Timestamp' + ); + } + if ( + !clusterTime.signature || + clusterTime.signature.hash?._bsontype !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'bigint' && + typeof clusterTime.signature.keyId !== 'number' && + clusterTime.signature.keyId?._bsontype !== 'Long') // apparently we decode the key to number? + ) { + throw new MongoInvalidArgumentError( + 'input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId' + ); + } + + _advanceClusterTime(this, clusterTime); + } + + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session: ClientSession): boolean { + if (!(session instanceof ClientSession)) { + return false; + } + + if (this.id == null || session.id == null) { + return false; + } + + return ByteUtils.equals(this.id.id.buffer, session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + * + * @privateRemarks + * This helper increments a value stored on the client session that will be + * added to the serverSession's txnNumber upon applying it to a command. + * This is because the serverSession is lazily acquired after a connection is obtained + */ + incrementTransactionNumber(): void { + this[kTxnNumberIncrement] += 1; + } + + /** @returns whether this session is currently in a transaction or not */ + inTransaction(): boolean { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options?: TransactionOptions): void { + if (this[kSnapshotEnabled]) { + throw new MongoCompatibilityError('Transactions are not supported in snapshot sessions'); + } + + if (this.inTransaction()) { + throw new MongoTransactionError('Transaction already in progress'); + } + + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + + const topologyMaxWireVersion = maxWireVersion(this.client.topology); + if ( + isSharded(this.client.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions + ) { + throw new MongoCompatibilityError( + 'Transactions are not supported on sharded clusters in MongoDB < 4.2.' + ); + } + + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new Transaction({ + readConcern: + options?.readConcern ?? + this.defaultTransactionOptions.readConcern ?? + this.clientOptions?.readConcern, + writeConcern: + options?.writeConcern ?? + this.defaultTransactionOptions.writeConcern ?? + this.clientOptions?.writeConcern, + readPreference: + options?.readPreference ?? + this.defaultTransactionOptions.readPreference ?? + this.clientOptions?.readPreference, + maxCommitTimeMS: options?.maxCommitTimeMS ?? this.defaultTransactionOptions.maxCommitTimeMS + }); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + */ + async commitTransaction(): Promise { + return endTransactionAsync(this, 'commitTransaction'); + } + + /** + * Aborts the currently active transaction in this session. + */ + async abortTransaction(): Promise { + return endTransactionAsync(this, 'abortTransaction'); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON(): never { + throw new MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + + /** + * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed. + * + * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations. + * + * @remarks + * This function: + * - If all operations successfully complete and the `commitTransaction` operation is successful, then this function will return the result of the provided function. + * - If the transaction is unable to complete or an error is thrown from within the provided function, then this function will throw an error. + * - If the transaction is manually aborted within the provided function it will not throw. + * - May be called multiple times if the driver needs to attempt to retry the operations. + * + * Checkout a descriptive example here: + * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions + * + * @param fn - callback to run within a transaction + * @param options - optional settings for the transaction + * @returns A raw command response or undefined + */ + async withTransaction( + fn: WithTransactionCallback, + options?: TransactionOptions + ): Promise { + const startTime = now(); + return attemptTransaction(this, startTime, fn, options); + } +} + +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); + +function hasNotTimedOut(startTime: number, max: number) { + return calculateDurationInMs(startTime) < max; +} + +function isUnknownTransactionCommitResult(err: MongoError) { + const isNonDeterministicWriteConcernError = + err instanceof MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + + return ( + isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== MONGODB_ERROR_CODES.UnknownReplWriteConcern) + ); +} + +export function maybeClearPinnedConnection( + session: ClientSession, + options?: EndSessionOptions +): void { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options?.error; + + if ( + session.inTransaction() && + error && + error instanceof MongoError && + error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + return; + } + + const topology = session.client.topology; + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn && topology != null) { + const servers = Array.from(topology.s.servers.values()); + const loadBalancer = servers[0]; + + if (options?.error == null || options?.force) { + loadBalancer.pool.checkIn(conn); + conn.emit( + UNPINNED, + session.transaction.state !== TxnState.NO_TRANSACTION + ? ConnectionPoolMetrics.TXN + : ConnectionPoolMetrics.CURSOR + ); + + if (options?.forceClear) { + loadBalancer.pool.clear({ serviceId: conn.serviceId }); + } + } + + session[kPinnedConnection] = undefined; + } +} + +function isMaxTimeMSExpiredError(err: MongoError) { + if (err == null || !(err instanceof MongoServerError)) { + return false; + } + + return ( + err.code === MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === MONGODB_ERROR_CODES.MaxTimeMSExpired) + ); +} + +function attemptTransactionCommit( + session: ClientSession, + startTime: number, + fn: WithTransactionCallback, + result: any, + options: TransactionOptions +): Promise { + return session.commitTransaction().then( + () => result, + (err: MongoError) => { + if ( + err instanceof MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err) + ) { + if (err.hasErrorLabel(MongoErrorLabel.UnknownTransactionCommitResult)) { + return attemptTransactionCommit(session, startTime, fn, result, options); + } + + if (err.hasErrorLabel(MongoErrorLabel.TransientTransactionError)) { + return attemptTransaction(session, startTime, fn, options); + } + } + + throw err; + } + ); +} + +const USER_EXPLICIT_TXN_END_STATES = new Set([ + TxnState.NO_TRANSACTION, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED +]); + +function userExplicitlyEndedTransaction(session: ClientSession) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} + +function attemptTransaction( + session: ClientSession, + startTime: number, + fn: WithTransactionCallback, + options: TransactionOptions = {} +): Promise { + session.startTransaction(options); + + let promise; + try { + promise = fn(session); + } catch (err) { + promise = Promise.reject(err); + } + + if (!isPromiseLike(promise)) { + session.abortTransaction().catch(() => null); + return Promise.reject( + new MongoInvalidArgumentError('Function provided to `withTransaction` must return a Promise') + ); + } + + return promise.then( + result => { + if (userExplicitlyEndedTransaction(session)) { + return result; + } + + return attemptTransactionCommit(session, startTime, fn, result, options); + }, + err => { + function maybeRetryOrThrow(err: MongoError): Promise { + if ( + err instanceof MongoError && + err.hasErrorLabel(MongoErrorLabel.TransientTransactionError) && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) + ) { + return attemptTransaction(session, startTime, fn, options); + } + + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel(MongoErrorLabel.UnknownTransactionCommitResult); + } + + throw err; + } + + if (session.inTransaction()) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + + return maybeRetryOrThrow(err); + } + ); +} + +const endTransactionAsync = promisify( + endTransaction as ( + session: ClientSession, + commandName: 'abortTransaction' | 'commitTransaction', + callback: (error: Error) => void + ) => void +); + +function endTransaction( + session: ClientSession, + commandName: 'abortTransaction' | 'commitTransaction', + callback: Callback +) { + // handle any initial problematic cases + const txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoTransactionError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback( + new MongoTransactionError('Cannot call commitTransaction after calling abortTransaction') + ); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoTransactionError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback( + new MongoTransactionError('Cannot call abortTransaction after calling commitTransaction') + ); + return; + } + } + + // construct and send the command + const command: Document = { [commandName]: 1 }; + + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } else if (session.clientOptions && session.clientOptions.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + + if (txnState === TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeoutMS: 10000 }, writeConcern, { w: 'majority' }); + } + + if (writeConcern) { + WriteConcern.apply(command, writeConcern); + } + + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + + function commandHandler(error?: Error) { + if (commandName !== 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + if (error instanceof MongoError) { + if ( + isRetryableWriteError(error) || + error instanceof MongoWriteConcernError || + isMaxTimeMSExpiredError(error) + ) { + if (isUnknownTransactionCommitResult(error)) { + error.addErrorLabel(MongoErrorLabel.UnknownTransactionCommitResult); + + // per txns spec, must unpin session in this case + session.unpin({ error }); + } + } else if (error.hasErrorLabel(MongoErrorLabel.TransientTransactionError)) { + session.unpin({ error }); + } + } + + callback(error); + } + + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + + const handleFirstCommandAttempt = (error?: Error) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + + if (error instanceof MongoError && isRetryableWriteError(error)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + + executeOperation( + session.client, + new RunAdminCommandOperation(command, { + session, + readPreference: ReadPreference.primary, + bypassPinningCheck: true + }) + ).then(() => commandHandler(), commandHandler); + return; + } + + commandHandler(error); + }; + + // send the command + executeOperation( + session.client, + new RunAdminCommandOperation(command, { + session, + readPreference: ReadPreference.primary, + bypassPinningCheck: true + }) + ).then(() => handleFirstCommandAttempt(), handleFirstCommandAttempt); +} + +/** @public */ +export type ServerSessionId = { id: Binary }; + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @public + */ +export class ServerSession { + id: ServerSessionId; + lastUse: number; + txnNumber: number; + isDirty: boolean; + + /** @internal */ + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = now(); + this.txnNumber = 0; + this.isDirty = false; + } + + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + hasTimedOut(sessionTimeoutMinutes: number): boolean { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + ((calculateDurationInMs(this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } + + /** + * @internal + * Cloning meant to keep a readable reference to the server session data + * after ClientSession has ended + */ + static clone(serverSession: ServerSession): Readonly { + const arrayBuffer = new ArrayBuffer(16); + const idBytes = Buffer.from(arrayBuffer); + idBytes.set(serverSession.id.id.buffer); + + const id = new Binary(idBytes, serverSession.id.id.sub_type); + + // Manual prototype construction to avoid modifying the constructor of this class + return Object.setPrototypeOf( + { + id: { id }, + lastUse: serverSession.lastUse, + txnNumber: serverSession.txnNumber, + isDirty: serverSession.isDirty + }, + ServerSession.prototype + ); + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +export class ServerSessionPool { + client: MongoClient; + sessions: List; + + constructor(client: MongoClient) { + if (client == null) { + throw new MongoRuntimeError('ServerSessionPool requires a MongoClient'); + } + + this.client = client; + this.sessions = new List(); + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession is created. + */ + acquire(): ServerSession { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + + let session: ServerSession | null = null; + + // Try to obtain from session pool + while (this.sessions.length > 0) { + const potentialSession = this.sessions.shift(); + if ( + potentialSession != null && + (!!this.client.topology?.loadBalanced || + !potentialSession.hasTimedOut(sessionTimeoutMinutes)) + ) { + session = potentialSession; + break; + } + } + + // If nothing valid came from the pool make a new one + if (session == null) { + session = new ServerSession(); + } + + return session; + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * + * @param session - The session to release to the pool + */ + release(session: ServerSession): void { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + + if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + + if (!sessionTimeoutMinutes) { + return; + } + + this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes)); + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + * + * @internal + */ +export function applySession( + session: ClientSession, + command: Document, + options: CommandOptions +): MongoDriverError | undefined { + if (session.hasEnded) { + return new MongoExpiredSessionError(); + } + + // May acquire serverSession here + const serverSession = session.serverSession; + if (serverSession == null) { + return new MongoRuntimeError('Unable to acquire server session'); + } + + if (options.writeConcern?.w === 0) { + if (session && session.explicit) { + // Error if user provided an explicit session to an unacknowledged write (SPEC-1019) + return new MongoAPIError('Cannot have explicit session with unacknowledged writes'); + } + return; + } + + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = now(); + command.lsid = serverSession.id; + + const inTxnOrTxnCommand = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = !!options.willRetryWrite; + + if (isRetryableWrite || inTxnOrTxnCommand) { + serverSession.txnNumber += session[kTxnNumberIncrement]; + session[kTxnNumberIncrement] = 0; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + command.txnNumber = Long.fromNumber(serverSession.txnNumber); + } + + if (!inTxnOrTxnCommand) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + if ( + session.supports.causalConsistency && + session.operationTime && + commandSupportsReadConcern(command) + ) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } else if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); + } + } + + return; + } + + // now attempt to apply transaction-specific sessions data + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session?.clientOptions?.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } + return; +} + +export function updateSessionFromResponse(session: ClientSession, document: Document): void { + if (document.$clusterTime) { + _advanceClusterTime(session, document.$clusterTime); + } + + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } + + if (session?.[kSnapshotEnabled] && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = document.cursor?.atClusterTime || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; + } + } +} diff --git a/nodejs/node_modules/mongodb/src/sort.ts b/nodejs/node_modules/mongodb/src/sort.ts new file mode 100644 index 00000000..6b766b54 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/sort.ts @@ -0,0 +1,132 @@ +import { MongoInvalidArgumentError } from './error'; + +/** @public */ +export type SortDirection = + | 1 + | -1 + | 'asc' + | 'desc' + | 'ascending' + | 'descending' + | { $meta: string }; + +/** @public */ +export type Sort = + | string + | Exclude + | string[] + | { [key: string]: SortDirection } + | Map + | [string, SortDirection][] + | [string, SortDirection]; + +/** Below stricter types were created for sort that correspond with type that the cmd takes */ + +/** @internal */ +export type SortDirectionForCmd = 1 | -1 | { $meta: string }; + +/** @internal */ +export type SortForCmd = Map; + +/** @internal */ +type SortPairForCmd = [string, SortDirectionForCmd]; + +/** @internal */ +function prepareDirection(direction: any = 1): SortDirectionForCmd { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} + +/** @internal */ +function isMeta(t: SortDirection): t is { $meta: string } { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} + +/** @internal */ +function isPair(t: Sort): t is [string, SortDirection] { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; + } catch (e) { + return false; + } + } + return false; +} + +function isDeep(t: Sort): t is [string, SortDirection][] { + return Array.isArray(t) && Array.isArray(t[0]); +} + +function isMap(t: Sort): t is Map { + return t instanceof Map && t.size > 0; +} + +/** @internal */ +function pairToMap(v: [string, SortDirection]): SortForCmd { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} + +/** @internal */ +function deepToMap(t: [string, SortDirection][]): SortForCmd { + const sortEntries: SortPairForCmd[] = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} + +/** @internal */ +function stringsToMap(t: string[]): SortForCmd { + const sortEntries: SortPairForCmd[] = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} + +/** @internal */ +function objectToMap(t: { [key: string]: SortDirection }): SortForCmd { + const sortEntries: SortPairForCmd[] = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} + +/** @internal */ +function mapToMap(t: Map): SortForCmd { + const sortEntries: SortPairForCmd[] = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} + +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +export function formatSort( + sort: Sort | undefined, + direction?: SortDirection +): SortForCmd | undefined { + if (sort == null) return undefined; + if (typeof sort === 'string') return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new MongoInvalidArgumentError( + `Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object` + ); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) return undefined; + if (isDeep(sort)) return deepToMap(sort); + if (isPair(sort)) return pairToMap(sort); + return stringsToMap(sort); +} diff --git a/nodejs/node_modules/mongodb/src/transactions.ts b/nodejs/node_modules/mongodb/src/transactions.ts new file mode 100644 index 00000000..7ee8660b --- /dev/null +++ b/nodejs/node_modules/mongodb/src/transactions.ts @@ -0,0 +1,188 @@ +import type { Document } from './bson'; +import { MongoRuntimeError, MongoTransactionError } from './error'; +import type { CommandOperationOptions } from './operations/command'; +import { ReadConcern, type ReadConcernLike } from './read_concern'; +import type { ReadPreferenceLike } from './read_preference'; +import { ReadPreference } from './read_preference'; +import type { Server } from './sdam/server'; +import { WriteConcern } from './write_concern'; + +/** @internal */ +export const TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +} as const); + +/** @internal */ +export type TxnState = (typeof TxnState)[keyof typeof TxnState]; + +const stateMachine: { [state in TxnState]: TxnState[] } = { + [TxnState.NO_TRANSACTION]: [TxnState.NO_TRANSACTION, TxnState.STARTING_TRANSACTION], + [TxnState.STARTING_TRANSACTION]: [ + TxnState.TRANSACTION_IN_PROGRESS, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.TRANSACTION_ABORTED + ], + [TxnState.TRANSACTION_IN_PROGRESS]: [ + TxnState.TRANSACTION_IN_PROGRESS, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED + ], + [TxnState.TRANSACTION_COMMITTED]: [ + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.STARTING_TRANSACTION, + TxnState.NO_TRANSACTION + ], + [TxnState.TRANSACTION_ABORTED]: [TxnState.STARTING_TRANSACTION, TxnState.NO_TRANSACTION], + [TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.NO_TRANSACTION + ] +}; + +const ACTIVE_STATES: Set = new Set([ + TxnState.STARTING_TRANSACTION, + TxnState.TRANSACTION_IN_PROGRESS +]); + +const COMMITTED_STATES: Set = new Set([ + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_COMMITTED_EMPTY, + TxnState.TRANSACTION_ABORTED +]); + +/** + * Configuration options for a transaction. + * @public + */ +export interface TransactionOptions extends CommandOperationOptions { + // TODO(NODE-3344): These options use the proper class forms of these settings, it should accept the basic enum values too + /** A default read concern for commands in this transaction */ + readConcern?: ReadConcernLike; + /** A default writeConcern for commands in this transaction */ + writeConcern?: WriteConcern; + /** A default read preference for commands in this transaction */ + readPreference?: ReadPreferenceLike; + /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */ + maxCommitTimeMS?: number; +} + +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +export class Transaction { + /** @internal */ + state: TxnState; + options: TransactionOptions; + /** @internal */ + _pinnedServer?: Server; + /** @internal */ + _recoveryToken?: Document; + + /** Create a transaction @internal */ + constructor(options?: TransactionOptions) { + options = options ?? {}; + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new MongoTransactionError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = writeConcern; + } + + if (options.readConcern) { + this.options.readConcern = ReadConcern.fromOptions(options); + } + + if (options.readPreference) { + this.options.readPreference = ReadPreference.fromOptions(options); + } + + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; + } + + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + + /** @internal */ + get server(): Server | undefined { + return this._pinnedServer; + } + + get recoveryToken(): Document | undefined { + return this._recoveryToken; + } + + get isPinned(): boolean { + return !!this.server; + } + + /** @returns Whether the transaction has started */ + get isStarting(): boolean { + return this.state === TxnState.STARTING_TRANSACTION; + } + + /** + * @returns Whether this session is presently in a transaction + */ + get isActive(): boolean { + return ACTIVE_STATES.has(this.state); + } + + get isCommitted(): boolean { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState: TxnState): void { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if ( + this.state === TxnState.NO_TRANSACTION || + this.state === TxnState.STARTING_TRANSACTION || + this.state === TxnState.TRANSACTION_ABORTED + ) { + this.unpinServer(); + } + return; + } + + throw new MongoRuntimeError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } + + /** @internal */ + pinServer(server: Server): void { + if (this.isActive) { + this._pinnedServer = server; + } + } + + /** @internal */ + unpinServer(): void { + this._pinnedServer = undefined; + } +} + +export function isTransactionCommand(command: Document): boolean { + return !!(command.commitTransaction || command.abortTransaction); +} diff --git a/nodejs/node_modules/mongodb/src/utils.ts b/nodejs/node_modules/mongodb/src/utils.ts new file mode 100644 index 00000000..98e3950f --- /dev/null +++ b/nodejs/node_modules/mongodb/src/utils.ts @@ -0,0 +1,1282 @@ +import * as crypto from 'crypto'; +import type { SrvRecord } from 'dns'; +import { type EventEmitter } from 'events'; +import * as http from 'http'; +import { clearTimeout, setTimeout } from 'timers'; +import * as url from 'url'; +import { URL } from 'url'; +import { promisify } from 'util'; + +import { type Document, ObjectId, resolveBSONOptions } from './bson'; +import type { Connection } from './cmap/connection'; +import { MAX_SUPPORTED_WIRE_VERSION } from './cmap/wire_protocol/constants'; +import type { Collection } from './collection'; +import { LEGACY_HELLO_COMMAND } from './constants'; +import type { AbstractCursor } from './cursor/abstract_cursor'; +import type { FindCursor } from './cursor/find_cursor'; +import type { Db } from './db'; +import { + type AnyError, + MongoCompatibilityError, + MongoInvalidArgumentError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoParseError, + MongoRuntimeError +} from './error'; +import type { Explain } from './explain'; +import type { MongoClient } from './mongo_client'; +import type { CommandOperationOptions, OperationParent } from './operations/command'; +import type { Hint, OperationOptions } from './operations/operation'; +import { ReadConcern } from './read_concern'; +import { ReadPreference } from './read_preference'; +import { ServerType } from './sdam/common'; +import type { Server } from './sdam/server'; +import type { Topology } from './sdam/topology'; +import type { ClientSession } from './sessions'; +import { WriteConcern } from './write_concern'; + +/** + * MongoDB Driver style callback + * @public + */ +export type Callback = (error?: AnyError, result?: T) => void; + +export type AnyOptions = Document; + +export const ByteUtils = { + toLocalBufferType(this: void, buffer: Buffer | Uint8Array): Buffer { + return Buffer.isBuffer(buffer) + ? buffer + : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + + equals(this: void, seqA: Uint8Array, seqB: Uint8Array) { + return ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + + compare(this: void, seqA: Uint8Array, seqB: Uint8Array) { + return ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + + toBase64(this: void, uint8array: Uint8Array) { + return ByteUtils.toLocalBufferType(uint8array).toString('base64'); + } +}; + +/** + * Determines if a connection's address matches a user provided list + * of domain wildcards. + */ +export function hostMatchesWildcards(host: string, wildcards: string[]): boolean { + for (const wildcard of wildcards) { + if ( + host === wildcard || + (wildcard.startsWith('*.') && host?.endsWith(wildcard.substring(2, wildcard.length))) || + (wildcard.startsWith('*/') && host?.endsWith(wildcard.substring(2, wildcard.length))) + ) { + return true; + } + } + return false; +} + +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +export function normalizeHintField(hint?: Hint): Hint | undefined { + let finalHint = undefined; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(param => { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {} as Document; + for (const name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +} + +const TO_STRING = (object: unknown) => Object.prototype.toString.call(object); +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ + +export function isObject(arg: unknown): arg is object { + return '[object Object]' === TO_STRING(arg); +} + +/** @internal */ +export function mergeOptions(target: T, source: S): T & S { + return { ...target, ...source }; +} + +/** @internal */ +export function filterOptions(options: AnyOptions, names: ReadonlyArray): AnyOptions { + const filterOptions: AnyOptions = {}; + + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; + } + } + + // Filtered options + return filterOptions; +} + +interface HasRetryableWrites { + retryWrites?: boolean; +} +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +export function applyRetryableWrites(target: T, db?: Db): T { + if (db && db.s.options?.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ + +/** + * Checks if a given value is a Promise + * + * @typeParam T - The resolution type of the possible promise + * @param value - An object that could be a promise + * @returns true if the provided value is a Promise + */ +export function isPromiseLike(value?: unknown): value is PromiseLike { + return ( + value != null && + typeof value === 'object' && + 'then' in value && + typeof value.then === 'function' + ); +} + +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +export function decorateWithCollation( + command: Document, + target: MongoClient | Db | Collection, + options: AnyOptions +): void { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoCompatibilityError(`Current topology does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * @internal + * + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method + */ +export function decorateWithReadConcern( + command: Document, + coll: { s: { readConcern?: ReadConcern } }, + options?: OperationOptions +): void { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +export function decorateWithExplain(command: Document, explain: Explain): Document { + if (command.explain) { + return command; + } + + return { explain: command, verbosity: explain.verbosity }; +} + +/** + * @internal + */ +export type TopologyProvider = + | MongoClient + | ClientSession + | FindCursor + | AbstractCursor + | Collection + | Db; + +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @throws MongoNotConnectedError + * @internal + */ +export function getTopology(provider: TopologyProvider): Topology { + // MongoClient or ClientSession or AbstractCursor + if ('topology' in provider && provider.topology) { + return provider.topology; + } else if ('client' in provider && provider.client.topology) { + return provider.client.topology; + } + + throw new MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} + +/** @internal */ +export function ns(ns: string): MongoDBNamespace { + return MongoDBNamespace.fromString(ns); +} + +/** @public */ +export class MongoDBNamespace { + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(public db: string, public collection?: string) { + this.collection = collection === '' ? undefined : collection; + } + + toString(): string { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + + withCollection(collection: string): MongoDBCollectionNamespace { + return new MongoDBCollectionNamespace(this.db, collection); + } + + static fromString(namespace?: string): MongoDBNamespace { + if (typeof namespace !== 'string' || namespace === '') { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + + const [db, ...collectionParts] = namespace.split('.'); + const collection = collectionParts.join('.'); + return new MongoDBNamespace(db, collection === '' ? undefined : collection); + } +} + +/** + * @public + * + * A class representing a collection's namespace. This class enforces (through Typescript) that + * the `collection` portion of the namespace is defined and should only be + * used in scenarios where this can be guaranteed. + */ +export class MongoDBCollectionNamespace extends MongoDBNamespace { + constructor(db: string, override collection: string) { + super(db, collection); + } + + static override fromString(namespace?: string): MongoDBCollectionNamespace { + return super.fromString(namespace) as MongoDBCollectionNamespace; + } +} + +/** @internal */ +export function* makeCounter(seed = 0): Generator { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} + +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +export function uuidV4(): Buffer { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} + +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +export function maxWireVersion(topologyOrServer?: Connection | Topology | Server): number { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced || topologyOrServer.serverApi?.version) { + // Since we do not have a monitor in the load balanced mode, + // we assume the load-balanced server is always pointed at the latest mongodb version. + // There is a risk that for on-prem deployments + // that don't upgrade immediately that this could alert to the + // application that a feature is available that is actually not. + // We also return the max supported wire version for serverAPI. + return MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.hello) { + return topologyOrServer.hello.maxWireVersion; + } + + if ('lastHello' in topologyOrServer && typeof topologyOrServer.lastHello === 'function') { + const lastHello = topologyOrServer.lastHello(); + if (lastHello) { + return lastHello.maxWireVersion; + } + } + + if ( + topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null + ) { + return topologyOrServer.description.maxWireVersion; + } + } + + return 0; +} + +/** @internal */ +export function arrayStrictEqual(arr: unknown[], arr2: unknown[]): boolean { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { + return false; + } + + return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} + +/** @internal */ +export function errorStrictEqual(lhs?: AnyError | null, rhs?: AnyError | null): boolean { + if (lhs === rhs) { + return true; + } + + if (!lhs || !rhs) { + return lhs === rhs; + } + + if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { + return false; + } + + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + + if (lhs.message !== rhs.message) { + return false; + } + + return true; +} + +interface StateTable { + [key: string]: string[]; +} +interface ObjectWithState { + s: { state: string }; + emit(event: 'stateChanged', state: string, newState: string): void; +} +interface StateTransitionFunction { + (target: ObjectWithState, newState: string): void; +} + +/** @public */ +export type EventEmitterWithState = { + /** @internal */ + stateChanged(previous: string, current: string): void; +}; + +/** @internal */ +export function makeStateMachine(stateTable: StateTable): StateTransitionFunction { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new MongoRuntimeError( + `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` + ); + } + + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} + +/** @internal */ +export function now(): number { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} + +/** @internal */ +export function calculateDurationInMs(started: number | undefined): number { + if (typeof started !== 'number') { + return -1; + } + + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} + +/** @internal */ +export function hasAtomicOperators(doc: Document | Document[]): boolean { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } + } + return false; + } + + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} + +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +export function resolveOptions( + parent: OperationParent | undefined, + options?: T +): T { + const result: T = Object.assign({}, options, resolveBSONOptions(options, parent)); + + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options?.session; + if (!session?.inTransaction()) { + const readConcern = ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + + const writeConcern = WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + + const readPreference = ReadPreference.fromOptions(options) ?? parent?.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + + return result; +} + +export function isSuperset(set: Set | any[], subset: Set | any[]): boolean { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; + } + } + return true; +} + +/** + * Checks if the document is a Hello request + * @internal + */ +export function isHello(doc: Document): boolean { + return doc[LEGACY_HELLO_COMMAND] || doc.hello ? true : false; +} + +/** Returns the items that are uniquely in setA */ +export function setDifference(setA: Iterable, setB: Iterable): Set { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} + +const HAS_OWN = (object: unknown, prop: string) => + Object.prototype.hasOwnProperty.call(object, prop); + +export function isRecord( + value: unknown, + requiredKeys: T +): value is Record; +export function isRecord(value: unknown): value is Record; +export function isRecord( + value: unknown, + requiredKeys: string[] | undefined = undefined +): value is Record { + if (!isObject(value)) { + return false; + } + + const ctor = (value as any).constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + + // Check to see if some method exists from the Object exists + if (!HAS_OWN(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + + if (requiredKeys) { + const keys = Object.keys(value as Record); + return isSuperset(keys, requiredKeys); + } + + return true; +} + +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +export function deepCopy(value: T): T { + if (value == null) { + return value; + } else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)) as unknown as T; + } else if (isRecord(value)) { + const res = {} as any; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + + const ctor = (value as any).constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value as any) as unknown as T; + case 'set': + return new Set(value as any) as unknown as T; + case 'buffer': + return Buffer.from(value as unknown as Buffer) as unknown as T; + } + } + + return value; +} + +type ListNode = { + value: T; + next: ListNode | HeadNode; + prev: ListNode | HeadNode; +}; + +type HeadNode = { + value: null; + next: ListNode; + prev: ListNode; +}; + +/** + * When a list is empty the head is a reference with pointers to itself + * So this type represents that self referential state + */ +type EmptyNode = { + value: null; + next: EmptyNode; + prev: EmptyNode; +}; + +/** + * A sequential list of items in a circularly linked list + * @remarks + * The head node is special, it is always defined and has a value of null. + * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator. + * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero. + * New nodes are declared as object literals with keys always in the same order: next, prev, value. + * @internal + */ +export class List { + private readonly head: HeadNode | EmptyNode; + private count: number; + + get length() { + return this.count; + } + + get [Symbol.toStringTag]() { + return 'List' as const; + } + + constructor() { + this.count = 0; + + // this is carefully crafted: + // declaring a complete and consistently key ordered + // object is beneficial to the runtime optimizations + this.head = { + next: null, + prev: null, + value: null + } as unknown as EmptyNode; + this.head.next = this.head; + this.head.prev = this.head; + } + + toArray() { + return Array.from(this); + } + + toString() { + return `head <=> ${this.toArray().join(' <=> ')} <=> head`; + } + + *[Symbol.iterator](): Generator { + for (const node of this.nodes()) { + yield node.value; + } + } + + private *nodes(): Generator, void, void> { + let ptr: HeadNode | ListNode | EmptyNode = this.head.next; + while (ptr !== this.head) { + // Save next before yielding so that we make removing within iteration safe + const { next } = ptr as ListNode; + yield ptr as ListNode; + ptr = next; + } + } + + /** Insert at end of list */ + push(value: T) { + this.count += 1; + const newNode: ListNode = { + next: this.head as HeadNode, + prev: this.head.prev as ListNode, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + + /** Inserts every item inside an iterable instead of the iterable itself */ + pushMany(iterable: Iterable) { + for (const value of iterable) { + this.push(value); + } + } + + /** Insert at front of list */ + unshift(value: T) { + this.count += 1; + const newNode: ListNode = { + next: this.head.next as ListNode, + prev: this.head as HeadNode, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + + private remove(node: ListNode | EmptyNode): T | null { + if (node === this.head || this.length === 0) { + return null; + } + + this.count -= 1; + + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + + return node.value; + } + + /** Removes the first node at the front of the list */ + shift(): T | null { + return this.remove(this.head.next); + } + + /** Removes the last node at the end of the list */ + pop(): T | null { + return this.remove(this.head.prev); + } + + /** Iterates through the list and removes nodes where filter returns true */ + prune(filter: (value: T) => boolean) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); + } + } + } + + clear() { + this.count = 0; + this.head.next = this.head as EmptyNode; + this.head.prev = this.head as EmptyNode; + } + + /** Returns the first item in the list, does not remove */ + first(): T | null { + // If the list is empty, value will be the head's null + return this.head.next.value; + } + + /** Returns the last item in the list, does not remove */ + last(): T | null { + // If the list is empty, value will be the head's null + return this.head.prev.value; + } +} + +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +export class BufferPool { + private buffers: List; + private totalByteLength: number; + + constructor() { + this.buffers = new List(); + this.totalByteLength = 0; + } + + get length(): number { + return this.totalByteLength; + } + + /** Adds a buffer to the internal buffer pool list */ + append(buffer: Buffer): void { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + + /** + * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, + * otherwise return null. Size can be negative, caller should error check. + */ + getInt32(): number | null { + if (this.totalByteLength < 4) { + return null; + } + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); + } + + // Unlikely case: an int32 is split across buffers. + // Use read and put the returned buffer back on top + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + + // Put it back. + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + + return value; + } + + /** Reads the requested number of bytes, optionally consuming them */ + read(size: number): Buffer { + if (typeof size !== 'number' || size < 0) { + throw new MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + + // oversized request returns empty buffer + if (size > this.totalByteLength) { + return Buffer.alloc(0); + } + + // We know we have enough, we just don't know how it is spread across chunks + // TODO(NODE-4732): alloc API should change based on raw option + const result = Buffer.allocUnsafe(size); + + for (let bytesRead = 0; bytesRead < size; ) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + + result.set(bytes, bytesRead); + + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + + return result; + } +} + +/** @public */ +export class HostAddress { + host: string | undefined = undefined; + port: number | undefined = undefined; + socketPath: string | undefined = undefined; + isIPv6 = false; + + constructor(hostString: string) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + + if (escapedHost.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(escapedHost); + return; + } + + const urlString = `iLoveJS://${escapedHost}`; + let url; + try { + url = new URL(urlString); + } catch (urlError) { + const runtimeError = new MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + + const hostname = url.hostname; + const port = url.port; + + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + + this.host = normalized.toLowerCase(); + + if (typeof port === 'number') { + this.port = port; + } else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } else { + this.port = 27017; + } + + if (this.port === 0) { + throw new MongoParseError('Invalid port (zero) with hostname'); + } + Object.freeze(this); + } + + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new HostAddress('${this.toString()}')`; + } + + toString(): string { + if (typeof this.host === 'string') { + if (this.isIPv6) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; + } + return `${this.socketPath}`; + } + + static fromString(this: void, s: string): HostAddress { + return new HostAddress(s); + } + + static fromHostPort(host: string, port: number): HostAddress { + if (host.includes(':')) { + host = `[${host}]`; // IPv6 address + } + return HostAddress.fromString(`${host}:${port}`); + } + + static fromSrvRecord({ name, port }: SrvRecord): HostAddress { + return HostAddress.fromHostPort(name, port); + } + + toHostPort(): { host: string; port: number } { + if (this.socketPath) { + return { host: this.socketPath, port: 0 }; + } + + const host = this.host ?? ''; + const port = this.port ?? 0; + return { host, port }; + } +} + +export const DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk(): ObjectId { + return new ObjectId(); + } +}; + +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```ts + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +export const MONGODB_WARNING_CODE = 'MONGODB DRIVER' as const; + +/** @internal */ +export function emitWarning(message: string): void { + return process.emitWarning(message, { code: MONGODB_WARNING_CODE } as any); +} + +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +export function emitWarningOnce(message: string): void { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} + +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +export function enumToString(en: Record): string { + return Object.values(en).join(', '); +} + +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +export function supportsRetryableWrites(server?: Server): boolean { + if (!server) { + return false; + } + + if (server.loadBalanced) { + // Loadbalanced topologies will always support retry writes + return true; + } + + if (server.description.logicalSessionTimeoutMinutes != null) { + // that supports sessions + if (server.description.type !== ServerType.Standalone) { + // and that is not a standalone + return true; + } + } + + return false; +} + +/** + * Fisher–Yates Shuffle + * + * Reference: https://bost.ocks.org/mike/shuffle/ + * @param sequence - items to be shuffled + * @param limit - Defaults to `0`. If nonzero shuffle will slice the randomized array e.g, `.slice(0, limit)` otherwise will return the entire randomized array. + */ +export function shuffle(sequence: Iterable, limit = 0): Array { + const items = Array.from(sequence); // shallow copy in order to never shuffle the input + + if (limit > items.length) { + throw new MongoRuntimeError('Limit must be less than the number of items'); + } + + let remainingItemsToShuffle = items.length; + const lowerBound = limit % items.length === 0 ? 1 : items.length - limit; + while (remainingItemsToShuffle > lowerBound) { + // Pick a remaining element + const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); + remainingItemsToShuffle -= 1; + + // And swap it with the current element + const swapHold = items[remainingItemsToShuffle]; + items[remainingItemsToShuffle] = items[randomIndex]; + items[randomIndex] = swapHold; + } + + return limit % items.length === 0 ? items : items.slice(lowerBound); +} + +// TODO(NODE-4936): read concern eligibility for commands should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +export function commandSupportsReadConcern(command: Document): boolean { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; + } + + return false; +} + +/** + * Compare objectIds. `null` is always less + * - `+1 = oid1 is greater than oid2` + * - `-1 = oid1 is less than oid2` + * - `+0 = oid1 is equal oid2` + */ +export function compareObjectId(oid1?: ObjectId | null, oid2?: ObjectId | null): 0 | 1 | -1 { + if (oid1 == null && oid2 == null) { + return 0; + } + + if (oid1 == null) { + return -1; + } + + if (oid2 == null) { + return 1; + } + + return ByteUtils.compare(oid1.id, oid2.id); +} + +export function parseInteger(value: unknown): number | null { + if (typeof value === 'number') return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + + return Number.isNaN(parsedValue) ? null : parsedValue; +} + +export function parseUnsignedInteger(value: unknown): number | null { + const parsedInt = parseInteger(value); + + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; +} + +/** + * Determines whether a provided address matches the provided parent domain. + * + * If a DNS server were to become compromised SRV records would still need to + * advertise addresses that are under the same domain as the srvHost. + * + * @param address - The address to check against a domain + * @param srvHost - The domain to check the provided address against + * @returns Whether the provided address matches the parent domain + */ +export function matchesParentDomain(address: string, srvHost: string): boolean { + // Remove trailing dot if exists on either the resolved address or the srv hostname + const normalizedAddress = address.endsWith('.') ? address.slice(0, address.length - 1) : address; + const normalizedSrvHost = srvHost.endsWith('.') ? srvHost.slice(0, srvHost.length - 1) : srvHost; + + const allCharacterBeforeFirstDot = /^.*?\./; + // Remove all characters before first dot + // Add leading dot back to string so + // an srvHostDomain = '.trusted.site' + // will not satisfy an addressDomain that endsWith '.fake-trusted.site' + const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, '')}`; + const srvHostDomain = `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, '')}`; + + return addressDomain.endsWith(srvHostDomain); +} + +interface RequestOptions { + json?: boolean; + method?: string; + timeout?: number; + headers?: http.OutgoingHttpHeaders; +} + +export async function request(uri: string): Promise>; +export async function request( + uri: string, + options?: { json?: true } & RequestOptions +): Promise>; +export async function request( + uri: string, + options?: { json: false } & RequestOptions +): Promise; +export async function request( + uri: string, + options: RequestOptions = {} +): Promise> { + return new Promise>((resolve, reject) => { + const requestOptions = { + method: 'GET', + timeout: 10000, + json: true, + ...url.parse(uri), + ...options + }; + + const req = http.request(requestOptions, res => { + res.setEncoding('utf8'); + + let data = ''; + res.on('data', d => { + data += d; + }); + + res.once('end', () => { + if (options.json === false) { + resolve(data); + return; + } + + try { + const parsed = JSON.parse(data); + resolve(parsed); + } catch { + // TODO(NODE-3483) + reject(new MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + + req.once('timeout', () => + req.destroy( + new MongoNetworkTimeoutError( + `Network request to ${uri} timed out after ${options.timeout} ms` + ) + ) + ); + req.once('error', error => reject(error)); + req.end(); + }); +} + +/** + * A custom AbortController that aborts after a specified timeout. + * + * If `timeout` is undefined or \<=0, the abort controller never aborts. + * + * This class provides two benefits over the built-in AbortSignal.timeout() method. + * - This class provides a mechanism for cancelling the timeout + * - This class supports infinite timeouts by interpreting a timeout of 0 as infinite. This is + * consistent with existing timeout options in the Node driver (serverSelectionTimeoutMS, for example). + * @internal + */ +export class TimeoutController extends AbortController { + constructor( + timeout = 0, + private timeoutId = timeout > 0 ? setTimeout(() => this.abort(), timeout) : null + ) { + super(); + } + + clear() { + if (this.timeoutId != null) { + clearTimeout(this.timeoutId); + } + this.timeoutId = null; + } +} + +/** @internal */ +export const DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/; +/** @internal */ +export const COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/; + +/** @internal */ +export const DOCUMENT_DB_MSG = + 'You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb'; +/** @internal */ +export const COSMOS_DB_MSG = + 'You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb'; + +/** @internal */ +export function isHostMatch(match: RegExp, host?: string): boolean { + return host && match.test(host.toLowerCase()) ? true : false; +} + +export function promiseWithResolvers() { + let resolve!: Parameters>[0]>[0]; + let reject!: Parameters>[0]>[1]; + const promise = new Promise(function withResolversExecutor(promiseResolve, promiseReject) { + resolve = promiseResolve; + reject = promiseReject; + }); + return { promise, resolve, reject } as const; +} + +export const randomBytes = promisify(crypto.randomBytes); + +/** + * Replicates the events.once helper. + * + * Removes unused signal logic and It **only** supports 0 or 1 argument events. + * + * @param ee - An event emitter that may emit `ev` + * @param name - An event name to wait for + */ +export async function once(ee: EventEmitter, name: string): Promise { + const { promise, resolve, reject } = promiseWithResolvers(); + const onEvent = (data: T) => resolve(data); + const onError = (error: Error) => reject(error); + + ee.once(name, onEvent).once('error', onError); + try { + const res = await promise; + ee.off('error', onError); + return res; + } catch (error) { + ee.off(name, onEvent); + throw error; + } +} diff --git a/nodejs/node_modules/mongodb/src/write_concern.ts b/nodejs/node_modules/mongodb/src/write_concern.ts new file mode 100644 index 00000000..e3a3f551 --- /dev/null +++ b/nodejs/node_modules/mongodb/src/write_concern.ts @@ -0,0 +1,161 @@ +import { type Document } from './bson'; + +/** @public */ +export type W = number | 'majority'; + +/** @public */ +export interface WriteConcernOptions { + /** Write Concern as an object */ + writeConcern?: WriteConcern | WriteConcernSettings; +} + +/** @public */ +export interface WriteConcernSettings { + /** The write concern */ + w?: W; + /** The write concern timeout */ + wtimeoutMS?: number; + /** The journal write concern */ + journal?: boolean; + + // legacy options + /** + * The journal write concern. + * @deprecated Will be removed in the next major version. Please use the journal option. + */ + j?: boolean; + /** + * The write concern timeout. + * @deprecated Will be removed in the next major version. Please use the wtimeoutMS option. + */ + wtimeout?: number; + /** + * The file sync write concern. + * @deprecated Will be removed in the next major version. Please use the journal option. + */ + fsync?: boolean | 1; +} + +export const WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; + +/** The write concern options that decorate the server command. */ +interface CommandWriteConcernOptions { + /** The write concern */ + w?: W; + /** The journal write concern. */ + j?: boolean; + /** The write concern timeout. */ + wtimeout?: number; +} + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://www.mongodb.com/docs/manual/reference/write-concern/ + */ +export class WriteConcern { + /** Request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */ + readonly w?: W; + /** Request acknowledgment that the write operation has been written to the on-disk journal */ + readonly journal?: boolean; + /** Specify a time limit to prevent write operations from blocking indefinitely */ + readonly wtimeoutMS?: number; + /** + * Specify a time limit to prevent write operations from blocking indefinitely. + * @deprecated Will be removed in the next major version. Please use wtimeoutMS. + */ + wtimeout?: number; + /** + * Request acknowledgment that the write operation has been written to the on-disk journal. + * @deprecated Will be removed in the next major version. Please use journal. + */ + j?: boolean; + /** + * Equivalent to the j option. + * @deprecated Will be removed in the next major version. Please use journal. + */ + fsync?: boolean | 1; + + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely + * @param journal - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version. + */ + constructor(w?: W, wtimeoutMS?: number, journal?: boolean, fsync?: boolean | 1) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } else { + this.w = w; + } + } + if (wtimeoutMS != null) { + this.wtimeoutMS = this.wtimeout = wtimeoutMS; + } + if (journal != null) { + this.journal = this.j = journal; + } + if (fsync != null) { + this.journal = this.j = fsync ? true : false; + } + } + + /** + * Apply a write concern to a command document. Will modify and return the command. + */ + static apply(command: Document, writeConcern: WriteConcern): Document { + const wc: CommandWriteConcernOptions = {}; + // The write concern document sent to the server has w/wtimeout/j fields. + if (writeConcern.w != null) wc.w = writeConcern.w; + if (writeConcern.wtimeoutMS != null) wc.wtimeout = writeConcern.wtimeoutMS; + if (writeConcern.journal != null) wc.j = writeConcern.j; + command.writeConcern = wc; + return command; + } + + /** Construct a WriteConcern given an options object. */ + static fromOptions( + options?: WriteConcernOptions | WriteConcern | W, + inherit?: WriteConcernOptions | WriteConcern + ): WriteConcern | undefined { + if (options == null) return undefined; + inherit = inherit ?? {}; + let opts: WriteConcernSettings | WriteConcern | undefined; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } else if (options instanceof WriteConcern) { + opts = options; + } else { + opts = options.writeConcern; + } + const parentOpts: WriteConcern | WriteConcernSettings | undefined = + inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + + const { + w = undefined, + wtimeout = undefined, + j = undefined, + fsync = undefined, + journal = undefined, + wtimeoutMS = undefined + } = { + ...parentOpts, + ...opts + }; + if ( + w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null + ) { + return new WriteConcern(w, wtimeout ?? wtimeoutMS, j ?? journal, fsync); + } + return undefined; + } +} diff --git a/nodejs/node_modules/mongodb/tsconfig.json b/nodejs/node_modules/mongodb/tsconfig.json new file mode 100644 index 00000000..0d08d129 --- /dev/null +++ b/nodejs/node_modules/mongodb/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + "allowJs": true, + "checkJs": false, + "strict": true, + "alwaysStrict": true, + "target": "ES2021", + "module": "commonJS", + "moduleResolution": "node", + "skipLibCheck": true, + "lib": [ + "es2021", + "ES2022.Error" + ], + // We don't make use of tslib helpers, all syntax used is supported by target engine + "importHelpers": false, + "noEmitHelpers": true, + // Never emit error filled code + "noEmitOnError": true, + "outDir": "lib", + // We want the sourcemaps in a separate file + "inlineSourceMap": false, + "sourceMap": true, + // API-Extractor uses declaration maps to report problems in source, no need to distribute + "declaration": true, + "declarationMap": true, + // we include sources in the release + "inlineSources": false, + // Prevents web types from being suggested by vscode. + "types": [ + "node" + ], + "forceConsistentCasingInFileNames": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + // TODO(NODE-3659): Enable useUnknownInCatchVariables and add type assertions or remove unnecessary catch blocks + "useUnknownInCatchVariables": false + }, + "ts-node": { + "transpileOnly": true, + "compiler": "typescript-cached-transpile" + }, + "include": [ + "src/**/*" + ] +} diff --git a/nodejs/node_modules/ms/index.js b/nodejs/node_modules/ms/index.js new file mode 100644 index 00000000..ea734fb7 --- /dev/null +++ b/nodejs/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/nodejs/node_modules/ms/license.md b/nodejs/node_modules/ms/license.md new file mode 100644 index 00000000..fa5d39b6 --- /dev/null +++ b/nodejs/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/ms/package.json b/nodejs/node_modules/ms/package.json new file mode 100644 index 00000000..49971890 --- /dev/null +++ b/nodejs/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/nodejs/node_modules/ms/readme.md b/nodejs/node_modules/ms/readme.md new file mode 100644 index 00000000..0fc1abb3 --- /dev/null +++ b/nodejs/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/nodejs/node_modules/napi-macros/LICENSE b/nodejs/node_modules/napi-macros/LICENSE new file mode 100644 index 00000000..cb757e5d --- /dev/null +++ b/nodejs/node_modules/napi-macros/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/napi-macros/README.md b/nodejs/node_modules/napi-macros/README.md new file mode 100644 index 00000000..16918450 --- /dev/null +++ b/nodejs/node_modules/napi-macros/README.md @@ -0,0 +1,277 @@ +# napi-macros + +Set of utility macros to make writing [N-API](https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html) modules a little easier. + +``` +npm install napi-macros +``` + +Then add the following to your target in your binding.gyp file + +``` +"include_dirs": [ + " +#include + +NAPI_METHOD(times_two) { + NAPI_ARGV(1) + NAPI_ARGV_INT32(number, 0) + + number *= 2; + + NAPI_RETURN_INT32(number) +} + +NAPI_INIT() { + NAPI_EXPORT_FUNCTION(times_two) +} +``` + +Full working example can be found in the [example/](https://github.com/mafintosh/napi-macros/tree/master/example) folder. + +## API + +#### `NAPI_INIT()` + +Setup init boilerplate. Pass the function body after. + +``` c +static char *my_string = "hello"; + +NAPI_INIT() { + EXPORT_STRING(my_string) +} +``` + +#### `NAPI_METHOD(name)` + +Setup method boilerplate. Pass the function body after. + +``` c +NAPI_METHOD(add) { + NAPI_ARGV(2) + NAPI_ARGV_INT32(a, 0) + NAPI_ARGV_INT32(b, 1) + + a = a + b + + NAPI_RETURN_INT32(a) +} +``` + +#### `NAPI_ARGV(n)` + +Setup up argv boilerplate. `n` is how many arguments you are expecting. +Expects the `napi_env` to be in scope as `env` and the `napi_callback_info` to be in scope as `info`. + +#### `NAPI_ARGV_BUFFER(name, index)` + +Get a buffer out of the arguments at the corresponding index. +Sets `char *name` and `size_t name_len` with the buffer and buffer length. + +#### `NAPI_ARGV_BUFFER_CAST(type, name, index)` + +Get a buffer out and cast the pointer to the specified type. +Note that the type should include the pointer star, i.e. + +``` c +NAPI_ARGV_BUFFER_CAST(uv_udp_t *, handle, 0) +``` + +Will cast the 1st argument as `uv_udp_t` pointer. + +#### `NAPI_ARGV_UINT32(name, index)` + +Get an argument as a uint32. +Will throw if argument is not the right type. + +#### `NAPI_ARGV_INT32(name, index)` + +Get an argument as an int32. +Will throw if argument is not the right type. + +#### `NAPI_ARGV_UTF8(name, length, index)` + +Get an argument as a utf8 string. + +`name` will be a `char[length]` array. + +Will throw if argument is not the right type. + +#### `NAPI_ARGV_UTF8_MALLOC(name, index)` + +Get an argument as a utf8 string. + +`name` will be a `char*`. + +Like `NAPI_ARGV_UTF8()` but allocates `name` on the heap using `malloc()`, which should be `free()`'d after usage. + +#### `NAPI_BUFFER_CAST(type, name, var)` + +Same as `NAPI_ARGV_BUFFER_CAST` but takes a generic `napi_value` variable instead of an argv index. + +#### `NAPI_BUFFER(name, var)` + +Same as `NAPI_ARGV_BUFFER` but takes a generic `napi_value` variable instead of an argv index. + +#### `NAPI_UTF8(name, size, var)` + +Same as `NAPI_ARGV_UTF8` but takes a generic `napi_value` variable instead of an argv index. + +#### `NAPI_UTF8_MALLOC(name, var)` + +Same as `NAPI_ARGV_UTF8_MALLOC` but takes a generic `napi_value` variable instead of an argv index. + +#### `NAPI_UINT32(name, var)` + +Same as `NAPI_ARGV_UINT32` but takes a generic `napi_value` variable instead of an argv index. + +#### `NAPI_INT32(name, var)` + +Same as `NAPI_ARGV_INT32` but takes a generic `napi_value` variable instead of an argv index. + +#### `NAPI_EXPORT_FUNCTION(fn)` + +Will export a function in the Init method. Expects the env and `exports` to be in scope. +The name of the exported function is the same name as the c function. + +#### `NAPI_EXPORT_SIZEOF(struct)` + +Export the size of a strict. The exported name is `sizeof_{struct-name}`. + +#### `NAPI_EXPORT_UINT32(name)` + +Export a uint32. +The name of the exported number is the same name as the c variable. + +#### `NAPI_EXPORT_INT32(name)` + +Export an int32. +The name of the exported number is the same name as the c variable. + +#### `NAPI_EXPORT_UTF8(name, len)` + +Export a utf8 string. `len` should be the length of the string. +The name of the exported string is the same name as the c variable. + +#### `NAPI_EXPORT_STRING(name)` + +Export a null terminated string. +The name of the exported string is the same name as the c variable. + +#### `NAPI_EXPORT_SIZEOF(type)` + +Exports `sizeof(type)`. +The name of the exported number is the same name as the c variable. + +#### `NAPI_EXPORT_SIZEOF_STRUCT(structName)` + +Exports `sizeof(struct structName)`. +The name of the exported number is the same name as the c variable. + +#### `NAPI_EXPORT_ALIGNMENTOF(type)` + +Exports the byte alignment of `type`. +The name of the exported number is the same name as the c variable. + +#### `NAPI_EXPORT_ALIGNMENTOF_STRUCT(structName)` + +Exports the byte alignment of `struct structName`. +The name of the exported number is the same name as the c variable. + +#### `NAPI_EXPORT_OFFSETOF(type, name)` + +Exports the byte offset of `name` within `type`. +The name of the exported number is the same name as the c variables. + +#### `NAPI_EXPORT_OFFSETOF_STRUCT(structName, name)` + +Exports the byte offset of `name` within `struct structName`. +The name of the exported number is the same name as the c variables. + +#### `NAPI_FOR_EACH(array, element)` + +Iterate over an array. `array` should be a `napi_value` containing a javascript array +and `element` is the variable name an element will be exposed as. Expects the loop body +to be passed after. + +``` c +napi_value buffers = argv[0] // first argument is a js array +NAPI_FOR_EACH(buffers, buffer) { + NAPI_BUFFER(cbuf, buffer) + printf("cbuf is now a char * pointer: %s\n", cbuf); +} +``` + +#### `NAPI_RETURN_UINT32(name)` + +Returns a uint32. + +#### `NAPI_RETURN_INT32(name)` + +Returns an int32. + +#### `NAPI_RETURN_UTF8(name, len)` + +Return a utf8 string. `len` should be the length of the string. + +#### `NAPI_RETURN_STRING(name)` + +Return a null terminated string. + +#### `NAPI_STATUS_THROWS(call)` + +Checks the return status of any `napi_*` function returning a `napi_status` type. This simplifies using a `napi_status` variable and comparing the result with `napi_ok`. It's used internally but can be used stand alone as well. + +```c +NAPI_STATUS_THROWS( + napi_create_threadsafe_function( + NULL, + callback, + 0, + async_resource_name, + 0, + 3, + 0, + my_finalize, + NULL, + my_callback, + &threadsafe_function + ) +); +``` + +Above example will fail because the first `env` parameter is `NULL` and throw the following error: + +``` +Error: napi_create_threadsafe_function(NULL, callback, 0, async_resource_name, 0, 3, 0, my_finalize, \ +NULL, my_callback, &threadsafe_function) failed! +``` + +#### `NAPI_UV_THROWS(err, fn)` + +Checks if a libuv call fails and if so, throws an error. + +``` c +int err; +NAPI_UV_THROWS(err, uv_ip4_addr((char *) &ip, port, &addr)) +``` + +#### `NAPI_MAKE_CALLBACK(env, async_ctx, ctx, func, argc, argv, result)` + +Same as `napi_make_callback` except it checks if the JS function throw an exception +and triggers a `process.on('uncaughtException')` if so. + +## License + +MIT diff --git a/nodejs/node_modules/napi-macros/example/binding.gyp b/nodejs/node_modules/napi-macros/example/binding.gyp new file mode 100644 index 00000000..375536db --- /dev/null +++ b/nodejs/node_modules/napi-macros/example/binding.gyp @@ -0,0 +1,9 @@ +{ + "targets": [{ + "target_name": "napi_macros_example", + "include_dirs": [ + " +#include + +NAPI_METHOD(times_two) { + NAPI_ARGV(1) + NAPI_ARGV_INT32(number, 0) + + number *= 2; + + NAPI_RETURN_INT32(number) +} + +NAPI_INIT() { + NAPI_EXPORT_FUNCTION(times_two) +} diff --git a/nodejs/node_modules/napi-macros/example/package.json b/nodejs/node_modules/napi-macros/example/package.json new file mode 100644 index 00000000..6d787d1e --- /dev/null +++ b/nodejs/node_modules/napi-macros/example/package.json @@ -0,0 +1,11 @@ +{ + "name": "napi-macros-example", + "version": "0.0.0", + "description": "an example using napi-macros", + "dependencies": { + "node-gyp-build": "^3.2.2" + }, + "scripts": { + "install": "node-gyp-build" + } +} diff --git a/nodejs/node_modules/napi-macros/index.js b/nodejs/node_modules/napi-macros/index.js new file mode 100644 index 00000000..29c169e6 --- /dev/null +++ b/nodejs/node_modules/napi-macros/index.js @@ -0,0 +1 @@ +console.log(require('path').relative('.', __dirname)) diff --git a/nodejs/node_modules/napi-macros/napi-macros.h b/nodejs/node_modules/napi-macros/napi-macros.h new file mode 100644 index 00000000..90f6e0f9 --- /dev/null +++ b/nodejs/node_modules/napi-macros/napi-macros.h @@ -0,0 +1,217 @@ +#ifndef NAPI_MACROS +#define NAPI_MACROS + +#define NAPI_INIT() \ + static void napi_macros_init(napi_env env, napi_value exports); \ + napi_value napi_macros_init_wrap (napi_env env, napi_value exports) { \ + napi_macros_init(env, exports); \ + return exports; \ + } \ + NAPI_MODULE(NODE_GYP_MODULE_NAME, napi_macros_init_wrap) \ + static void napi_macros_init (napi_env env, napi_value exports) + +#define NAPI_MAKE_CALLBACK(env, nil, ctx, cb, n, argv, res) \ + if (napi_make_callback(env, nil, ctx, cb, n, argv, res) == napi_pending_exception) { \ + napi_value fatal_exception; \ + napi_get_and_clear_last_exception(env, &fatal_exception); \ + napi_fatal_exception(env, fatal_exception); \ + } + +#define NAPI_STATUS_THROWS_VOID(call) \ + if ((call) != napi_ok) { \ + napi_throw_error(env, NULL, #call " failed!"); \ + return; \ + } + +#define NAPI_STATUS_THROWS(call) \ + if ((call) != napi_ok) { \ + napi_throw_error(env, NULL, #call " failed!"); \ + return NULL; \ + } + +#define NAPI_METHOD(name) \ + napi_value name (napi_env env, napi_callback_info info) + +#define NAPI_UV_THROWS(err, fn) \ + err = fn; \ + if (err < 0) { \ + napi_throw_error(env, uv_err_name(err), uv_strerror(err)); \ + return NULL; \ + } + +#define NAPI_EXPORT_OFFSETOF(type, name) \ + { \ + napi_value name##_offsetof; \ + type tmp; \ + void *ptr = &(tmp.name); \ + void *ptr_base = &tmp; \ + int offset = (char *) ptr - (char *) ptr_base; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, offset, &name##_offsetof)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, "offsetof_" #type "_" #name, name##_offsetof)) \ + } + +#define NAPI_EXPORT_OFFSETOF_STRUCT(type, name) \ + { \ + napi_value name##_offsetof; \ + struct type tmp; \ + void *ptr = &(tmp.name); \ + void *ptr_base = &tmp; \ + int offset = (char *) ptr - (char *) ptr_base; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, offset, &name##_offsetof)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, "offsetof_struct_" #type "_" #name, name##_offsetof)) \ + } + + +#define NAPI_EXPORT_ALIGNMENTOF(name) \ + { \ + napi_value name##_alignmentof; \ + struct tmp { \ + char a; \ + name b; \ + }; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, sizeof(struct tmp) - sizeof(name), &name##_alignmentof)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, "alignmentof_" #name, name##_alignmentof)) \ + } + +#define NAPI_EXPORT_ALIGNMENTOF_STRUCT(name) \ + { \ + napi_value name##_alignmentof; \ + struct tmp { \ + char a; \ + struct name b; \ + }; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, sizeof(struct tmp) - sizeof(struct name), &name##_alignmentof)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, "alignmentof_" #name, name##_alignmentof)) \ + } + +#define NAPI_EXPORT_SIZEOF(name) \ + { \ + napi_value name##_sizeof; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, sizeof(name), &name##_sizeof)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, "sizeof_" #name, name##_sizeof)) \ + } + +#define NAPI_EXPORT_SIZEOF_STRUCT(name) \ + { \ + napi_value name##_sizeof; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, sizeof(struct name), &name##_sizeof)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, "sizeof_" #name, name##_sizeof)) \ + } + +#define NAPI_EXPORT_UINT32(name) \ + { \ + napi_value name##_uint32; \ + NAPI_STATUS_THROWS_VOID(napi_create_uint32(env, name, &name##_uint32)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, #name, name##_uint32)) \ + } + +#define NAPI_EXPORT_INT32(name) \ + { \ + napi_value name##_int32; \ + NAPI_STATUS_THROWS_VOID(napi_create_int32(env, name, &name##_int32)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, #name, name##_int32)) \ + } + +#define NAPI_EXPORT_FUNCTION(name) \ + { \ + napi_value name##_fn; \ + NAPI_STATUS_THROWS_VOID(napi_create_function(env, NULL, 0, name, NULL, &name##_fn)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, #name, name##_fn)) \ + } + +#define NAPI_EXPORT_UTF8(name, len) \ + { \ + napi_value name##_utf8; \ + NAPI_STATUS_THROWS_VOID(napi_create_string_utf8(env, name, len, &name##_utf8)) \ + NAPI_STATUS_THROWS_VOID(napi_set_named_property(env, exports, #name, name##_utf8)) \ + } + +#define NAPI_EXPORT_STRING(name) \ + NAPI_EXPORT_UTF8(name, NAPI_AUTO_LENGTH) + +#define NAPI_RETURN_INT32(name) \ + napi_value return_int32; \ + NAPI_STATUS_THROWS(napi_create_int32(env, name, &return_int32)) \ + return return_int32; + +#define NAPI_RETURN_UINT32(name) \ + napi_value return_uint32; \ + NAPI_STATUS_THROWS(napi_create_uint32(env, name, &return_uint32)) \ + return return_uint32; + +#define NAPI_RETURN_UTF8(name, len) \ + napi_value return_utf8; \ + NAPI_STATUS_THROWS(napi_create_string_utf8(env, name, len, &return_utf8)) \ + return return_utf8; + +#define NAPI_RETURN_STRING(name) \ + NAPI_RETURN_UTF8(name, NAPI_AUTO_LENGTH) + +#define NAPI_UTF8(name, size, val) \ + char name[size]; \ + size_t name##_len; \ + if (napi_get_value_string_utf8(env, val, (char *) &name, size, &name##_len) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected string"); \ + return NULL; \ + } + +#define NAPI_UTF8_MALLOC(name, val) \ + size_t name##_size = 0; \ + NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, val, NULL, 0, &name##_size)) \ + char* name = (char*)malloc((name##_size + 1) * sizeof(char)); \ + size_t name##_len; \ + NAPI_STATUS_THROWS(napi_get_value_string_utf8(env, val, name, name##_size + 1, &name##_len)) \ + name[name##_size] = '\0'; + +#define NAPI_UINT32(name, val) \ + uint32_t name; \ + if (napi_get_value_uint32(env, val, &name) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected unsigned number"); \ + return NULL; \ + } + +#define NAPI_INT32(name, val) \ + int32_t name; \ + if (napi_get_value_int32(env, val, &name) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected number"); \ + return NULL; \ + } + +#define NAPI_BUFFER_CAST(type, name, val) \ + type name; \ + size_t name##_len; \ + NAPI_STATUS_THROWS(napi_get_buffer_info(env, val, (void **) &name, &name##_len)) + +#define NAPI_BUFFER(name, val) \ + NAPI_BUFFER_CAST(char *, name, val) + +#define NAPI_FOR_EACH(arr, element) \ + uint32_t arr##_len; \ + napi_get_array_length(env, arr, &arr##_len); \ + napi_value element; \ + for (uint32_t i = 0; i < arr##_len && napi_get_element(env, arr, i, &element) == napi_ok; i++) + +#define NAPI_ARGV(n) \ + napi_value argv[n]; \ + size_t argc = n; \ + NAPI_STATUS_THROWS(napi_get_cb_info(env, info, &argc, argv, NULL, NULL)) + +#define NAPI_ARGV_UTF8(name, size, i) \ + NAPI_UTF8(name, size, argv[i]) + +#define NAPI_ARGV_UTF8_MALLOC(name, i) \ + NAPI_UTF8_MALLOC(name, argv[i]) + +#define NAPI_ARGV_UINT32(name, i) \ + NAPI_UINT32(name, argv[i]) + +#define NAPI_ARGV_INT32(name, i) \ + NAPI_INT32(name, argv[i]) + +#define NAPI_ARGV_BUFFER_CAST(type, name, i) \ + NAPI_BUFFER_CAST(type, name, argv[i]) + +#define NAPI_ARGV_BUFFER(name, i) \ + NAPI_ARGV_BUFFER_CAST(char *, name, i) + +#endif diff --git a/nodejs/node_modules/napi-macros/package.json b/nodejs/node_modules/napi-macros/package.json new file mode 100644 index 00000000..03ec47fd --- /dev/null +++ b/nodejs/node_modules/napi-macros/package.json @@ -0,0 +1,18 @@ +{ + "name": "napi-macros", + "version": "2.0.0", + "description": "Set of utility macros to make writing N-API modules a little easier.", + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/napi-macros.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/napi-macros/issues" + }, + "homepage": "https://github.com/mafintosh/napi-macros" +} diff --git a/nodejs/node_modules/node-gyp-build/LICENSE b/nodejs/node_modules/node-gyp-build/LICENSE new file mode 100644 index 00000000..56fce089 --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/node-gyp-build/README.md b/nodejs/node_modules/node-gyp-build/README.md new file mode 100644 index 00000000..99944b71 --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/README.md @@ -0,0 +1,56 @@ +# node-gyp-build + +> Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds. + +``` +npm install node-gyp-build +``` + +[![Build Status](https://travis-ci.org/prebuild/node-gyp-build.svg?branch=master)](https://travis-ci.org/prebuild/node-gyp-build) + +Use together with [`prebuildify`][prebuildify] to easily support prebuilds for your native modules. + +## Usage + +> **Note.** Prebuild names have changed in [`prebuildify@3`][prebuildify] and `node-gyp-build@4`. Please see the documentation below. + +`node-gyp-build` works similar to [`node-gyp build`][node-gyp] except that it will check if a build or prebuild is present before rebuilding your project. + +It's main intended use is as an npm install script and bindings loader for native modules that bundle prebuilds using [`prebuildify`][prebuildify]. + +First add `node-gyp-build` as an install script to your native project + +``` js +{ + ... + "scripts": { + "install": "node-gyp-build" + } +} +``` + +Then in your `index.js`, instead of using the [`bindings`](https://www.npmjs.com/package/bindings) module use `node-gyp-build` to load your binding. + +``` js +var binding = require('node-gyp-build')(__dirname) +``` + +If you do these two things and bundle prebuilds with [`prebuildify`][prebuildify] your native module will work for most platforms +without having to compile on install time AND will work in both node and electron without the need to recompile between usage. + +Users can override `node-gyp-build` and force compiling by doing `npm install --build-from-source`. + +## Supported prebuild names + +If so desired you can bundle more specific flavors, for example `musl` builds to support Alpine, or targeting a numbered ARM architecture version. + +These prebuilds can be bundled in addition to generic prebuilds; `node-gyp-build` will try to find the most specific flavor first. Prebuild filenames are composed of _tags_. The runtime tag takes precedence, as does an `abi` tag over `napi`. For more details on tags, please see [`prebuildify`][prebuildify]. + +Values for the `libc` and `armv` tags are auto-detected but can be overridden through the `LIBC` and `ARM_VERSION` environment variables, respectively. + +## License + +MIT + +[prebuildify]: https://github.com/prebuild/prebuildify +[node-gyp]: https://www.npmjs.com/package/node-gyp diff --git a/nodejs/node_modules/node-gyp-build/bin.js b/nodejs/node_modules/node-gyp-build/bin.js new file mode 100755 index 00000000..bb322d4e --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/bin.js @@ -0,0 +1,75 @@ +#!/usr/bin/env node + +var proc = require('child_process') +var os = require('os') +var path = require('path') + +if (!buildFromSource()) { + proc.exec('node-gyp-build-test', function (err, stdout, stderr) { + if (err) { + if (verbose()) console.error(stderr) + preinstall() + } + }) +} else { + preinstall() +} + +function build () { + var args = [os.platform() === 'win32' ? 'node-gyp.cmd' : 'node-gyp', 'rebuild'] + + try { + args = [ + process.execPath, + path.join(require.resolve('node-gyp/package.json'), '..', require('node-gyp/package.json').bin['node-gyp']), + 'rebuild' + ] + } catch (_) {} + + proc.spawn(args[0], args.slice(1), { stdio: 'inherit' }).on('exit', function (code) { + if (code || !process.argv[3]) process.exit(code) + exec(process.argv[3]).on('exit', function (code) { + process.exit(code) + }) + }) +} + +function preinstall () { + if (!process.argv[2]) return build() + exec(process.argv[2]).on('exit', function (code) { + if (code) process.exit(code) + build() + }) +} + +function exec (cmd) { + if (process.platform !== 'win32') { + var shell = os.platform() === 'android' ? 'sh' : '/bin/sh' + return proc.spawn(shell, ['-c', '--', cmd], { + stdio: 'inherit' + }) + } + + return proc.spawn(process.env.comspec || 'cmd.exe', ['/s', '/c', '"' + cmd + '"'], { + windowsVerbatimArguments: true, + stdio: 'inherit' + }) +} + +function buildFromSource () { + return hasFlag('--build-from-source') +} + +function verbose () { + return hasFlag('--verbose') +} + +function hasFlag (flag) { + if (!process.env.npm_config_argv) return false + + try { + return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1 + } catch (_) { + return false + } +} diff --git a/nodejs/node_modules/node-gyp-build/build-test.js b/nodejs/node_modules/node-gyp-build/build-test.js new file mode 100755 index 00000000..b6622a5c --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/build-test.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +process.env.NODE_ENV = 'test' + +var path = require('path') +var test = null + +try { + var pkg = require(path.join(process.cwd(), 'package.json')) + if (pkg.name && process.env[pkg.name.toUpperCase().replace(/-/g, '_')]) { + process.exit(0) + } + test = pkg.prebuild.test +} catch (err) { + // do nothing +} + +if (test) require(path.join(process.cwd(), test)) +else require('./')() diff --git a/nodejs/node_modules/node-gyp-build/index.js b/nodejs/node_modules/node-gyp-build/index.js new file mode 100644 index 00000000..cd189dd3 --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/index.js @@ -0,0 +1,154 @@ +var fs = require('fs') +var path = require('path') +var os = require('os') + +// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression' +var runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line + +var prebuildsOnly = !!process.env.PREBUILDS_ONLY +var abi = process.versions.modules // TODO: support old node where this is undef +var runtime = isElectron() ? 'electron' : 'node' +var arch = os.arch() +var platform = os.platform() +var libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc') +var armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : process.config.variables.arm_version) || '' +var uv = (process.versions.uv || '').split('.')[0] + +module.exports = load + +function load (dir) { + return runtimeRequire(load.path(dir)) +} + +load.path = function (dir) { + dir = path.resolve(dir || '.') + + try { + var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_') + if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD'] + } catch (err) {} + + if (!prebuildsOnly) { + var release = getFirst(path.join(dir, 'build/Release'), matchBuild) + if (release) return release + + var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild) + if (debug) return debug + } + + // Find most specific flavor first + var prebuilds = path.join(dir, 'prebuilds', platform + '-' + arch) + var parsed = readdirSync(prebuilds).map(parseTags) + var candidates = parsed.filter(matchTags(runtime, abi)) + var winner = candidates.sort(compareTags(runtime))[0] + if (winner) return path.join(prebuilds, winner.file) + + var target = [ + 'platform=' + platform, + 'arch=' + arch, + 'runtime=' + runtime, + 'abi=' + abi, + 'uv=' + uv, + armv ? 'armv=' + armv : '', + 'libc=' + libc + ].filter(Boolean).join(' ') + + throw new Error('No native build was found for ' + target) +} + +function readdirSync (dir) { + try { + return fs.readdirSync(dir) + } catch (err) { + return [] + } +} + +function getFirst (dir, filter) { + var files = readdirSync(dir).filter(filter) + return files[0] && path.join(dir, files[0]) +} + +function matchBuild (name) { + return /\.node$/.test(name) +} + +function parseTags (file) { + var arr = file.split('.') + var extension = arr.pop() + var tags = { file: file, specificity: 0 } + + if (extension !== 'node') return + + for (var i = 0; i < arr.length; i++) { + var tag = arr[i] + + if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') { + tags.runtime = tag + } else if (tag === 'napi') { + tags.napi = true + } else if (tag.slice(0, 3) === 'abi') { + tags.abi = tag.slice(3) + } else if (tag.slice(0, 2) === 'uv') { + tags.uv = tag.slice(2) + } else if (tag.slice(0, 4) === 'armv') { + tags.armv = tag.slice(4) + } else if (tag === 'glibc' || tag === 'musl') { + tags.libc = tag + } else { + continue + } + + tags.specificity++ + } + + return tags +} + +function matchTags (runtime, abi) { + return function (tags) { + if (tags == null) return false + if (tags.runtime !== runtime && !runtimeAgnostic(tags)) return false + if (tags.abi !== abi && !tags.napi) return false + if (tags.uv && tags.uv !== uv) return false + if (tags.armv && tags.armv !== armv) return false + if (tags.libc && tags.libc !== libc) return false + + return true + } +} + +function runtimeAgnostic (tags) { + return tags.runtime === 'node' && tags.napi +} + +function compareTags (runtime) { + // Precedence: non-agnostic runtime, abi over napi, then by specificity. + return function (a, b) { + if (a.runtime !== b.runtime) { + return a.runtime === runtime ? -1 : 1 + } else if (a.abi !== b.abi) { + return a.abi ? -1 : 1 + } else if (a.specificity !== b.specificity) { + return a.specificity > b.specificity ? -1 : 1 + } else { + return 0 + } + } +} + +function isElectron () { + if (process.versions && process.versions.electron) return true + if (process.env.ELECTRON_RUN_AS_NODE) return true + return typeof window !== 'undefined' && window.process && window.process.type === 'renderer' +} + +function isAlpine (platform) { + return platform === 'linux' && fs.existsSync('/etc/alpine-release') +} + +// Exposed for unit tests +// TODO: move to lib +load.parseTags = parseTags +load.matchTags = matchTags +load.compareTags = compareTags diff --git a/nodejs/node_modules/node-gyp-build/optional.js b/nodejs/node_modules/node-gyp-build/optional.js new file mode 100755 index 00000000..8daa04a6 --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/optional.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node + +/* +I am only useful as an install script to make node-gyp not compile for purely optional native deps +*/ + +process.exit(0) diff --git a/nodejs/node_modules/node-gyp-build/package.json b/nodejs/node_modules/node-gyp-build/package.json new file mode 100644 index 00000000..3e95d648 --- /dev/null +++ b/nodejs/node_modules/node-gyp-build/package.json @@ -0,0 +1,29 @@ +{ + "name": "node-gyp-build", + "version": "4.1.1", + "description": "Build tool and bindings loader for node-gyp that supports prebuilds", + "main": "index.js", + "devDependencies": { + "array-shuffle": "^1.0.1", + "standard": "^14.0.0", + "tape": "^4.10.1" + }, + "scripts": { + "test": "standard && node test" + }, + "bin": { + "node-gyp-build": "./bin.js", + "node-gyp-build-optional": "./optional.js", + "node-gyp-build-test": "./build-test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/prebuild/node-gyp-build.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/prebuild/node-gyp-build/issues" + }, + "homepage": "https://github.com/prebuild/node-gyp-build" +} diff --git a/nodejs/node_modules/one-time/LICENSE b/nodejs/node_modules/one-time/LICENSE new file mode 100644 index 00000000..6dc9316a --- /dev/null +++ b/nodejs/node_modules/one-time/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Unshift.io, Arnout Kazemier, the Contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/nodejs/node_modules/one-time/README.md b/nodejs/node_modules/one-time/README.md new file mode 100644 index 00000000..75143adb --- /dev/null +++ b/nodejs/node_modules/one-time/README.md @@ -0,0 +1,88 @@ +# one-time + +Call the supplied function exactly one time. This prevents double callback +execution. This module can be used on both Node.js, React-Native, or browsers +using Browserify. No magical ES5/6 methods used unlike the `once` module does +(except for the async version). + +## Installation + +This module is published to the public npm registry and can be installed +by running: + +```sh +npm install --save one-time +``` + +## Usage (normal) + +Simply supply the function with the function that should only be called one +time: + +```js +var one = require('one-time'); + +function load(file, fn) { + fn = one(fn); + + eventemitter.once('load', fn); + eventemitter.once('error', fn); + + // do stuff + eventemitter.emit('error', new Error('Failed to load, but still finished')); + eventemitter.emit('load'); +} + +function example(fn) { + fn = one(fn); + + fn(); + fn('also receives all arguments'); + fn('it returns the same value') === 'bar'; + fn('never'); + fn('gonna'); + fn('give'); + fn('you'); + fn('up'); +} + +example(function () { + return 'bar' +}); +``` + +## Usage (async) + +The same pattern is available for **async** functions as well, for that you +should import that `one-time/async` version instead. This one is optimized +for **async** and **await** support. It following exactly the same as the +normal version but assumes it's an `async function () {}` that it's wrapping +instead of a regular function, and it will return an `async function() {}` +instead of a regular function. + +```js +import one from 'one-time/async'; + +const fn = one(async function () { + return await example(); +}); + +await fn(); +await fn(); +await fn(); +``` + +### Why not `once`? + +The main reason is that `once` cannot be used in a browser environment unless +it's ES5 compatible. For a module as simple as this I find that unacceptable. In +addition to that it super heavy on the dependency side. So it's totally not +suitable to be used in client side applications. + +In addition to that we make sure that your code stays easy to debug as returned +functions are named in the same way as your supplied functions. Making heap +inspection and stack traces easier to understand. + +## License + +[MIT](LICENSE) diff --git a/nodejs/node_modules/one-time/async.js b/nodejs/node_modules/one-time/async.js new file mode 100644 index 00000000..7370ae31 --- /dev/null +++ b/nodejs/node_modules/one-time/async.js @@ -0,0 +1,43 @@ +'use strict'; + +var name = require('fn.name'); + +/** + * Wrap callbacks to prevent double execution. + * + * @param {Function} fn Function that should only be called once. + * @returns {Function} A async wrapped callback which prevents multiple executions. + * @public + */ +module.exports = function one(fn) { + var called = 0 + , value; + + /** + * The function that prevents double execution. + * + * @async + * @public + */ + async function onetime() { + if (called) return value; + + called = 1; + value = await fn.apply(this, arguments); + fn = null; + + return value; + } + + // + // To make debugging more easy we want to use the name of the supplied + // function. So when you look at the functions that are assigned to event + // listeners you don't see a load of `onetime` functions but actually the + // names of the functions that this module will call. + // + // NOTE: We cannot override the `name` property, as that is `readOnly` + // property, so displayName will have to do. + // + onetime.displayName = name(fn); + return onetime; +}; diff --git a/nodejs/node_modules/one-time/index.js b/nodejs/node_modules/one-time/index.js new file mode 100644 index 00000000..96b2f3dc --- /dev/null +++ b/nodejs/node_modules/one-time/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var name = require('fn.name'); + +/** + * Wrap callbacks to prevent double execution. + * + * @param {Function} fn Function that should only be called once. + * @returns {Function} A wrapped callback which prevents multiple executions. + * @public + */ +module.exports = function one(fn) { + var called = 0 + , value; + + /** + * The function that prevents double execution. + * + * @private + */ + function onetime() { + if (called) return value; + + called = 1; + value = fn.apply(this, arguments); + fn = null; + + return value; + } + + // + // To make debugging more easy we want to use the name of the supplied + // function. So when you look at the functions that are assigned to event + // listeners you don't see a load of `onetime` functions but actually the + // names of the functions that this module will call. + // + // NOTE: We cannot override the `name` property, as that is `readOnly` + // property, so displayName will have to do. + // + onetime.displayName = name(fn); + return onetime; +}; diff --git a/nodejs/node_modules/one-time/package.json b/nodejs/node_modules/one-time/package.json new file mode 100644 index 00000000..bc32a024 --- /dev/null +++ b/nodejs/node_modules/one-time/package.json @@ -0,0 +1,34 @@ +{ + "name": "one-time", + "version": "1.0.0", + "description": "Run the supplied function exactly one time (once)", + "main": "index.js", + "scripts": { + "test:runner": "mocha test.js", + "test:watch": "npm run test:runner -- --watch", + "test": "nyc --reporter=text --reporter=json-summary npm run test:runner" + }, + "repository": { + "type": "git", + "url": "https://github.com/3rd-Eden/one-time.git" + }, + "keywords": [ + "once", + "function", + "single", + "one", + "one-time", + "execution", + "nope" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "devDependencies": { + "assume": "^2.2.0", + "mocha": "^6.1.4", + "nyc": "^14.1.0" + }, + "dependencies": { + "fn.name": "1.x.x" + } +} diff --git a/nodejs/node_modules/prr/.jshintrc b/nodejs/node_modules/prr/.jshintrc new file mode 100644 index 00000000..6a7a956c --- /dev/null +++ b/nodejs/node_modules/prr/.jshintrc @@ -0,0 +1,61 @@ +{ + "predef": [ ] + , "bitwise": false + , "camelcase": false + , "curly": false + , "eqeqeq": false + , "forin": false + , "immed": false + , "latedef": false + , "newcap": true + , "noarg": true + , "noempty": true + , "nonew": true + , "plusplus": false + , "quotmark": true + , "regexp": false + , "undef": true + , "unused": true + , "strict": false + , "trailing": true + , "maxlen": 120 + , "asi": true + , "boss": true + , "debug": true + , "eqnull": true + , "es5": true + , "esnext": true + , "evil": true + , "expr": true + , "funcscope": false + , "globalstrict": false + , "iterator": false + , "lastsemic": true + , "laxbreak": true + , "laxcomma": true + , "loopfunc": true + , "multistr": false + , "onecase": false + , "proto": false + , "regexdash": false + , "scripturl": true + , "smarttabs": false + , "shadow": false + , "sub": true + , "supernew": false + , "validthis": true + , "browser": true + , "couch": false + , "devel": false + , "dojo": false + , "mootools": false + , "node": true + , "nonstandard": true + , "prototypejs": false + , "rhino": false + , "worker": true + , "wsh": false + , "nomen": false + , "onevar": true + , "passfail": false +} \ No newline at end of file diff --git a/nodejs/node_modules/prr/.npmignore b/nodejs/node_modules/prr/.npmignore new file mode 100644 index 00000000..b512c09d --- /dev/null +++ b/nodejs/node_modules/prr/.npmignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/nodejs/node_modules/prr/.travis.yml b/nodejs/node_modules/prr/.travis.yml new file mode 100644 index 00000000..33dcbc3a --- /dev/null +++ b/nodejs/node_modules/prr/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - 0.8 + - "0.10" +branches: + only: + - master +notifications: + email: + - rod@vagg.org \ No newline at end of file diff --git a/nodejs/node_modules/prr/LICENSE.md b/nodejs/node_modules/prr/LICENSE.md new file mode 100644 index 00000000..29b95e39 --- /dev/null +++ b/nodejs/node_modules/prr/LICENSE.md @@ -0,0 +1,11 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2014 Rod Vagg +--------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/prr/README.md b/nodejs/node_modules/prr/README.md new file mode 100644 index 00000000..b9340482 --- /dev/null +++ b/nodejs/node_modules/prr/README.md @@ -0,0 +1,47 @@ +# prr [![Build Status](https://secure.travis-ci.org/rvagg/prr.png)](http://travis-ci.org/rvagg/prr) + +An sensible alternative to `Object.defineProperty()`. Available in npm and Ender as **prr**. + +## Usage + +Set the property `'foo'` (`obj.foo`) to have the value `'bar'` with default options (`'enumerable'`, `'configurable'` and `'writable'` are all `false`): + +```js +prr(obj, 'foo', 'bar') +``` + +Adjust the default options: + +```js +prr(obj, 'foo', 'bar', { enumerable: true, writable: true }) +``` + +Do the same operation for multiple properties: + +```js +prr(obj, { one: 'one', two: 'two' }) +// or with options: +prr(obj, { one: 'one', two: 'two' }, { enumerable: true, writable: true }) +``` + +### Simplify! + +But obviously, having to write out the full options object makes it nearly as bad as the original `Object.defineProperty()` so we can simplify. + +As an alternative method we can use an options string where each character represents a option: `'e'=='enumerable'`, `'c'=='configurable'` and `'w'=='writable'`: + +```js +prr(obj, 'foo', 'bar', 'ew') // enumerable and writable but not configurable +// muliple properties: +prr(obj, { one: 'one', two: 'two' }, 'ewc') // configurable too +``` + +## Where can I use it? + +Anywhere! For pre-ES5 environments *prr* will simply fall-back to an `object[property] = value` so you can get close to what you want. + +*prr* is Ender-compatible so you can include it in your Ender build and `$.prr(...)` or `var prr = require('prr'); prr(...)`. + +## Licence + +prr is Copyright (c) 2013 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licensed under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/nodejs/node_modules/prr/package.json b/nodejs/node_modules/prr/package.json new file mode 100644 index 00000000..5d298e59 --- /dev/null +++ b/nodejs/node_modules/prr/package.json @@ -0,0 +1,26 @@ +{ + "name": "prr", + "description": "A better Object.defineProperty()", + "version": "1.0.1", + "homepage": "https://github.com/rvagg/prr", + "author": "Rod Vagg (https://github.com/rvagg)", + "keywords": [ + "property", + "properties", + "defineProperty", + "ender" + ], + "main": "./prr.js", + "repository": { + "type": "git", + "url": "https://github.com/rvagg/prr.git" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "scripts": { + "test": "node ./test.js" + }, + "license": "MIT" +} diff --git a/nodejs/node_modules/prr/prr.js b/nodejs/node_modules/prr/prr.js new file mode 100644 index 00000000..94f58628 --- /dev/null +++ b/nodejs/node_modules/prr/prr.js @@ -0,0 +1,63 @@ +/*! + * prr + * (c) 2013 Rod Vagg + * https://github.com/rvagg/prr + * License: MIT + */ + +(function (name, context, definition) { + if (typeof module != 'undefined' && module.exports) + module.exports = definition() + else + context[name] = definition() +})('prr', this, function() { + + var setProperty = typeof Object.defineProperty == 'function' + ? function (obj, key, options) { + Object.defineProperty(obj, key, options) + return obj + } + : function (obj, key, options) { // < es5 + obj[key] = options.value + return obj + } + + , makeOptions = function (value, options) { + var oo = typeof options == 'object' + , os = !oo && typeof options == 'string' + , op = function (p) { + return oo + ? !!options[p] + : os + ? options.indexOf(p[0]) > -1 + : false + } + + return { + enumerable : op('enumerable') + , configurable : op('configurable') + , writable : op('writable') + , value : value + } + } + + , prr = function (obj, key, value, options) { + var k + + options = makeOptions(value, options) + + if (typeof key == 'object') { + for (k in key) { + if (Object.hasOwnProperty.call(key, k)) { + options.value = key[k] + setProperty(obj, k, options) + } + } + return obj + } + + return setProperty(obj, key, options) + } + + return prr +}) \ No newline at end of file diff --git a/nodejs/node_modules/prr/test.js b/nodejs/node_modules/prr/test.js new file mode 100644 index 00000000..5222e307 --- /dev/null +++ b/nodejs/node_modules/prr/test.js @@ -0,0 +1,169 @@ +const test = require('tap').test + , prr = require('./') + +test('test prr(o, key, value) form', function (t) { + t.plan(2) + + var o = {} + prr(o, 'foo', 'bar') + t.equal(o.foo, 'bar', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo') + , { + enumerable : false + , configurable : false + , writable : false + , value : 'bar' + } + , 'correct property descriptor' + ) + t.end() +}) + +test('test prr(o, { key: value }) form', function (t) { + t.plan(2) + + var o = {} + prr(o, { foo: 'bar' }) + + t.equal(o.foo, 'bar', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo') + , { + enumerable : false + , configurable : false + , writable : false + , value : 'bar' + } + , 'correct property descriptor' + ) + t.end() +}) + +test('test multiple key:value pairs', function (t) { + var o = { foo: 'bar' } + + prr(o, { one: 'ONE', two: 'TWO', obj: { o: 'o' }}) + + t.deepEqual(o, { foo: 'bar' }, 'properties are not enumerable') + t.equal(o.one, 'ONE', 'correctly set property') + t.equal(o.two, 'TWO', 'correctly set property') + t.deepEqual(o.obj, { o: 'o' }, 'correctly set property') + + ;[ 'one', 'two', 'obj' ].forEach(function (p) { + t.deepEqual( + Object.getOwnPropertyDescriptor(o, p) + , { + enumerable : false + , configurable : false + , writable : false + , value : p == 'obj' ? { o: 'o' } : p.toUpperCase() + } + , 'correct property descriptor' + ) + }) + + t.end() +}) + +test('test descriptor options', function (t) { + var o = {} + + prr(o, 'foo', 'bar', { + enumerable : true + , configurable : false + }) + t.equal(o.foo, 'bar', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo') + , { + enumerable : true + , configurable : false + , writable : false + , value : 'bar' + } + , 'correct property descriptor' + ) + + prr(o, 'foo2', 'bar2', { + enumerable : true + , configurable : true + , writable : false + }) + t.equal(o.foo2, 'bar2', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo2') + , { + enumerable : true + , configurable : true + , writable : false + , value : 'bar2' + } + , 'correct property descriptor' + ) + + prr(o, 'foo3', 'bar3', { + enumerable : true + , configurable : true + , writable : true + }) + t.equal(o.foo3, 'bar3', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo3') + , { + enumerable : true + , configurable : true + , writable : true + , value : 'bar3' + } + , 'correct property descriptor' + ) + + t.end() +}) + + +test('test descriptor options, string form', function (t) { + var o = {} + + prr(o, 'foo', 'bar', 'e') + t.equal(o.foo, 'bar', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo') + , { + enumerable : true + , configurable : false + , writable : false + , value : 'bar' + } + , 'correct property descriptor' + ) + + prr(o, 'foo2', 'bar2', 'ec') + t.equal(o.foo2, 'bar2', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo2') + , { + enumerable : true + , configurable : true + , writable : false + , value : 'bar2' + } + , 'correct property descriptor' + ) + + prr(o, 'foo3', 'bar3', 'ecw') + t.equal(o.foo3, 'bar3', 'correct value') + t.deepEqual( + Object.getOwnPropertyDescriptor(o, 'foo3') + , { + enumerable : true + , configurable : true + , writable : true + , value : 'bar3' + } + , 'correct property descriptor' + ) + + t.end() +}) diff --git a/nodejs/node_modules/punycode/LICENSE-MIT.txt b/nodejs/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 00000000..a41e0a7e --- /dev/null +++ b/nodejs/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/punycode/README.md b/nodejs/node_modules/punycode/README.md new file mode 100644 index 00000000..f611016b --- /dev/null +++ b/nodejs/node_modules/punycode/README.md @@ -0,0 +1,148 @@ +# Punycode.js [![punycode on npm](https://img.shields.io/npm/v/punycode)](https://www.npmjs.com/package/punycode) [![](https://data.jsdelivr.com/v1/package/npm/punycode/badge)](https://www.jsdelivr.com/package/npm/punycode) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +This project provides a CommonJS module that uses ES2015+ features and JavaScript module, which work in modern Node.js versions and browsers. For the old Punycode.js version that offers the same functionality in a UMD build with support for older pre-ES2015 runtimes, including Rhino, Ringo, and Narwhal, see [v1.4.1](https://github.com/mathiasbynens/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +> ⚠️ Note that userland modules don't hide core modules. +> For example, `require('punycode')` still imports the deprecated core module even if you executed `npm install punycode`. +> Use `require('punycode/')` to import userland modules rather than core modules. + +```js +const punycode = require('punycode/'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## For maintainers + +### How to publish a new release + +1. On the `main` branch, bump the version number in `package.json`: + + ```sh + npm version patch -m 'Release v%s' + ``` + + Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/). + + Note that this produces a Git commit + tag. + +1. Push the release commit and tag: + + ```sh + git push && git push --tags + ``` + + Our CI then automatically publishes the new release to npm, under both the [`punycode`](https://www.npmjs.com/package/punycode) and [`punycode.js`](https://www.npmjs.com/package/punycode.js) names. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/nodejs/node_modules/punycode/package.json b/nodejs/node_modules/punycode/package.json new file mode 100644 index 00000000..b8b76fc7 --- /dev/null +++ b/nodejs/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.3.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "jsnext:main": "punycode.es6.js", + "module": "punycode.es6.js", + "engines": { + "node": ">=6" + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/punycode.js.git" + }, + "bugs": "https://github.com/mathiasbynens/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "build": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^3.8.3", + "nyc": "^15.1.0", + "mocha": "^10.2.0" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/nodejs/node_modules/punycode/punycode.es6.js b/nodejs/node_modules/punycode/punycode.es6.js new file mode 100644 index 00000000..dadece25 --- /dev/null +++ b/nodejs/node_modules/punycode/punycode.es6.js @@ -0,0 +1,444 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/nodejs/node_modules/punycode/punycode.js b/nodejs/node_modules/punycode/punycode.js new file mode 100644 index 00000000..a1ef2519 --- /dev/null +++ b/nodejs/node_modules/punycode/punycode.js @@ -0,0 +1,443 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/nodejs/node_modules/readable-stream/CONTRIBUTING.md b/nodejs/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 00000000..f478d58d --- /dev/null +++ b/nodejs/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/nodejs/node_modules/readable-stream/GOVERNANCE.md b/nodejs/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 00000000..16ffb93f --- /dev/null +++ b/nodejs/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/nodejs/node_modules/readable-stream/LICENSE b/nodejs/node_modules/readable-stream/LICENSE new file mode 100644 index 00000000..2873b3b2 --- /dev/null +++ b/nodejs/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/nodejs/node_modules/readable-stream/README.md b/nodejs/node_modules/readable-stream/README.md new file mode 100644 index 00000000..19117c1a --- /dev/null +++ b/nodejs/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/nodejs/node_modules/readable-stream/errors-browser.js b/nodejs/node_modules/readable-stream/errors-browser.js new file mode 100644 index 00000000..fb8e73e1 --- /dev/null +++ b/nodejs/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/nodejs/node_modules/readable-stream/errors.js b/nodejs/node_modules/readable-stream/errors.js new file mode 100644 index 00000000..8471526d --- /dev/null +++ b/nodejs/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/nodejs/node_modules/readable-stream/experimentalWarning.js b/nodejs/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 00000000..78e84149 --- /dev/null +++ b/nodejs/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/nodejs/node_modules/readable-stream/lib/_stream_duplex.js b/nodejs/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 00000000..19abfa60 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/_stream_passthrough.js b/nodejs/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 00000000..24a6bdde --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/_stream_readable.js b/nodejs/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 00000000..df1f608d --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/_stream_transform.js b/nodejs/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 00000000..1ccb7157 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/_stream_writable.js b/nodejs/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 00000000..292415e2 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/nodejs/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 00000000..742c5a46 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/nodejs/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 00000000..69bda497 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/destroy.js b/nodejs/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 00000000..31a17c4d --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.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(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/nodejs/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 00000000..59c671b5 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/from-browser.js b/nodejs/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 00000000..a4ce56f3 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/from.js b/nodejs/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 00000000..0a34ee92 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/pipeline.js b/nodejs/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 00000000..e6f39241 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/state.js b/nodejs/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 00000000..3fbf8927 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/nodejs/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 00000000..9332a3fd --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/nodejs/node_modules/readable-stream/lib/internal/streams/stream.js b/nodejs/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 00000000..ce2ad5b6 --- /dev/null +++ b/nodejs/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/nodejs/node_modules/readable-stream/package.json b/nodejs/node_modules/readable-stream/package.json new file mode 100644 index 00000000..ade59e71 --- /dev/null +++ b/nodejs/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/nodejs/node_modules/readable-stream/readable-browser.js b/nodejs/node_modules/readable-stream/readable-browser.js new file mode 100644 index 00000000..adbf60de --- /dev/null +++ b/nodejs/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/nodejs/node_modules/readable-stream/readable.js b/nodejs/node_modules/readable-stream/readable.js new file mode 100644 index 00000000..9e0ca120 --- /dev/null +++ b/nodejs/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/nodejs/node_modules/safe-buffer/LICENSE b/nodejs/node_modules/safe-buffer/LICENSE new file mode 100644 index 00000000..0c068cee --- /dev/null +++ b/nodejs/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/safe-buffer/README.md b/nodejs/node_modules/safe-buffer/README.md new file mode 100644 index 00000000..e9a81afd --- /dev/null +++ b/nodejs/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/nodejs/node_modules/safe-buffer/index.d.ts b/nodejs/node_modules/safe-buffer/index.d.ts new file mode 100644 index 00000000..e9fed809 --- /dev/null +++ b/nodejs/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/nodejs/node_modules/safe-buffer/index.js b/nodejs/node_modules/safe-buffer/index.js new file mode 100644 index 00000000..f8d3ec98 --- /dev/null +++ b/nodejs/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/nodejs/node_modules/safe-buffer/package.json b/nodejs/node_modules/safe-buffer/package.json new file mode 100644 index 00000000..f2869e25 --- /dev/null +++ b/nodejs/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/nodejs/node_modules/safe-stable-stringify/LICENSE b/nodejs/node_modules/safe-stable-stringify/LICENSE new file mode 100644 index 00000000..99c65e2c --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ruben Bridgewater + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/safe-stable-stringify/esm/package.json b/nodejs/node_modules/safe-stable-stringify/esm/package.json new file mode 100644 index 00000000..4393479d --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/esm/package.json @@ -0,0 +1,4 @@ +{ + "type": "module", + "main": "wrapper.js" +} diff --git a/nodejs/node_modules/safe-stable-stringify/esm/wrapper.d.ts b/nodejs/node_modules/safe-stable-stringify/esm/wrapper.d.ts new file mode 100644 index 00000000..2351eb12 --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/esm/wrapper.d.ts @@ -0,0 +1,4 @@ +import { stringify } from '../index.js' + +export * from '../index.js' +export default stringify diff --git a/nodejs/node_modules/safe-stable-stringify/esm/wrapper.js b/nodejs/node_modules/safe-stable-stringify/esm/wrapper.js new file mode 100644 index 00000000..0cf01f05 --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/esm/wrapper.js @@ -0,0 +1,6 @@ +import cjsModule from '../index.js' + +export const configure = cjsModule.configure + +export const stringify = cjsModule +export default cjsModule diff --git a/nodejs/node_modules/safe-stable-stringify/index.d.ts b/nodejs/node_modules/safe-stable-stringify/index.d.ts new file mode 100644 index 00000000..442bda5e --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/index.d.ts @@ -0,0 +1,22 @@ +export type Replacer = (number | string)[] | null | undefined | ((key: string, value: unknown) => string | number | boolean | null | object) + +export function stringify(value: undefined | symbol | ((...args: unknown[]) => unknown), replacer?: Replacer, space?: string | number): undefined +export function stringify(value: string | number | unknown[] | null | boolean | object, replacer?: Replacer, space?: string | number): string +export function stringify(value: unknown, replacer?: ((key: string, value: unknown) => unknown) | (number | string)[] | null | undefined, space?: string | number): string | undefined + +export interface StringifyOptions { + bigint?: boolean, + circularValue?: string | null | TypeErrorConstructor | ErrorConstructor, + deterministic?: boolean, + maximumBreadth?: number, + maximumDepth?: number, + strict?: boolean, +} + +export namespace stringify { + export function configure(options: StringifyOptions): typeof stringify +} + +export function configure(options: StringifyOptions): typeof stringify + +export default stringify diff --git a/nodejs/node_modules/safe-stable-stringify/index.js b/nodejs/node_modules/safe-stable-stringify/index.js new file mode 100644 index 00000000..707daa0e --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/index.js @@ -0,0 +1,612 @@ +'use strict' + +const { hasOwnProperty } = Object.prototype + +const stringify = configure() + +// @ts-expect-error +stringify.configure = configure +// @ts-expect-error +stringify.stringify = stringify + +// @ts-expect-error +stringify.default = stringify + +// @ts-expect-error used for named export +exports.stringify = stringify +// @ts-expect-error used for named export +exports.configure = configure + +module.exports = stringify + +// eslint-disable-next-line no-control-regex +const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/ + +// Escape C0 control characters, double quotes, the backslash and every code +// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF. +function strEscape (str) { + // Some magic numbers that worked out fine while benchmarking with v8 8.0 + if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) { + return `"${str}"` + } + return JSON.stringify(str) +} + +function insertSort (array) { + // Insertion sort is very efficient for small input sizes but it has a bad + // worst case complexity. Thus, use native array sort for bigger values. + if (array.length > 2e2) { + return array.sort() + } + for (let i = 1; i < array.length; i++) { + const currentValue = array[i] + let position = i + while (position !== 0 && array[position - 1] > currentValue) { + array[position] = array[position - 1] + position-- + } + array[position] = currentValue + } + return array +} + +const typedArrayPrototypeGetSymbolToStringTag = + Object.getOwnPropertyDescriptor( + Object.getPrototypeOf( + Object.getPrototypeOf( + new Int8Array() + ) + ), + Symbol.toStringTag + ).get + +function isTypedArrayWithEntries (value) { + return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0 +} + +function stringifyTypedArray (array, separator, maximumBreadth) { + if (array.length < maximumBreadth) { + maximumBreadth = array.length + } + const whitespace = separator === ',' ? '' : ' ' + let res = `"0":${whitespace}${array[0]}` + for (let i = 1; i < maximumBreadth; i++) { + res += `${separator}"${i}":${whitespace}${array[i]}` + } + return res +} + +function getCircularValueOption (options) { + if (hasOwnProperty.call(options, 'circularValue')) { + const circularValue = options.circularValue + if (typeof circularValue === 'string') { + return `"${circularValue}"` + } + if (circularValue == null) { + return circularValue + } + if (circularValue === Error || circularValue === TypeError) { + return { + toString () { + throw new TypeError('Converting circular structure to JSON') + } + } + } + throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined') + } + return '"[Circular]"' +} + +function getBooleanOption (options, key) { + let value + if (hasOwnProperty.call(options, key)) { + value = options[key] + if (typeof value !== 'boolean') { + throw new TypeError(`The "${key}" argument must be of type boolean`) + } + } + return value === undefined ? true : value +} + +function getPositiveIntegerOption (options, key) { + let value + if (hasOwnProperty.call(options, key)) { + value = options[key] + if (typeof value !== 'number') { + throw new TypeError(`The "${key}" argument must be of type number`) + } + if (!Number.isInteger(value)) { + throw new TypeError(`The "${key}" argument must be an integer`) + } + if (value < 1) { + throw new RangeError(`The "${key}" argument must be >= 1`) + } + } + return value === undefined ? Infinity : value +} + +function getItemCount (number) { + if (number === 1) { + return '1 item' + } + return `${number} items` +} + +function getUniqueReplacerSet (replacerArray) { + const replacerSet = new Set() + for (const value of replacerArray) { + if (typeof value === 'string' || typeof value === 'number') { + replacerSet.add(String(value)) + } + } + return replacerSet +} + +function getStrictOption (options) { + if (hasOwnProperty.call(options, 'strict')) { + const value = options.strict + if (typeof value !== 'boolean') { + throw new TypeError('The "strict" argument must be of type boolean') + } + if (value) { + return (value) => { + let message = `Object can not safely be stringified. Received type ${typeof value}` + if (typeof value !== 'function') message += ` (${value.toString()})` + throw new Error(message) + } + } + } +} + +function configure (options) { + options = { ...options } + const fail = getStrictOption(options) + if (fail) { + if (options.bigint === undefined) { + options.bigint = false + } + if (!('circularValue' in options)) { + options.circularValue = Error + } + } + const circularValue = getCircularValueOption(options) + const bigint = getBooleanOption(options, 'bigint') + const deterministic = getBooleanOption(options, 'deterministic') + const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth') + const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth') + + function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) { + let value = parent[key] + + if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { + value = value.toJSON(key) + } + value = replacer.call(parent, key, value) + + switch (typeof value) { + case 'string': + return strEscape(value) + case 'object': { + if (value === null) { + return 'null' + } + if (stack.indexOf(value) !== -1) { + return circularValue + } + + let res = '' + let join = ',' + const originalIndentation = indentation + + if (Array.isArray(value)) { + if (value.length === 0) { + return '[]' + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"' + } + stack.push(value) + if (spacer !== '') { + indentation += spacer + res += `\n${indentation}` + join = `,\n${indentation}` + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth) + let i = 0 + for (; i < maximumValuesToStringify - 1; i++) { + const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation) + res += tmp !== undefined ? tmp : 'null' + res += join + } + const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation) + res += tmp !== undefined ? tmp : 'null' + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1 + res += `${join}"... ${getItemCount(removedKeys)} not stringified"` + } + if (spacer !== '') { + res += `\n${originalIndentation}` + } + stack.pop() + return `[${res}]` + } + + let keys = Object.keys(value) + const keyLength = keys.length + if (keyLength === 0) { + return '{}' + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"' + } + let whitespace = '' + let separator = '' + if (spacer !== '') { + indentation += spacer + join = `,\n${indentation}` + whitespace = ' ' + } + const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth) + if (deterministic && !isTypedArrayWithEntries(value)) { + keys = insertSort(keys) + } + stack.push(value) + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key = keys[i] + const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation) + if (tmp !== undefined) { + res += `${separator}${strEscape(key)}:${whitespace}${tmp}` + separator = join + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth + res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"` + separator = join + } + if (spacer !== '' && separator.length > 1) { + res = `\n${indentation}${res}\n${originalIndentation}` + } + stack.pop() + return `{${res}}` + } + case 'number': + return isFinite(value) ? String(value) : fail ? fail(value) : 'null' + case 'boolean': + return value === true ? 'true' : 'false' + case 'undefined': + return undefined + case 'bigint': + if (bigint) { + return String(value) + } + // fallthrough + default: + return fail ? fail(value) : undefined + } + } + + function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) { + if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') { + value = value.toJSON(key) + } + + switch (typeof value) { + case 'string': + return strEscape(value) + case 'object': { + if (value === null) { + return 'null' + } + if (stack.indexOf(value) !== -1) { + return circularValue + } + + const originalIndentation = indentation + let res = '' + let join = ',' + + if (Array.isArray(value)) { + if (value.length === 0) { + return '[]' + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"' + } + stack.push(value) + if (spacer !== '') { + indentation += spacer + res += `\n${indentation}` + join = `,\n${indentation}` + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth) + let i = 0 + for (; i < maximumValuesToStringify - 1; i++) { + const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation) + res += tmp !== undefined ? tmp : 'null' + res += join + } + const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation) + res += tmp !== undefined ? tmp : 'null' + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1 + res += `${join}"... ${getItemCount(removedKeys)} not stringified"` + } + if (spacer !== '') { + res += `\n${originalIndentation}` + } + stack.pop() + return `[${res}]` + } + stack.push(value) + let whitespace = '' + if (spacer !== '') { + indentation += spacer + join = `,\n${indentation}` + whitespace = ' ' + } + let separator = '' + for (const key of replacer) { + const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation) + if (tmp !== undefined) { + res += `${separator}${strEscape(key)}:${whitespace}${tmp}` + separator = join + } + } + if (spacer !== '' && separator.length > 1) { + res = `\n${indentation}${res}\n${originalIndentation}` + } + stack.pop() + return `{${res}}` + } + case 'number': + return isFinite(value) ? String(value) : fail ? fail(value) : 'null' + case 'boolean': + return value === true ? 'true' : 'false' + case 'undefined': + return undefined + case 'bigint': + if (bigint) { + return String(value) + } + // fallthrough + default: + return fail ? fail(value) : undefined + } + } + + function stringifyIndent (key, value, stack, spacer, indentation) { + switch (typeof value) { + case 'string': + return strEscape(value) + case 'object': { + if (value === null) { + return 'null' + } + if (typeof value.toJSON === 'function') { + value = value.toJSON(key) + // Prevent calling `toJSON` again. + if (typeof value !== 'object') { + return stringifyIndent(key, value, stack, spacer, indentation) + } + if (value === null) { + return 'null' + } + } + if (stack.indexOf(value) !== -1) { + return circularValue + } + const originalIndentation = indentation + + if (Array.isArray(value)) { + if (value.length === 0) { + return '[]' + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"' + } + stack.push(value) + indentation += spacer + let res = `\n${indentation}` + const join = `,\n${indentation}` + const maximumValuesToStringify = Math.min(value.length, maximumBreadth) + let i = 0 + for (; i < maximumValuesToStringify - 1; i++) { + const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation) + res += tmp !== undefined ? tmp : 'null' + res += join + } + const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation) + res += tmp !== undefined ? tmp : 'null' + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1 + res += `${join}"... ${getItemCount(removedKeys)} not stringified"` + } + res += `\n${originalIndentation}` + stack.pop() + return `[${res}]` + } + + let keys = Object.keys(value) + const keyLength = keys.length + if (keyLength === 0) { + return '{}' + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"' + } + indentation += spacer + const join = `,\n${indentation}` + let res = '' + let separator = '' + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth) + if (isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, join, maximumBreadth) + keys = keys.slice(value.length) + maximumPropertiesToStringify -= value.length + separator = join + } + if (deterministic) { + keys = insertSort(keys) + } + stack.push(value) + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key = keys[i] + const tmp = stringifyIndent(key, value[key], stack, spacer, indentation) + if (tmp !== undefined) { + res += `${separator}${strEscape(key)}: ${tmp}` + separator = join + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth + res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"` + separator = join + } + if (separator !== '') { + res = `\n${indentation}${res}\n${originalIndentation}` + } + stack.pop() + return `{${res}}` + } + case 'number': + return isFinite(value) ? String(value) : fail ? fail(value) : 'null' + case 'boolean': + return value === true ? 'true' : 'false' + case 'undefined': + return undefined + case 'bigint': + if (bigint) { + return String(value) + } + // fallthrough + default: + return fail ? fail(value) : undefined + } + } + + function stringifySimple (key, value, stack) { + switch (typeof value) { + case 'string': + return strEscape(value) + case 'object': { + if (value === null) { + return 'null' + } + if (typeof value.toJSON === 'function') { + value = value.toJSON(key) + // Prevent calling `toJSON` again + if (typeof value !== 'object') { + return stringifySimple(key, value, stack) + } + if (value === null) { + return 'null' + } + } + if (stack.indexOf(value) !== -1) { + return circularValue + } + + let res = '' + + if (Array.isArray(value)) { + if (value.length === 0) { + return '[]' + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"' + } + stack.push(value) + const maximumValuesToStringify = Math.min(value.length, maximumBreadth) + let i = 0 + for (; i < maximumValuesToStringify - 1; i++) { + const tmp = stringifySimple(String(i), value[i], stack) + res += tmp !== undefined ? tmp : 'null' + res += ',' + } + const tmp = stringifySimple(String(i), value[i], stack) + res += tmp !== undefined ? tmp : 'null' + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1 + res += `,"... ${getItemCount(removedKeys)} not stringified"` + } + stack.pop() + return `[${res}]` + } + + let keys = Object.keys(value) + const keyLength = keys.length + if (keyLength === 0) { + return '{}' + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"' + } + let separator = '' + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth) + if (isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, ',', maximumBreadth) + keys = keys.slice(value.length) + maximumPropertiesToStringify -= value.length + separator = ',' + } + if (deterministic) { + keys = insertSort(keys) + } + stack.push(value) + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key = keys[i] + const tmp = stringifySimple(key, value[key], stack) + if (tmp !== undefined) { + res += `${separator}${strEscape(key)}:${tmp}` + separator = ',' + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth + res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"` + } + stack.pop() + return `{${res}}` + } + case 'number': + return isFinite(value) ? String(value) : fail ? fail(value) : 'null' + case 'boolean': + return value === true ? 'true' : 'false' + case 'undefined': + return undefined + case 'bigint': + if (bigint) { + return String(value) + } + // fallthrough + default: + return fail ? fail(value) : undefined + } + } + + function stringify (value, replacer, space) { + if (arguments.length > 1) { + let spacer = '' + if (typeof space === 'number') { + spacer = ' '.repeat(Math.min(space, 10)) + } else if (typeof space === 'string') { + spacer = space.slice(0, 10) + } + if (replacer != null) { + if (typeof replacer === 'function') { + return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '') + } + if (Array.isArray(replacer)) { + return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '') + } + } + if (spacer.length !== 0) { + return stringifyIndent('', value, [], spacer, '') + } + } + return stringifySimple('', value, []) + } + + return stringify +} diff --git a/nodejs/node_modules/safe-stable-stringify/package.json b/nodejs/node_modules/safe-stable-stringify/package.json new file mode 100644 index 00000000..8eb08d39 --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/package.json @@ -0,0 +1,65 @@ +{ + "name": "safe-stable-stringify", + "version": "2.4.3", + "description": "Deterministic and safely JSON.stringify to quickly serialize JavaScript objects", + "exports": { + "require": "./index.js", + "import": "./esm/wrapper.js" + }, + "keywords": [ + "stable", + "stringify", + "JSON", + "JSON.stringify", + "safe", + "serialize", + "deterministic", + "circular", + "object", + "predicable", + "repeatable", + "fast", + "bigint" + ], + "main": "index.js", + "scripts": { + "test": "standard && tap test.js", + "tap": "tap test.js", + "tap:only": "tap test.js --watch --only", + "benchmark": "node benchmark.js", + "compare": "node compare.js", + "lint": "standard --fix", + "tsc": "tsc --project tsconfig.json" + }, + "engines": { + "node": ">=10" + }, + "author": "Ruben Bridgewater", + "license": "MIT", + "typings": "index.d.ts", + "devDependencies": { + "@types/json-stable-stringify": "^1.0.34", + "@types/node": "^18.11.18", + "benchmark": "^2.1.4", + "clone": "^2.1.2", + "fast-json-stable-stringify": "^2.1.0", + "fast-safe-stringify": "^2.1.1", + "fast-stable-stringify": "^1.0.0", + "faster-stable-stringify": "^1.0.0", + "fastest-stable-stringify": "^2.0.2", + "json-stable-stringify": "^1.0.1", + "json-stringify-deterministic": "^1.0.7", + "json-stringify-safe": "^5.0.1", + "standard": "^16.0.4", + "tap": "^15.0.9", + "typescript": "^4.8.3" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/BridgeAR/safe-stable-stringify.git" + }, + "bugs": { + "url": "https://github.com/BridgeAR/safe-stable-stringify/issues" + }, + "homepage": "https://github.com/BridgeAR/safe-stable-stringify#readme" +} diff --git a/nodejs/node_modules/safe-stable-stringify/readme.md b/nodejs/node_modules/safe-stable-stringify/readme.md new file mode 100644 index 00000000..7fc84192 --- /dev/null +++ b/nodejs/node_modules/safe-stable-stringify/readme.md @@ -0,0 +1,177 @@ +# safe-stable-stringify + +Safe, deterministic and fast serialization alternative to [JSON.stringify][]. +Zero dependencies. ESM and CJS. 100% coverage. + +Gracefully handles circular structures and bigint instead of throwing. + +Optional custom circular values, deterministic behavior or strict JSON +compatibility check. + +## stringify(value[, replacer[, space]]) + +The same as [JSON.stringify][]. + +* `value` {any} +* `replacer` {string[]|function|null} +* `space` {number|string} +* Returns: {string} + +```js +const stringify = require('safe-stable-stringify') + +const bigint = { a: 0, c: 2n, b: 1 } + +stringify(bigint) +// '{"a":0,"b":1,"c":2}' +JSON.stringify(bigint) +// TypeError: Do not know how to serialize a BigInt + +const circular = { b: 1, a: 0 } +circular.circular = circular + +stringify(circular) +// '{"a":0,"b":1,"circular":"[Circular]"}' +JSON.stringify(circular) +// TypeError: Converting circular structure to JSON + +stringify(circular, ['a', 'b'], 2) +// { +// "a": 0, +// "b": 1 +// } +``` + +## stringify.configure(options) + +* `bigint` {boolean} If `true`, bigint values are converted to a number. Otherwise + they are ignored. **Default:** `true`. +* `circularValue` {string|null|undefined|ErrorConstructor} Defines the value for + circular references. Set to `undefined`, circular properties are not + serialized (array entries are replaced with `null`). Set to `Error`, to throw + on circular references. **Default:** `'[Circular]'`. +* `deterministic` {boolean} If `true`, guarantee a deterministic key order + instead of relying on the insertion order. **Default:** `true`. +* `maximumBreadth` {number} Maximum number of entries to serialize per object + (at least one). The serialized output contains information about how many + entries have not been serialized. Ignored properties are counted as well + (e.g., properties with symbol values). Using the array replacer overrules this + option. **Default:** `Infinity` +* `maximumDepth` {number} Maximum number of object nesting levels (at least 1) + that will be serialized. Objects at the maximum level are serialized as + `'[Object]'` and arrays as `'[Array]'`. **Default:** `Infinity` +* `strict` {boolean} Instead of handling any JSON value gracefully, throw an + error in case it may not be represented as JSON (functions, NaN, ...). + Circular values and bigint values throw as well in case either option is not + explicitly defined. Sets and Maps are not detected! **Default:** `false` +* Returns: {function} A stringify function with the options applied. + +```js +import { configure } from 'safe-stable-stringify' + +const stringify = configure({ + bigint: true, + circularValue: 'Magic circle!', + deterministic: false, + maximumDepth: 1, + maximumBreadth: 4 +}) + +const circular = { + bigint: 999_999_999_999_999_999n, + typed: new Uint8Array(3), + deterministic: "I don't think so", +} +circular.circular = circular +circular.ignored = true +circular.alsoIgnored = 'Yes!' + +const stringified = stringify(circular, null, 4) + +console.log(stringified) +// { +// "bigint": 999999999999999999, +// "typed": "[Object]", +// "deterministic": "I don't think so", +// "circular": "Magic circle!", +// "...": "2 items not stringified" +// } + +const throwOnCircular = configure({ + circularValue: Error +}) + +throwOnCircular(circular); +// TypeError: Converting circular structure to JSON +``` + +## Differences to JSON.stringify + +1. _Circular values_ are replaced with the string `[Circular]` (configurable). +1. _Object keys_ are sorted instead of using the insertion order (configurable). +1. _BigInt_ values are stringified as regular number instead of throwing a + TypeError (configurable). +1. _Boxed primitives_ (e.g., `Number(5)`) are not unboxed and are handled as + regular object. + +Those are the only differences to `JSON.stringify()`. This is a side effect free +variant and [`toJSON`][], [`replacer`][] and the [`spacer`][] work the same as +with `JSON.stringify()`. + +## Performance / Benchmarks + +Currently this is by far the fastest known stable (deterministic) stringify +implementation. This is especially important for big objects and TypedArrays. + +(Dell Precision 5540, i7-9850H CPU @ 2.60GHz, Node.js 16.11.1) + +```md +simple: simple object x 3,463,894 ops/sec ±0.44% (98 runs sampled) +simple: circular x 1,236,007 ops/sec ±0.46% (99 runs sampled) +simple: deep x 18,942 ops/sec ±0.41% (93 runs sampled) +simple: deep circular x 18,690 ops/sec ±0.72% (96 runs sampled) + +replacer: simple object x 2,664,940 ops/sec ±0.31% (98 runs sampled) +replacer: circular x 1,015,981 ops/sec ±0.09% (99 runs sampled) +replacer: deep x 17,328 ops/sec ±0.38% (97 runs sampled) +replacer: deep circular x 17,071 ops/sec ±0.21% (98 runs sampled) + +array: simple object x 3,869,608 ops/sec ±0.22% (98 runs sampled) +array: circular x 3,853,943 ops/sec ±0.45% (96 runs sampled) +array: deep x 3,563,227 ops/sec ±0.20% (100 runs sampled) +array: deep circular x 3,286,475 ops/sec ±0.07% (100 runs sampled) + +indentation: simple object x 2,183,162 ops/sec ±0.66% (97 runs sampled) +indentation: circular x 872,538 ops/sec ±0.57% (98 runs sampled) +indentation: deep x 16,795 ops/sec ±0.48% (93 runs sampled) +indentation: deep circular x 16,443 ops/sec ±0.40% (97 runs sampled) +``` + +Comparing `safe-stable-stringify` with known alternatives: + +```md +fast-json-stable-stringify x 18,765 ops/sec ±0.71% (94 runs sampled) +json-stable-stringify x 13,870 ops/sec ±0.72% (94 runs sampled) +fast-stable-stringify x 21,343 ops/sec ±0.33% (95 runs sampled) +faster-stable-stringify x 17,707 ops/sec ±0.44% (97 runs sampled) +json-stringify-deterministic x 11,208 ops/sec ±0.57% (98 runs sampled) +fast-safe-stringify x 21,460 ops/sec ±0.75% (99 runs sampled) +this x 30,367 ops/sec ±0.39% (96 runs sampled) + +The fastest is this +``` + +The `fast-safe-stringify` comparison uses the modules stable implementation. + +## Acknowledgements + +Sponsored by [MaibornWolff](https://www.maibornwolff.de/) and [nearForm](http://nearform.com) + +## License + +MIT + +[`replacer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter +[`spacer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20space%20argument +[`toJSON`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior +[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify diff --git a/nodejs/node_modules/simple-swizzle/LICENSE b/nodejs/node_modules/simple-swizzle/LICENSE new file mode 100644 index 00000000..1b77e5be --- /dev/null +++ b/nodejs/node_modules/simple-swizzle/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/simple-swizzle/README.md b/nodejs/node_modules/simple-swizzle/README.md new file mode 100644 index 00000000..7624577b --- /dev/null +++ b/nodejs/node_modules/simple-swizzle/README.md @@ -0,0 +1,39 @@ +# simple-swizzle [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-simple-swizzle.svg?style=flat-square)](https://travis-ci.org/Qix-/node-simple-swizzle) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-simple-swizzle.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-simple-swizzle) + +> [Swizzle](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) your function arguments; pass in mixed arrays/values and get a clean array + +## Usage + +```js +var swizzle = require('simple-swizzle'); + +function myFunc() { + var args = swizzle(arguments); + // ... + return args; +} + +myFunc(1, [2, 3], 4); // [1, 2, 3, 4] +myFunc(1, 2, 3, 4); // [1, 2, 3, 4] +myFunc([1, 2, 3, 4]); // [1, 2, 3, 4] +``` + +Functions can also be wrapped to automatically swizzle arguments and be passed +the resulting array. + +```js +var swizzle = require('simple-swizzle'); + +var swizzledFn = swizzle.wrap(function (args) { + // ... + return args; +}); + +swizzledFn(1, [2, 3], 4); // [1, 2, 3, 4] +swizzledFn(1, 2, 3, 4); // [1, 2, 3, 4] +swizzledFn([1, 2, 3, 4]); // [1, 2, 3, 4] +``` + +## License +Licensed under the [MIT License](http://opensource.org/licenses/MIT). +You can find a copy of it in [LICENSE](LICENSE). diff --git a/nodejs/node_modules/simple-swizzle/index.js b/nodejs/node_modules/simple-swizzle/index.js new file mode 100644 index 00000000..4d6b8ff7 --- /dev/null +++ b/nodejs/node_modules/simple-swizzle/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var isArrayish = require('is-arrayish'); + +var concat = Array.prototype.concat; +var slice = Array.prototype.slice; + +var swizzle = module.exports = function swizzle(args) { + var results = []; + + for (var i = 0, len = args.length; i < len; i++) { + var arg = args[i]; + + if (isArrayish(arg)) { + // http://jsperf.com/javascript-array-concat-vs-push/98 + results = concat.call(results, slice.call(arg)); + } else { + results.push(arg); + } + } + + return results; +}; + +swizzle.wrap = function (fn) { + return function () { + return fn(swizzle(arguments)); + }; +}; diff --git a/nodejs/node_modules/simple-swizzle/package.json b/nodejs/node_modules/simple-swizzle/package.json new file mode 100644 index 00000000..795ae4cc --- /dev/null +++ b/nodejs/node_modules/simple-swizzle/package.json @@ -0,0 +1,36 @@ +{ + "name": "simple-swizzle", + "description": "Simply swizzle your arguments", + "version": "0.2.2", + "author": "Qix (http://github.com/qix-)", + "keywords": [ + "argument", + "arguments", + "swizzle", + "swizzling", + "parameter", + "parameters", + "mixed", + "array" + ], + "license": "MIT", + "scripts": { + "pretest": "xo", + "test": "mocha --compilers coffee:coffee-script/register" + }, + "files": [ + "index.js" + ], + "repository": "qix-/node-simple-swizzle", + "devDependencies": { + "coffee-script": "^1.9.3", + "coveralls": "^2.11.2", + "istanbul": "^0.3.17", + "mocha": "^2.2.5", + "should": "^7.0.1", + "xo": "^0.7.1" + }, + "dependencies": { + "is-arrayish": "^0.3.1" + } +} diff --git a/nodejs/node_modules/sparse-bitfield/.npmignore b/nodejs/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/nodejs/node_modules/sparse-bitfield/.travis.yml b/nodejs/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 00000000..c0428217 --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/nodejs/node_modules/sparse-bitfield/LICENSE b/nodejs/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 00000000..bae9da7b --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/sparse-bitfield/README.md b/nodejs/node_modules/sparse-bitfield/README.md new file mode 100644 index 00000000..7b6b8f9e --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/README.md @@ -0,0 +1,62 @@ +# sparse-bitfield + +Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields +without allocating a massive buffer. If you want to simple implementation of a flat bitfield +see the [bitfield](https://github.com/fb55/bitfield) module. + +This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. + +``` +npm install sparse-bitfield +``` + +[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) + +## Usage + +``` js +var bitfield = require('sparse-bitfield') +var bits = bitfield() + +bits.set(0, true) // set first bit +bits.set(1, true) // set second bit +bits.set(1000000000000, true) // set the 1.000.000.000.000th bit +``` + +Running the above example will allocate two 1kb buffers internally. +Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. + +## API + +#### `var bits = bitfield([options])` + +Create a new bitfield. Options include + +``` js +{ + pageSize: 1024, // how big should the partial buffers be + buffer: anExistingBitfield, + trackUpdates: false // track when pages are being updated in the pager +} +``` + +#### `bits.set(index, value)` + +Set a bit to true or false. + +#### `bits.get(index)` + +Get the value of a bit. + +#### `bits.pages` + +A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. +If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. + +#### `var buffer = bits.toBuffer()` + +Get a single buffer representing the entire bitfield. + +## License + +MIT diff --git a/nodejs/node_modules/sparse-bitfield/index.js b/nodejs/node_modules/sparse-bitfield/index.js new file mode 100644 index 00000000..ff458c97 --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/index.js @@ -0,0 +1,95 @@ +var pager = require('memory-pager') + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(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 = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} diff --git a/nodejs/node_modules/sparse-bitfield/package.json b/nodejs/node_modules/sparse-bitfield/package.json new file mode 100644 index 00000000..092a23f6 --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/package.json @@ -0,0 +1,27 @@ +{ + "name": "sparse-bitfield", + "version": "3.0.3", + "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", + "main": "index.js", + "dependencies": { + "memory-pager": "^1.0.2" + }, + "devDependencies": { + "buffer-alloc": "^1.1.0", + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/sparse-bitfield.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/sparse-bitfield/issues" + }, + "homepage": "https://github.com/mafintosh/sparse-bitfield" +} diff --git a/nodejs/node_modules/sparse-bitfield/test.js b/nodejs/node_modules/sparse-bitfield/test.js new file mode 100644 index 00000000..ae42ef46 --- /dev/null +++ b/nodejs/node_modules/sparse-bitfield/test.js @@ -0,0 +1,79 @@ +var alloc = require('buffer-alloc') +var tape = require('tape') +var bitfield = require('./') + +tape('set and get', function (t) { + var bits = bitfield() + + t.same(bits.get(0), false, 'first bit is false') + bits.set(0, true) + t.same(bits.get(0), true, 'first bit is true') + t.same(bits.get(1), false, 'second bit is false') + bits.set(0, false) + t.same(bits.get(0), false, 'first bit is reset') + t.end() +}) + +tape('set large and get', function (t) { + var bits = bitfield() + + t.same(bits.get(9999999999999), false, 'large bit is false') + bits.set(9999999999999, true) + t.same(bits.get(9999999999999), true, 'large bit is true') + t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') + bits.set(9999999999999, false) + t.same(bits.get(9999999999999), false, 'large bit is reset') + t.end() +}) + +tape('get and set buffer', function (t) { + var bits = bitfield({trackUpdates: true}) + + t.same(bits.pages.get(0, true), undefined) + t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) + bits.set(9999999999999, true) + + var bits2 = bitfield() + var upd = bits.pages.lastUpdate() + bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) + t.same(bits2.get(9999999999999), true, 'bit is set') + t.end() +}) + +tape('toBuffer', function (t) { + var bits = bitfield() + + t.same(bits.toBuffer(), alloc(0)) + + bits.set(0, true) + + t.same(bits.toBuffer(), bits.pages.get(0).buffer) + + bits.set(9000, true) + + t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) + t.end() +}) + +tape('pass in buffer', function (t) { + var bits = bitfield() + + bits.set(0, true) + bits.set(9000, true) + + var clone = bitfield(bits.toBuffer()) + + t.same(clone.get(0), true) + t.same(clone.get(9000), true) + t.end() +}) + +tape('set small buffer', function (t) { + var buf = alloc(1) + buf[0] = 255 + var bits = bitfield(buf) + + t.same(bits.get(0), true) + t.same(bits.pages.get(0).buffer.length, bits.pageSize) + t.end() +}) diff --git a/nodejs/node_modules/stack-trace/.npmignore b/nodejs/node_modules/stack-trace/.npmignore new file mode 100644 index 00000000..b59f7e3a --- /dev/null +++ b/nodejs/node_modules/stack-trace/.npmignore @@ -0,0 +1 @@ +test/ \ No newline at end of file diff --git a/nodejs/node_modules/stack-trace/License b/nodejs/node_modules/stack-trace/License new file mode 100644 index 00000000..11ec094e --- /dev/null +++ b/nodejs/node_modules/stack-trace/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/nodejs/node_modules/stack-trace/Makefile b/nodejs/node_modules/stack-trace/Makefile new file mode 100644 index 00000000..a7ce31d3 --- /dev/null +++ b/nodejs/node_modules/stack-trace/Makefile @@ -0,0 +1,11 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +release: + git push + git push --tags + npm publish . + +.PHONY: test diff --git a/nodejs/node_modules/stack-trace/Readme.md b/nodejs/node_modules/stack-trace/Readme.md new file mode 100644 index 00000000..fcd1b97c --- /dev/null +++ b/nodejs/node_modules/stack-trace/Readme.md @@ -0,0 +1,98 @@ +# stack-trace + +Get v8 stack traces as an array of CallSite objects. + +## Install + +``` bash +npm install stack-trace +``` + +## Usage + +The stack-trace module makes it easy for you to capture the current stack: + +``` javascript +var stackTrace = require('stack-trace'); +var trace = stackTrace.get(); + +require('assert').strictEqual(trace[0].getFileName(), __filename); +``` + +However, sometimes you have already popped the stack you are interested in, +and all you have left is an `Error` object. This module can help: + +``` javascript +var stackTrace = require('stack-trace'); +var err = new Error('something went wrong'); +var trace = stackTrace.parse(err); + +require('assert').strictEqual(trace[0].getFileName(), __filename); +``` + +Please note that parsing the `Error#stack` property is not perfect, only +certain properties can be retrieved with it as noted in the API docs below. + +## Long stack traces + +stack-trace works great with [long-stack-traces][], when parsing an `err.stack` +that has crossed the event loop boundary, a `CallSite` object returning +`'----------------------------------------'` for `getFileName()` is created. +All other methods of the event loop boundary call site return `null`. + +[long-stack-traces]: https://github.com/tlrobinson/long-stack-traces + +## API + +### stackTrace.get([belowFn]) + +Returns an array of `CallSite` objects, where element `0` is the current call +site. + +When passing a function on the current stack as the `belowFn` parameter, the +returned array will only include `CallSite` objects below this function. + +### stackTrace.parse(err) + +Parses the `err.stack` property of an `Error` object into an array compatible +with those returned by `stackTrace.get()`. However, only the following methods +are implemented on the returned `CallSite` objects. + +* getTypeName +* getFunctionName +* getMethodName +* getFileName +* getLineNumber +* getColumnNumber +* isNative + +Note: Except `getFunctionName()`, all of the above methods return exactly the +same values as you would get from `stackTrace.get()`. `getFunctionName()` +is sometimes a little different, but still useful. + +### CallSite + +The official v8 CallSite object API can be found [here][v8stackapi]. A quick +excerpt: + +> A CallSite object defines the following methods: +> +> * **getThis**: returns the value of this +> * **getTypeName**: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. +> * **getFunction**: returns the current function +> * **getFunctionName**: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. +> * **getMethodName**: returns the name of the property of this or one of its prototypes that holds the current function +> * **getFileName**: if this function was defined in a script returns the name of the script +> * **getLineNumber**: if this function was defined in a script returns the current line number +> * **getColumnNumber**: if this function was defined in a script returns the current column number +> * **getEvalOrigin**: if this function was created using a call to eval returns a CallSite object representing the location where eval was called +> * **isToplevel**: is this a toplevel invocation, that is, is this the global object? +> * **isEval**: does this call take place in code defined by a call to eval? +> * **isNative**: is this call in native V8 code? +> * **isConstructor**: is this a constructor call? + +[v8stackapi]: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + +## License + +stack-trace is licensed under the MIT license. diff --git a/nodejs/node_modules/stack-trace/lib/stack-trace.js b/nodejs/node_modules/stack-trace/lib/stack-trace.js new file mode 100644 index 00000000..cbadd58f --- /dev/null +++ b/nodejs/node_modules/stack-trace/lib/stack-trace.js @@ -0,0 +1,136 @@ +exports.get = function(belowFn) { + var oldLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + + var dummyObject = {}; + + var v8Handler = Error.prepareStackTrace; + Error.prepareStackTrace = function(dummyObject, v8StackTrace) { + return v8StackTrace; + }; + Error.captureStackTrace(dummyObject, belowFn || exports.get); + + var v8StackTrace = dummyObject.stack; + Error.prepareStackTrace = v8Handler; + Error.stackTraceLimit = oldLimit; + + return v8StackTrace; +}; + +exports.parse = function(err) { + if (!err.stack) { + return []; + } + + var self = this; + var lines = err.stack.split('\n').slice(1); + + return lines + .map(function(line) { + if (line.match(/^\s*[-]{4,}$/)) { + return self._createParsedCallSite({ + fileName: line, + lineNumber: null, + functionName: null, + typeName: null, + methodName: null, + columnNumber: null, + 'native': null, + }); + } + + var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return; + } + + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = (lineMatch[5] === 'native'); + + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart-1] == '.') + methodStart--; + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = null; + } + + if (method) { + typeName = object; + methodName = method; + } + + if (method === '') { + methodName = null; + functionName = null; + } + + var properties = { + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3], 10) || null, + functionName: functionName, + typeName: typeName, + methodName: methodName, + columnNumber: parseInt(lineMatch[4], 10) || null, + 'native': isNative, + }; + + return self._createParsedCallSite(properties); + }) + .filter(function(callSite) { + return !!callSite; + }); +}; + +function CallSite(properties) { + for (var property in properties) { + this[property] = properties[property]; + } +} + +var strProperties = [ + 'this', + 'typeName', + 'functionName', + 'methodName', + 'fileName', + 'lineNumber', + 'columnNumber', + 'function', + 'evalOrigin' +]; +var boolProperties = [ + 'topLevel', + 'eval', + 'native', + 'constructor' +]; +strProperties.forEach(function (property) { + CallSite.prototype[property] = null; + CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () { + return this[property]; + } +}); +boolProperties.forEach(function (property) { + CallSite.prototype[property] = false; + CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () { + return this[property]; + } +}); + +exports._createParsedCallSite = function(properties) { + return new CallSite(properties); +}; diff --git a/nodejs/node_modules/stack-trace/package.json b/nodejs/node_modules/stack-trace/package.json new file mode 100644 index 00000000..9cd0d074 --- /dev/null +++ b/nodejs/node_modules/stack-trace/package.json @@ -0,0 +1,21 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "stack-trace", + "description": "Get v8 stack traces as an array of CallSite objects.", + "version": "0.0.10", + "homepage": "https://github.com/felixge/node-stack-trace", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-stack-trace.git" + }, + "main": "./lib/stack-trace", + "engines": { + "node": "*" + }, + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "far": "0.0.3", + "long-stack-traces": "0.1.2" + } +} diff --git a/nodejs/node_modules/string_decoder/LICENSE b/nodejs/node_modules/string_decoder/LICENSE new file mode 100644 index 00000000..778edb20 --- /dev/null +++ b/nodejs/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/nodejs/node_modules/string_decoder/README.md b/nodejs/node_modules/string_decoder/README.md new file mode 100644 index 00000000..5fd58315 --- /dev/null +++ b/nodejs/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/nodejs/node_modules/string_decoder/lib/string_decoder.js b/nodejs/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 00000000..2e89e63f --- /dev/null +++ b/nodejs/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.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(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + 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 enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/nodejs/node_modules/string_decoder/package.json b/nodejs/node_modules/string_decoder/package.json new file mode 100644 index 00000000..b2bb1411 --- /dev/null +++ b/nodejs/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/nodejs/node_modules/text-hex/LICENSE b/nodejs/node_modules/text-hex/LICENSE new file mode 100644 index 00000000..bfb9d773 --- /dev/null +++ b/nodejs/node_modules/text-hex/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 Arnout Kazemier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/text-hex/README.md b/nodejs/node_modules/text-hex/README.md new file mode 100644 index 00000000..bb867054 --- /dev/null +++ b/nodejs/node_modules/text-hex/README.md @@ -0,0 +1,20 @@ +# text-hex + +Transforms a given piece of text to a hex color. + +## Install + +``` +npm install text-hex +``` + +## Usage + +```js +var hex = require('text-hex'); +console.log(hex('foo')); +``` + +## License + +MIT diff --git a/nodejs/node_modules/text-hex/index.js b/nodejs/node_modules/text-hex/index.js new file mode 100644 index 00000000..5bec54d3 --- /dev/null +++ b/nodejs/node_modules/text-hex/index.js @@ -0,0 +1,24 @@ +'use strict'; + +/*** + * Convert string to hex color. + * + * @param {String} str Text to hash and convert to hex. + * @returns {String} + * @api public + */ +module.exports = function hex(str) { + for ( + var i = 0, hash = 0; + i < str.length; + hash = str.charCodeAt(i++) + ((hash << 5) - hash) + ); + + var color = Math.floor( + Math.abs( + (Math.sin(hash) * 10000) % 1 * 16777216 + ) + ).toString(16); + + return '#' + Array(6 - color.length + 1).join('0') + color; +}; diff --git a/nodejs/node_modules/text-hex/package.json b/nodejs/node_modules/text-hex/package.json new file mode 100644 index 00000000..cbbcfcea --- /dev/null +++ b/nodejs/node_modules/text-hex/package.json @@ -0,0 +1,30 @@ +{ + "name": "text-hex", + "version": "1.0.0", + "description": "Generate a hex color from the given text", + "main": "index.js", + "scripts": { + "test": "mocha --reporter spec --ui bdd test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/3rd-Eden/text-hex" + }, + "keywords": [ + "css", + "color", + "hex", + "text" + ], + "author": "Arnout Kazemier", + "license": "MIT", + "bugs": { + "url": "https://github.com/3rd-Eden/text-hex/issues" + }, + "homepage": "https://github.com/3rd-Eden/text-hex", + "devDependencies": { + "assume": "2.1.x", + "mocha": "5.2.x", + "pre-commit": "1.2.x" + } +} diff --git a/nodejs/node_modules/text-hex/test.js b/nodejs/node_modules/text-hex/test.js new file mode 100644 index 00000000..2adbbd1b --- /dev/null +++ b/nodejs/node_modules/text-hex/test.js @@ -0,0 +1,11 @@ +describe('text-hex', function () { + 'use strict'; + + var assume = require('assume') + , hex = require('./'); + + it('is a 6 digit hex', function () { + assume(hex('a')).to.have.length(7); // including a # + assume(hex('a244fdafadfa4 adfau8fa a u adf8a0')).to.have.length(7); + }); +}); diff --git a/nodejs/node_modules/tr46/LICENSE.md b/nodejs/node_modules/tr46/LICENSE.md new file mode 100644 index 00000000..62c0de28 --- /dev/null +++ b/nodejs/node_modules/tr46/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sebastian Mayr + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/tr46/README.md b/nodejs/node_modules/tr46/README.md new file mode 100644 index 00000000..f4f7607a --- /dev/null +++ b/nodejs/node_modules/tr46/README.md @@ -0,0 +1,68 @@ +# tr46 + +An JavaScript implementation of [Unicode Technical Standard #46: Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). + +## API + +### `toASCII(domainName[, options])` + +Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. + +Available options: + +* [`checkBidi`](#checkBidi) +* [`checkHyphens`](#checkHyphens) +* [`checkJoiners`](#checkJoiners) +* [`processingOption`](#processingOption) +* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) +* [`verifyDNSLength`](#verifyDNSLength) + +### `toUnicode(domainName[, options])` + +Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. + +Available options: + +* [`checkBidi`](#checkBidi) +* [`checkHyphens`](#checkHyphens) +* [`checkJoiners`](#checkJoiners) +* [`processingOption`](#processingOption) +* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) + +## Options + +### `checkBidi` + +Type: `boolean` +Default value: `false` +When set to `true`, any bi-directional text within the input will be checked for validation. + +### `checkHyphens` + +Type: `boolean` +Default value: `false` +When set to `true`, the positions of any hyphen characters within the input will be checked for validation. + +### `checkJoiners` + +Type: `boolean` +Default value: `false` +When set to `true`, any word joiner characters within the input will be checked for validation. + +### `processingOption` + +Type: `string` +Default value: `"nontransitional"` +When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. + +### `useSTD3ASCIIRules` + +Type: `boolean` +Default value: `false` +When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). + +### `verifyDNSLength` + +Type: `boolean` +Default value: `false` +When set to `true`, the length of each DNS label within the input will be checked for validation. diff --git a/nodejs/node_modules/tr46/index.js b/nodejs/node_modules/tr46/index.js new file mode 100644 index 00000000..518eb10b --- /dev/null +++ b/nodejs/node_modules/tr46/index.js @@ -0,0 +1,300 @@ +"use strict"; + +const punycode = require("punycode/"); +const regexes = require("./lib/regexes.js"); +const mappingTable = require("./lib/mappingTable.json"); +const { STATUS_MAPPING } = require("./lib/statusMapping.js"); + +function containsNonASCII(str) { + return /[^\x00-\x7F]/u.test(str); +} + +function findStatus(val, { useSTD3ASCIIRules }) { + let start = 0; + let end = mappingTable.length - 1; + + while (start <= end) { + const mid = Math.floor((start + end) / 2); + + const target = mappingTable[mid]; + const min = Array.isArray(target[0]) ? target[0][0] : target[0]; + const max = Array.isArray(target[0]) ? target[0][1] : target[0]; + + if (min <= val && max >= val) { + if (useSTD3ASCIIRules && + (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) { + return [STATUS_MAPPING.disallowed, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) { + return [STATUS_MAPPING.valid, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) { + return [STATUS_MAPPING.mapped, ...target.slice(2)]; + } + + return target.slice(1); + } else if (min > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) { + let hasError = false; + let processed = ""; + + for (const ch of domainName) { + const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + + switch (status) { + case STATUS_MAPPING.disallowed: + hasError = true; + processed += ch; + break; + case STATUS_MAPPING.ignored: + break; + case STATUS_MAPPING.mapped: + processed += mapping; + break; + case STATUS_MAPPING.deviation: + if (processingOption === "transitional") { + processed += mapping; + } else { + processed += ch; + } + break; + case STATUS_MAPPING.valid: + processed += ch; + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) { + if (label.normalize("NFC") !== label) { + return false; + } + + const codePoints = Array.from(label); + + if (checkHyphens) { + if ((codePoints[2] === "-" && codePoints[3] === "-") || + (label.startsWith("-") || label.endsWith("-"))) { + return false; + } + } + + if (label.includes(".") || + (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) { + return false; + } + + for (const ch of codePoints) { + const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + if ((processingOption === "transitional" && status !== STATUS_MAPPING.valid) || + (processingOption === "nontransitional" && + status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation)) { + return false; + } + } + + // https://tools.ietf.org/html/rfc5892#appendix-A + if (checkJoiners) { + let last = 0; + for (const [i, ch] of codePoints.entries()) { + if (ch === "\u200C" || ch === "\u200D") { + if (i > 0) { + if (regexes.combiningClassVirama.test(codePoints[i - 1])) { + continue; + } + if (ch === "\u200C") { + // TODO: make this more efficient + const next = codePoints.indexOf("\u200C", i + 1); + const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); + if (regexes.validZWNJ.test(test.join(""))) { + last = i + 1; + continue; + } + } + } + return false; + } + } + } + + // https://tools.ietf.org/html/rfc5893#section-2 + // For the codePoints length check, see discussion in https://github.com/jsdom/whatwg-url/pull/250 and the second item + // in https://github.com/whatwg/url/issues/744. + if (checkBidi && codePoints.length > 0) { + let rtl; + + // 1 + if (regexes.bidiS1LTR.test(codePoints[0])) { + rtl = false; + } else if (regexes.bidiS1RTL.test(codePoints[0])) { + rtl = true; + } else { + return false; + } + + if (rtl) { + // 2-4 + if (!regexes.bidiS2.test(label) || + !regexes.bidiS3.test(label) || + (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) { + return false; + } + } else if (!regexes.bidiS5.test(label) || + !regexes.bidiS6.test(label)) { // 5-6 + return false; + } + } + + return true; +} + +function isBidiDomain(labels) { + const domain = labels.map(label => { + if (label.startsWith("xn--")) { + try { + return punycode.decode(label.substring(4)); + } catch (err) { + return ""; + } + } + return label; + }).join("."); + return regexes.bidiDomain.test(domain); +} + +function processing(domainName, options) { + const { processingOption } = options; + + // 1. Map. + let { string, error } = mapChars(domainName, options); + + // 2. Normalize. + string = string.normalize("NFC"); + + // 3. Break. + const labels = string.split("."); + const isBidi = isBidiDomain(labels); + + // 4. Convert/Validate. + for (const [i, origLabel] of labels.entries()) { + let label = origLabel; + let curProcessing = processingOption; + if (label.startsWith("xn--")) { + try { + label = punycode.decode(label.substring(4)); + labels[i] = label; + } catch (err) { + error = true; + continue; + } + curProcessing = "nontransitional"; + } + + // No need to validate if we already know there is an error. + if (error) { + continue; + } + const validation = validateLabel(label, { + ...options, + processingOption: curProcessing, + checkBidi: options.checkBidi && isBidi + }); + if (!validation) { + error = true; + } + } + + return { + string: labels.join("."), + error + }; +} + +function toASCII(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional", + verifyDNSLength = false +} = {}) { + if (processingOption !== "transitional" && processingOption !== "nontransitional") { + throw new RangeError("processingOption must be either transitional or nontransitional"); + } + + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + let labels = result.string.split("."); + labels = labels.map(l => { + if (containsNonASCII(l)) { + try { + return `xn--${punycode.encode(l)}`; + } catch (e) { + result.error = true; + } + } + return l; + }); + + if (verifyDNSLength) { + const total = labels.join(".").length; + if (total > 253 || total === 0) { + result.error = true; + } + + for (let i = 0; i < labels.length; ++i) { + if (labels[i].length > 63 || labels[i].length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) { + return null; + } + return labels.join("."); +} + +function toUnicode(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional" +} = {}) { + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + + return { + domain: result.string, + error: result.error + }; +} + +module.exports = { + toASCII, + toUnicode +}; diff --git a/nodejs/node_modules/tr46/lib/mappingTable.json b/nodejs/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 00000000..483ca3b9 --- /dev/null +++ b/nodejs/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],4],[[45,46],2],[47,4],[[48,57],2],[[58,64],4],[65,1,"a"],[66,1,"b"],[67,1,"c"],[68,1,"d"],[69,1,"e"],[70,1,"f"],[71,1,"g"],[72,1,"h"],[73,1,"i"],[74,1,"j"],[75,1,"k"],[76,1,"l"],[77,1,"m"],[78,1,"n"],[79,1,"o"],[80,1,"p"],[81,1,"q"],[82,1,"r"],[83,1,"s"],[84,1,"t"],[85,1,"u"],[86,1,"v"],[87,1,"w"],[88,1,"x"],[89,1,"y"],[90,1,"z"],[[91,96],4],[[97,122],2],[[123,127],4],[[128,159],3],[160,5," "],[[161,167],2],[168,5," ̈"],[169,2],[170,1,"a"],[[171,172],2],[173,7],[174,2],[175,5," ̄"],[[176,177],2],[178,1,"2"],[179,1,"3"],[180,5," ́"],[181,1,"μ"],[182,2],[183,2],[184,5," ̧"],[185,1,"1"],[186,1,"o"],[187,2],[188,1,"1⁄4"],[189,1,"1⁄2"],[190,1,"3⁄4"],[191,2],[192,1,"à"],[193,1,"á"],[194,1,"â"],[195,1,"ã"],[196,1,"ä"],[197,1,"å"],[198,1,"æ"],[199,1,"ç"],[200,1,"è"],[201,1,"é"],[202,1,"ê"],[203,1,"ë"],[204,1,"ì"],[205,1,"í"],[206,1,"î"],[207,1,"ï"],[208,1,"ð"],[209,1,"ñ"],[210,1,"ò"],[211,1,"ó"],[212,1,"ô"],[213,1,"õ"],[214,1,"ö"],[215,2],[216,1,"ø"],[217,1,"ù"],[218,1,"ú"],[219,1,"û"],[220,1,"ü"],[221,1,"ý"],[222,1,"þ"],[223,6,"ss"],[[224,246],2],[247,2],[[248,255],2],[256,1,"ā"],[257,2],[258,1,"ă"],[259,2],[260,1,"ą"],[261,2],[262,1,"ć"],[263,2],[264,1,"ĉ"],[265,2],[266,1,"ċ"],[267,2],[268,1,"č"],[269,2],[270,1,"ď"],[271,2],[272,1,"đ"],[273,2],[274,1,"ē"],[275,2],[276,1,"ĕ"],[277,2],[278,1,"ė"],[279,2],[280,1,"ę"],[281,2],[282,1,"ě"],[283,2],[284,1,"ĝ"],[285,2],[286,1,"ğ"],[287,2],[288,1,"ġ"],[289,2],[290,1,"ģ"],[291,2],[292,1,"ĥ"],[293,2],[294,1,"ħ"],[295,2],[296,1,"ĩ"],[297,2],[298,1,"ī"],[299,2],[300,1,"ĭ"],[301,2],[302,1,"į"],[303,2],[304,1,"i̇"],[305,2],[[306,307],1,"ij"],[308,1,"ĵ"],[309,2],[310,1,"ķ"],[[311,312],2],[313,1,"ĺ"],[314,2],[315,1,"ļ"],[316,2],[317,1,"ľ"],[318,2],[[319,320],1,"l·"],[321,1,"ł"],[322,2],[323,1,"ń"],[324,2],[325,1,"ņ"],[326,2],[327,1,"ň"],[328,2],[329,1,"ʼn"],[330,1,"ŋ"],[331,2],[332,1,"ō"],[333,2],[334,1,"ŏ"],[335,2],[336,1,"ő"],[337,2],[338,1,"œ"],[339,2],[340,1,"ŕ"],[341,2],[342,1,"ŗ"],[343,2],[344,1,"ř"],[345,2],[346,1,"ś"],[347,2],[348,1,"ŝ"],[349,2],[350,1,"ş"],[351,2],[352,1,"š"],[353,2],[354,1,"ţ"],[355,2],[356,1,"ť"],[357,2],[358,1,"ŧ"],[359,2],[360,1,"ũ"],[361,2],[362,1,"ū"],[363,2],[364,1,"ŭ"],[365,2],[366,1,"ů"],[367,2],[368,1,"ű"],[369,2],[370,1,"ų"],[371,2],[372,1,"ŵ"],[373,2],[374,1,"ŷ"],[375,2],[376,1,"ÿ"],[377,1,"ź"],[378,2],[379,1,"ż"],[380,2],[381,1,"ž"],[382,2],[383,1,"s"],[384,2],[385,1,"ɓ"],[386,1,"ƃ"],[387,2],[388,1,"ƅ"],[389,2],[390,1,"ɔ"],[391,1,"ƈ"],[392,2],[393,1,"ɖ"],[394,1,"ɗ"],[395,1,"ƌ"],[[396,397],2],[398,1,"ǝ"],[399,1,"ə"],[400,1,"ɛ"],[401,1,"ƒ"],[402,2],[403,1,"ɠ"],[404,1,"ɣ"],[405,2],[406,1,"ɩ"],[407,1,"ɨ"],[408,1,"ƙ"],[[409,411],2],[412,1,"ɯ"],[413,1,"ɲ"],[414,2],[415,1,"ɵ"],[416,1,"ơ"],[417,2],[418,1,"ƣ"],[419,2],[420,1,"ƥ"],[421,2],[422,1,"ʀ"],[423,1,"ƨ"],[424,2],[425,1,"ʃ"],[[426,427],2],[428,1,"ƭ"],[429,2],[430,1,"ʈ"],[431,1,"ư"],[432,2],[433,1,"ʊ"],[434,1,"ʋ"],[435,1,"ƴ"],[436,2],[437,1,"ƶ"],[438,2],[439,1,"ʒ"],[440,1,"ƹ"],[[441,443],2],[444,1,"ƽ"],[[445,451],2],[[452,454],1,"dž"],[[455,457],1,"lj"],[[458,460],1,"nj"],[461,1,"ǎ"],[462,2],[463,1,"ǐ"],[464,2],[465,1,"ǒ"],[466,2],[467,1,"ǔ"],[468,2],[469,1,"ǖ"],[470,2],[471,1,"ǘ"],[472,2],[473,1,"ǚ"],[474,2],[475,1,"ǜ"],[[476,477],2],[478,1,"ǟ"],[479,2],[480,1,"ǡ"],[481,2],[482,1,"ǣ"],[483,2],[484,1,"ǥ"],[485,2],[486,1,"ǧ"],[487,2],[488,1,"ǩ"],[489,2],[490,1,"ǫ"],[491,2],[492,1,"ǭ"],[493,2],[494,1,"ǯ"],[[495,496],2],[[497,499],1,"dz"],[500,1,"ǵ"],[501,2],[502,1,"ƕ"],[503,1,"ƿ"],[504,1,"ǹ"],[505,2],[506,1,"ǻ"],[507,2],[508,1,"ǽ"],[509,2],[510,1,"ǿ"],[511,2],[512,1,"ȁ"],[513,2],[514,1,"ȃ"],[515,2],[516,1,"ȅ"],[517,2],[518,1,"ȇ"],[519,2],[520,1,"ȉ"],[521,2],[522,1,"ȋ"],[523,2],[524,1,"ȍ"],[525,2],[526,1,"ȏ"],[527,2],[528,1,"ȑ"],[529,2],[530,1,"ȓ"],[531,2],[532,1,"ȕ"],[533,2],[534,1,"ȗ"],[535,2],[536,1,"ș"],[537,2],[538,1,"ț"],[539,2],[540,1,"ȝ"],[541,2],[542,1,"ȟ"],[543,2],[544,1,"ƞ"],[545,2],[546,1,"ȣ"],[547,2],[548,1,"ȥ"],[549,2],[550,1,"ȧ"],[551,2],[552,1,"ȩ"],[553,2],[554,1,"ȫ"],[555,2],[556,1,"ȭ"],[557,2],[558,1,"ȯ"],[559,2],[560,1,"ȱ"],[561,2],[562,1,"ȳ"],[563,2],[[564,566],2],[[567,569],2],[570,1,"ⱥ"],[571,1,"ȼ"],[572,2],[573,1,"ƚ"],[574,1,"ⱦ"],[[575,576],2],[577,1,"ɂ"],[578,2],[579,1,"ƀ"],[580,1,"ʉ"],[581,1,"ʌ"],[582,1,"ɇ"],[583,2],[584,1,"ɉ"],[585,2],[586,1,"ɋ"],[587,2],[588,1,"ɍ"],[589,2],[590,1,"ɏ"],[591,2],[[592,680],2],[[681,685],2],[[686,687],2],[688,1,"h"],[689,1,"ɦ"],[690,1,"j"],[691,1,"r"],[692,1,"ɹ"],[693,1,"ɻ"],[694,1,"ʁ"],[695,1,"w"],[696,1,"y"],[[697,705],2],[[706,709],2],[[710,721],2],[[722,727],2],[728,5," ̆"],[729,5," ̇"],[730,5," ̊"],[731,5," ̨"],[732,5," ̃"],[733,5," ̋"],[734,2],[735,2],[736,1,"ɣ"],[737,1,"l"],[738,1,"s"],[739,1,"x"],[740,1,"ʕ"],[[741,745],2],[[746,747],2],[748,2],[749,2],[750,2],[[751,767],2],[[768,831],2],[832,1,"̀"],[833,1,"́"],[834,2],[835,1,"̓"],[836,1,"̈́"],[837,1,"ι"],[[838,846],2],[847,7],[[848,855],2],[[856,860],2],[[861,863],2],[[864,865],2],[866,2],[[867,879],2],[880,1,"ͱ"],[881,2],[882,1,"ͳ"],[883,2],[884,1,"ʹ"],[885,2],[886,1,"ͷ"],[887,2],[[888,889],3],[890,5," ι"],[[891,893],2],[894,5,";"],[895,1,"ϳ"],[[896,899],3],[900,5," ́"],[901,5," ̈́"],[902,1,"ά"],[903,1,"·"],[904,1,"έ"],[905,1,"ή"],[906,1,"ί"],[907,3],[908,1,"ό"],[909,3],[910,1,"ύ"],[911,1,"ώ"],[912,2],[913,1,"α"],[914,1,"β"],[915,1,"γ"],[916,1,"δ"],[917,1,"ε"],[918,1,"ζ"],[919,1,"η"],[920,1,"θ"],[921,1,"ι"],[922,1,"κ"],[923,1,"λ"],[924,1,"μ"],[925,1,"ν"],[926,1,"ξ"],[927,1,"ο"],[928,1,"π"],[929,1,"ρ"],[930,3],[931,1,"σ"],[932,1,"τ"],[933,1,"υ"],[934,1,"φ"],[935,1,"χ"],[936,1,"ψ"],[937,1,"ω"],[938,1,"ϊ"],[939,1,"ϋ"],[[940,961],2],[962,6,"σ"],[[963,974],2],[975,1,"ϗ"],[976,1,"β"],[977,1,"θ"],[978,1,"υ"],[979,1,"ύ"],[980,1,"ϋ"],[981,1,"φ"],[982,1,"π"],[983,2],[984,1,"ϙ"],[985,2],[986,1,"ϛ"],[987,2],[988,1,"ϝ"],[989,2],[990,1,"ϟ"],[991,2],[992,1,"ϡ"],[993,2],[994,1,"ϣ"],[995,2],[996,1,"ϥ"],[997,2],[998,1,"ϧ"],[999,2],[1000,1,"ϩ"],[1001,2],[1002,1,"ϫ"],[1003,2],[1004,1,"ϭ"],[1005,2],[1006,1,"ϯ"],[1007,2],[1008,1,"κ"],[1009,1,"ρ"],[1010,1,"σ"],[1011,2],[1012,1,"θ"],[1013,1,"ε"],[1014,2],[1015,1,"ϸ"],[1016,2],[1017,1,"σ"],[1018,1,"ϻ"],[1019,2],[1020,2],[1021,1,"ͻ"],[1022,1,"ͼ"],[1023,1,"ͽ"],[1024,1,"ѐ"],[1025,1,"ё"],[1026,1,"ђ"],[1027,1,"ѓ"],[1028,1,"є"],[1029,1,"ѕ"],[1030,1,"і"],[1031,1,"ї"],[1032,1,"ј"],[1033,1,"љ"],[1034,1,"њ"],[1035,1,"ћ"],[1036,1,"ќ"],[1037,1,"ѝ"],[1038,1,"ў"],[1039,1,"џ"],[1040,1,"а"],[1041,1,"б"],[1042,1,"в"],[1043,1,"г"],[1044,1,"д"],[1045,1,"е"],[1046,1,"ж"],[1047,1,"з"],[1048,1,"и"],[1049,1,"й"],[1050,1,"к"],[1051,1,"л"],[1052,1,"м"],[1053,1,"н"],[1054,1,"о"],[1055,1,"п"],[1056,1,"р"],[1057,1,"с"],[1058,1,"т"],[1059,1,"у"],[1060,1,"ф"],[1061,1,"х"],[1062,1,"ц"],[1063,1,"ч"],[1064,1,"ш"],[1065,1,"щ"],[1066,1,"ъ"],[1067,1,"ы"],[1068,1,"ь"],[1069,1,"э"],[1070,1,"ю"],[1071,1,"я"],[[1072,1103],2],[1104,2],[[1105,1116],2],[1117,2],[[1118,1119],2],[1120,1,"ѡ"],[1121,2],[1122,1,"ѣ"],[1123,2],[1124,1,"ѥ"],[1125,2],[1126,1,"ѧ"],[1127,2],[1128,1,"ѩ"],[1129,2],[1130,1,"ѫ"],[1131,2],[1132,1,"ѭ"],[1133,2],[1134,1,"ѯ"],[1135,2],[1136,1,"ѱ"],[1137,2],[1138,1,"ѳ"],[1139,2],[1140,1,"ѵ"],[1141,2],[1142,1,"ѷ"],[1143,2],[1144,1,"ѹ"],[1145,2],[1146,1,"ѻ"],[1147,2],[1148,1,"ѽ"],[1149,2],[1150,1,"ѿ"],[1151,2],[1152,1,"ҁ"],[1153,2],[1154,2],[[1155,1158],2],[1159,2],[[1160,1161],2],[1162,1,"ҋ"],[1163,2],[1164,1,"ҍ"],[1165,2],[1166,1,"ҏ"],[1167,2],[1168,1,"ґ"],[1169,2],[1170,1,"ғ"],[1171,2],[1172,1,"ҕ"],[1173,2],[1174,1,"җ"],[1175,2],[1176,1,"ҙ"],[1177,2],[1178,1,"қ"],[1179,2],[1180,1,"ҝ"],[1181,2],[1182,1,"ҟ"],[1183,2],[1184,1,"ҡ"],[1185,2],[1186,1,"ң"],[1187,2],[1188,1,"ҥ"],[1189,2],[1190,1,"ҧ"],[1191,2],[1192,1,"ҩ"],[1193,2],[1194,1,"ҫ"],[1195,2],[1196,1,"ҭ"],[1197,2],[1198,1,"ү"],[1199,2],[1200,1,"ұ"],[1201,2],[1202,1,"ҳ"],[1203,2],[1204,1,"ҵ"],[1205,2],[1206,1,"ҷ"],[1207,2],[1208,1,"ҹ"],[1209,2],[1210,1,"һ"],[1211,2],[1212,1,"ҽ"],[1213,2],[1214,1,"ҿ"],[1215,2],[1216,3],[1217,1,"ӂ"],[1218,2],[1219,1,"ӄ"],[1220,2],[1221,1,"ӆ"],[1222,2],[1223,1,"ӈ"],[1224,2],[1225,1,"ӊ"],[1226,2],[1227,1,"ӌ"],[1228,2],[1229,1,"ӎ"],[1230,2],[1231,2],[1232,1,"ӑ"],[1233,2],[1234,1,"ӓ"],[1235,2],[1236,1,"ӕ"],[1237,2],[1238,1,"ӗ"],[1239,2],[1240,1,"ә"],[1241,2],[1242,1,"ӛ"],[1243,2],[1244,1,"ӝ"],[1245,2],[1246,1,"ӟ"],[1247,2],[1248,1,"ӡ"],[1249,2],[1250,1,"ӣ"],[1251,2],[1252,1,"ӥ"],[1253,2],[1254,1,"ӧ"],[1255,2],[1256,1,"ө"],[1257,2],[1258,1,"ӫ"],[1259,2],[1260,1,"ӭ"],[1261,2],[1262,1,"ӯ"],[1263,2],[1264,1,"ӱ"],[1265,2],[1266,1,"ӳ"],[1267,2],[1268,1,"ӵ"],[1269,2],[1270,1,"ӷ"],[1271,2],[1272,1,"ӹ"],[1273,2],[1274,1,"ӻ"],[1275,2],[1276,1,"ӽ"],[1277,2],[1278,1,"ӿ"],[1279,2],[1280,1,"ԁ"],[1281,2],[1282,1,"ԃ"],[1283,2],[1284,1,"ԅ"],[1285,2],[1286,1,"ԇ"],[1287,2],[1288,1,"ԉ"],[1289,2],[1290,1,"ԋ"],[1291,2],[1292,1,"ԍ"],[1293,2],[1294,1,"ԏ"],[1295,2],[1296,1,"ԑ"],[1297,2],[1298,1,"ԓ"],[1299,2],[1300,1,"ԕ"],[1301,2],[1302,1,"ԗ"],[1303,2],[1304,1,"ԙ"],[1305,2],[1306,1,"ԛ"],[1307,2],[1308,1,"ԝ"],[1309,2],[1310,1,"ԟ"],[1311,2],[1312,1,"ԡ"],[1313,2],[1314,1,"ԣ"],[1315,2],[1316,1,"ԥ"],[1317,2],[1318,1,"ԧ"],[1319,2],[1320,1,"ԩ"],[1321,2],[1322,1,"ԫ"],[1323,2],[1324,1,"ԭ"],[1325,2],[1326,1,"ԯ"],[1327,2],[1328,3],[1329,1,"ա"],[1330,1,"բ"],[1331,1,"գ"],[1332,1,"դ"],[1333,1,"ե"],[1334,1,"զ"],[1335,1,"է"],[1336,1,"ը"],[1337,1,"թ"],[1338,1,"ժ"],[1339,1,"ի"],[1340,1,"լ"],[1341,1,"խ"],[1342,1,"ծ"],[1343,1,"կ"],[1344,1,"հ"],[1345,1,"ձ"],[1346,1,"ղ"],[1347,1,"ճ"],[1348,1,"մ"],[1349,1,"յ"],[1350,1,"ն"],[1351,1,"շ"],[1352,1,"ո"],[1353,1,"չ"],[1354,1,"պ"],[1355,1,"ջ"],[1356,1,"ռ"],[1357,1,"ս"],[1358,1,"վ"],[1359,1,"տ"],[1360,1,"ր"],[1361,1,"ց"],[1362,1,"ւ"],[1363,1,"փ"],[1364,1,"ք"],[1365,1,"օ"],[1366,1,"ֆ"],[[1367,1368],3],[1369,2],[[1370,1375],2],[1376,2],[[1377,1414],2],[1415,1,"եւ"],[1416,2],[1417,2],[1418,2],[[1419,1420],3],[[1421,1422],2],[1423,2],[1424,3],[[1425,1441],2],[1442,2],[[1443,1455],2],[[1456,1465],2],[1466,2],[[1467,1469],2],[1470,2],[1471,2],[1472,2],[[1473,1474],2],[1475,2],[1476,2],[1477,2],[1478,2],[1479,2],[[1480,1487],3],[[1488,1514],2],[[1515,1518],3],[1519,2],[[1520,1524],2],[[1525,1535],3],[[1536,1539],3],[1540,3],[1541,3],[[1542,1546],2],[1547,2],[1548,2],[[1549,1551],2],[[1552,1557],2],[[1558,1562],2],[1563,2],[1564,3],[1565,2],[1566,2],[1567,2],[1568,2],[[1569,1594],2],[[1595,1599],2],[1600,2],[[1601,1618],2],[[1619,1621],2],[[1622,1624],2],[[1625,1630],2],[1631,2],[[1632,1641],2],[[1642,1645],2],[[1646,1647],2],[[1648,1652],2],[1653,1,"اٴ"],[1654,1,"وٴ"],[1655,1,"ۇٴ"],[1656,1,"يٴ"],[[1657,1719],2],[[1720,1721],2],[[1722,1726],2],[1727,2],[[1728,1742],2],[1743,2],[[1744,1747],2],[1748,2],[[1749,1756],2],[1757,3],[1758,2],[[1759,1768],2],[1769,2],[[1770,1773],2],[[1774,1775],2],[[1776,1785],2],[[1786,1790],2],[1791,2],[[1792,1805],2],[1806,3],[1807,3],[[1808,1836],2],[[1837,1839],2],[[1840,1866],2],[[1867,1868],3],[[1869,1871],2],[[1872,1901],2],[[1902,1919],2],[[1920,1968],2],[1969,2],[[1970,1983],3],[[1984,2037],2],[[2038,2042],2],[[2043,2044],3],[2045,2],[[2046,2047],2],[[2048,2093],2],[[2094,2095],3],[[2096,2110],2],[2111,3],[[2112,2139],2],[[2140,2141],3],[2142,2],[2143,3],[[2144,2154],2],[[2155,2159],3],[[2160,2183],2],[2184,2],[[2185,2190],2],[2191,3],[[2192,2193],3],[[2194,2199],3],[[2200,2207],2],[2208,2],[2209,2],[[2210,2220],2],[[2221,2226],2],[[2227,2228],2],[2229,2],[[2230,2237],2],[[2238,2247],2],[[2248,2258],2],[2259,2],[[2260,2273],2],[2274,3],[2275,2],[[2276,2302],2],[2303,2],[2304,2],[[2305,2307],2],[2308,2],[[2309,2361],2],[[2362,2363],2],[[2364,2381],2],[2382,2],[2383,2],[[2384,2388],2],[2389,2],[[2390,2391],2],[2392,1,"क़"],[2393,1,"ख़"],[2394,1,"ग़"],[2395,1,"ज़"],[2396,1,"ड़"],[2397,1,"ढ़"],[2398,1,"फ़"],[2399,1,"य़"],[[2400,2403],2],[[2404,2405],2],[[2406,2415],2],[2416,2],[[2417,2418],2],[[2419,2423],2],[2424,2],[[2425,2426],2],[[2427,2428],2],[2429,2],[[2430,2431],2],[2432,2],[[2433,2435],2],[2436,3],[[2437,2444],2],[[2445,2446],3],[[2447,2448],2],[[2449,2450],3],[[2451,2472],2],[2473,3],[[2474,2480],2],[2481,3],[2482,2],[[2483,2485],3],[[2486,2489],2],[[2490,2491],3],[2492,2],[2493,2],[[2494,2500],2],[[2501,2502],3],[[2503,2504],2],[[2505,2506],3],[[2507,2509],2],[2510,2],[[2511,2518],3],[2519,2],[[2520,2523],3],[2524,1,"ড়"],[2525,1,"ঢ়"],[2526,3],[2527,1,"য়"],[[2528,2531],2],[[2532,2533],3],[[2534,2545],2],[[2546,2554],2],[2555,2],[2556,2],[2557,2],[2558,2],[[2559,2560],3],[2561,2],[2562,2],[2563,2],[2564,3],[[2565,2570],2],[[2571,2574],3],[[2575,2576],2],[[2577,2578],3],[[2579,2600],2],[2601,3],[[2602,2608],2],[2609,3],[2610,2],[2611,1,"ਲ਼"],[2612,3],[2613,2],[2614,1,"ਸ਼"],[2615,3],[[2616,2617],2],[[2618,2619],3],[2620,2],[2621,3],[[2622,2626],2],[[2627,2630],3],[[2631,2632],2],[[2633,2634],3],[[2635,2637],2],[[2638,2640],3],[2641,2],[[2642,2648],3],[2649,1,"ਖ਼"],[2650,1,"ਗ਼"],[2651,1,"ਜ਼"],[2652,2],[2653,3],[2654,1,"ਫ਼"],[[2655,2661],3],[[2662,2676],2],[2677,2],[2678,2],[[2679,2688],3],[[2689,2691],2],[2692,3],[[2693,2699],2],[2700,2],[2701,2],[2702,3],[[2703,2705],2],[2706,3],[[2707,2728],2],[2729,3],[[2730,2736],2],[2737,3],[[2738,2739],2],[2740,3],[[2741,2745],2],[[2746,2747],3],[[2748,2757],2],[2758,3],[[2759,2761],2],[2762,3],[[2763,2765],2],[[2766,2767],3],[2768,2],[[2769,2783],3],[2784,2],[[2785,2787],2],[[2788,2789],3],[[2790,2799],2],[2800,2],[2801,2],[[2802,2808],3],[2809,2],[[2810,2815],2],[2816,3],[[2817,2819],2],[2820,3],[[2821,2828],2],[[2829,2830],3],[[2831,2832],2],[[2833,2834],3],[[2835,2856],2],[2857,3],[[2858,2864],2],[2865,3],[[2866,2867],2],[2868,3],[2869,2],[[2870,2873],2],[[2874,2875],3],[[2876,2883],2],[2884,2],[[2885,2886],3],[[2887,2888],2],[[2889,2890],3],[[2891,2893],2],[[2894,2900],3],[2901,2],[[2902,2903],2],[[2904,2907],3],[2908,1,"ଡ଼"],[2909,1,"ଢ଼"],[2910,3],[[2911,2913],2],[[2914,2915],2],[[2916,2917],3],[[2918,2927],2],[2928,2],[2929,2],[[2930,2935],2],[[2936,2945],3],[[2946,2947],2],[2948,3],[[2949,2954],2],[[2955,2957],3],[[2958,2960],2],[2961,3],[[2962,2965],2],[[2966,2968],3],[[2969,2970],2],[2971,3],[2972,2],[2973,3],[[2974,2975],2],[[2976,2978],3],[[2979,2980],2],[[2981,2983],3],[[2984,2986],2],[[2987,2989],3],[[2990,2997],2],[2998,2],[[2999,3001],2],[[3002,3005],3],[[3006,3010],2],[[3011,3013],3],[[3014,3016],2],[3017,3],[[3018,3021],2],[[3022,3023],3],[3024,2],[[3025,3030],3],[3031,2],[[3032,3045],3],[3046,2],[[3047,3055],2],[[3056,3058],2],[[3059,3066],2],[[3067,3071],3],[3072,2],[[3073,3075],2],[3076,2],[[3077,3084],2],[3085,3],[[3086,3088],2],[3089,3],[[3090,3112],2],[3113,3],[[3114,3123],2],[3124,2],[[3125,3129],2],[[3130,3131],3],[3132,2],[3133,2],[[3134,3140],2],[3141,3],[[3142,3144],2],[3145,3],[[3146,3149],2],[[3150,3156],3],[[3157,3158],2],[3159,3],[[3160,3161],2],[3162,2],[[3163,3164],3],[3165,2],[[3166,3167],3],[[3168,3169],2],[[3170,3171],2],[[3172,3173],3],[[3174,3183],2],[[3184,3190],3],[3191,2],[[3192,3199],2],[3200,2],[3201,2],[[3202,3203],2],[3204,2],[[3205,3212],2],[3213,3],[[3214,3216],2],[3217,3],[[3218,3240],2],[3241,3],[[3242,3251],2],[3252,3],[[3253,3257],2],[[3258,3259],3],[[3260,3261],2],[[3262,3268],2],[3269,3],[[3270,3272],2],[3273,3],[[3274,3277],2],[[3278,3284],3],[[3285,3286],2],[[3287,3292],3],[3293,2],[3294,2],[3295,3],[[3296,3297],2],[[3298,3299],2],[[3300,3301],3],[[3302,3311],2],[3312,3],[[3313,3314],2],[3315,2],[[3316,3327],3],[3328,2],[3329,2],[[3330,3331],2],[3332,2],[[3333,3340],2],[3341,3],[[3342,3344],2],[3345,3],[[3346,3368],2],[3369,2],[[3370,3385],2],[3386,2],[[3387,3388],2],[3389,2],[[3390,3395],2],[3396,2],[3397,3],[[3398,3400],2],[3401,3],[[3402,3405],2],[3406,2],[3407,2],[[3408,3411],3],[[3412,3414],2],[3415,2],[[3416,3422],2],[3423,2],[[3424,3425],2],[[3426,3427],2],[[3428,3429],3],[[3430,3439],2],[[3440,3445],2],[[3446,3448],2],[3449,2],[[3450,3455],2],[3456,3],[3457,2],[[3458,3459],2],[3460,3],[[3461,3478],2],[[3479,3481],3],[[3482,3505],2],[3506,3],[[3507,3515],2],[3516,3],[3517,2],[[3518,3519],3],[[3520,3526],2],[[3527,3529],3],[3530,2],[[3531,3534],3],[[3535,3540],2],[3541,3],[3542,2],[3543,3],[[3544,3551],2],[[3552,3557],3],[[3558,3567],2],[[3568,3569],3],[[3570,3571],2],[3572,2],[[3573,3584],3],[[3585,3634],2],[3635,1,"ํา"],[[3636,3642],2],[[3643,3646],3],[3647,2],[[3648,3662],2],[3663,2],[[3664,3673],2],[[3674,3675],2],[[3676,3712],3],[[3713,3714],2],[3715,3],[3716,2],[3717,3],[3718,2],[[3719,3720],2],[3721,2],[3722,2],[3723,3],[3724,2],[3725,2],[[3726,3731],2],[[3732,3735],2],[3736,2],[[3737,3743],2],[3744,2],[[3745,3747],2],[3748,3],[3749,2],[3750,3],[3751,2],[[3752,3753],2],[[3754,3755],2],[3756,2],[[3757,3762],2],[3763,1,"ໍາ"],[[3764,3769],2],[3770,2],[[3771,3773],2],[[3774,3775],3],[[3776,3780],2],[3781,3],[3782,2],[3783,3],[[3784,3789],2],[3790,2],[3791,3],[[3792,3801],2],[[3802,3803],3],[3804,1,"ຫນ"],[3805,1,"ຫມ"],[[3806,3807],2],[[3808,3839],3],[3840,2],[[3841,3850],2],[3851,2],[3852,1,"་"],[[3853,3863],2],[[3864,3865],2],[[3866,3871],2],[[3872,3881],2],[[3882,3892],2],[3893,2],[3894,2],[3895,2],[3896,2],[3897,2],[[3898,3901],2],[[3902,3906],2],[3907,1,"གྷ"],[[3908,3911],2],[3912,3],[[3913,3916],2],[3917,1,"ཌྷ"],[[3918,3921],2],[3922,1,"དྷ"],[[3923,3926],2],[3927,1,"བྷ"],[[3928,3931],2],[3932,1,"ཛྷ"],[[3933,3944],2],[3945,1,"ཀྵ"],[3946,2],[[3947,3948],2],[[3949,3952],3],[[3953,3954],2],[3955,1,"ཱི"],[3956,2],[3957,1,"ཱུ"],[3958,1,"ྲྀ"],[3959,1,"ྲཱྀ"],[3960,1,"ླྀ"],[3961,1,"ླཱྀ"],[[3962,3968],2],[3969,1,"ཱྀ"],[[3970,3972],2],[3973,2],[[3974,3979],2],[[3980,3983],2],[[3984,3986],2],[3987,1,"ྒྷ"],[[3988,3989],2],[3990,2],[3991,2],[3992,3],[[3993,3996],2],[3997,1,"ྜྷ"],[[3998,4001],2],[4002,1,"ྡྷ"],[[4003,4006],2],[4007,1,"ྦྷ"],[[4008,4011],2],[4012,1,"ྫྷ"],[4013,2],[[4014,4016],2],[[4017,4023],2],[4024,2],[4025,1,"ྐྵ"],[[4026,4028],2],[4029,3],[[4030,4037],2],[4038,2],[[4039,4044],2],[4045,3],[4046,2],[4047,2],[[4048,4049],2],[[4050,4052],2],[[4053,4056],2],[[4057,4058],2],[[4059,4095],3],[[4096,4129],2],[4130,2],[[4131,4135],2],[4136,2],[[4137,4138],2],[4139,2],[[4140,4146],2],[[4147,4149],2],[[4150,4153],2],[[4154,4159],2],[[4160,4169],2],[[4170,4175],2],[[4176,4185],2],[[4186,4249],2],[[4250,4253],2],[[4254,4255],2],[[4256,4293],3],[4294,3],[4295,1,"ⴧ"],[[4296,4300],3],[4301,1,"ⴭ"],[[4302,4303],3],[[4304,4342],2],[[4343,4344],2],[[4345,4346],2],[4347,2],[4348,1,"ნ"],[[4349,4351],2],[[4352,4441],2],[[4442,4446],2],[[4447,4448],3],[[4449,4514],2],[[4515,4519],2],[[4520,4601],2],[[4602,4607],2],[[4608,4614],2],[4615,2],[[4616,4678],2],[4679,2],[4680,2],[4681,3],[[4682,4685],2],[[4686,4687],3],[[4688,4694],2],[4695,3],[4696,2],[4697,3],[[4698,4701],2],[[4702,4703],3],[[4704,4742],2],[4743,2],[4744,2],[4745,3],[[4746,4749],2],[[4750,4751],3],[[4752,4782],2],[4783,2],[4784,2],[4785,3],[[4786,4789],2],[[4790,4791],3],[[4792,4798],2],[4799,3],[4800,2],[4801,3],[[4802,4805],2],[[4806,4807],3],[[4808,4814],2],[4815,2],[[4816,4822],2],[4823,3],[[4824,4846],2],[4847,2],[[4848,4878],2],[4879,2],[4880,2],[4881,3],[[4882,4885],2],[[4886,4887],3],[[4888,4894],2],[4895,2],[[4896,4934],2],[4935,2],[[4936,4954],2],[[4955,4956],3],[[4957,4958],2],[4959,2],[4960,2],[[4961,4988],2],[[4989,4991],3],[[4992,5007],2],[[5008,5017],2],[[5018,5023],3],[[5024,5108],2],[5109,2],[[5110,5111],3],[5112,1,"Ᏸ"],[5113,1,"Ᏹ"],[5114,1,"Ᏺ"],[5115,1,"Ᏻ"],[5116,1,"Ᏼ"],[5117,1,"Ᏽ"],[[5118,5119],3],[5120,2],[[5121,5740],2],[[5741,5742],2],[[5743,5750],2],[[5751,5759],2],[5760,3],[[5761,5786],2],[[5787,5788],2],[[5789,5791],3],[[5792,5866],2],[[5867,5872],2],[[5873,5880],2],[[5881,5887],3],[[5888,5900],2],[5901,2],[[5902,5908],2],[5909,2],[[5910,5918],3],[5919,2],[[5920,5940],2],[[5941,5942],2],[[5943,5951],3],[[5952,5971],2],[[5972,5983],3],[[5984,5996],2],[5997,3],[[5998,6000],2],[6001,3],[[6002,6003],2],[[6004,6015],3],[[6016,6067],2],[[6068,6069],3],[[6070,6099],2],[[6100,6102],2],[6103,2],[[6104,6107],2],[6108,2],[6109,2],[[6110,6111],3],[[6112,6121],2],[[6122,6127],3],[[6128,6137],2],[[6138,6143],3],[[6144,6149],2],[6150,3],[[6151,6154],2],[[6155,6157],7],[6158,3],[6159,7],[[6160,6169],2],[[6170,6175],3],[[6176,6263],2],[6264,2],[[6265,6271],3],[[6272,6313],2],[6314,2],[[6315,6319],3],[[6320,6389],2],[[6390,6399],3],[[6400,6428],2],[[6429,6430],2],[6431,3],[[6432,6443],2],[[6444,6447],3],[[6448,6459],2],[[6460,6463],3],[6464,2],[[6465,6467],3],[[6468,6469],2],[[6470,6509],2],[[6510,6511],3],[[6512,6516],2],[[6517,6527],3],[[6528,6569],2],[[6570,6571],2],[[6572,6575],3],[[6576,6601],2],[[6602,6607],3],[[6608,6617],2],[6618,2],[[6619,6621],3],[[6622,6623],2],[[6624,6655],2],[[6656,6683],2],[[6684,6685],3],[[6686,6687],2],[[6688,6750],2],[6751,3],[[6752,6780],2],[[6781,6782],3],[[6783,6793],2],[[6794,6799],3],[[6800,6809],2],[[6810,6815],3],[[6816,6822],2],[6823,2],[[6824,6829],2],[[6830,6831],3],[[6832,6845],2],[6846,2],[[6847,6848],2],[[6849,6862],2],[[6863,6911],3],[[6912,6987],2],[6988,2],[[6989,6991],3],[[6992,7001],2],[[7002,7018],2],[[7019,7027],2],[[7028,7036],2],[[7037,7038],2],[7039,3],[[7040,7082],2],[[7083,7085],2],[[7086,7097],2],[[7098,7103],2],[[7104,7155],2],[[7156,7163],3],[[7164,7167],2],[[7168,7223],2],[[7224,7226],3],[[7227,7231],2],[[7232,7241],2],[[7242,7244],3],[[7245,7293],2],[[7294,7295],2],[7296,1,"в"],[7297,1,"д"],[7298,1,"о"],[7299,1,"с"],[[7300,7301],1,"т"],[7302,1,"ъ"],[7303,1,"ѣ"],[7304,1,"ꙋ"],[[7305,7311],3],[7312,1,"ა"],[7313,1,"ბ"],[7314,1,"გ"],[7315,1,"დ"],[7316,1,"ე"],[7317,1,"ვ"],[7318,1,"ზ"],[7319,1,"თ"],[7320,1,"ი"],[7321,1,"კ"],[7322,1,"ლ"],[7323,1,"მ"],[7324,1,"ნ"],[7325,1,"ო"],[7326,1,"პ"],[7327,1,"ჟ"],[7328,1,"რ"],[7329,1,"ს"],[7330,1,"ტ"],[7331,1,"უ"],[7332,1,"ფ"],[7333,1,"ქ"],[7334,1,"ღ"],[7335,1,"ყ"],[7336,1,"შ"],[7337,1,"ჩ"],[7338,1,"ც"],[7339,1,"ძ"],[7340,1,"წ"],[7341,1,"ჭ"],[7342,1,"ხ"],[7343,1,"ჯ"],[7344,1,"ჰ"],[7345,1,"ჱ"],[7346,1,"ჲ"],[7347,1,"ჳ"],[7348,1,"ჴ"],[7349,1,"ჵ"],[7350,1,"ჶ"],[7351,1,"ჷ"],[7352,1,"ჸ"],[7353,1,"ჹ"],[7354,1,"ჺ"],[[7355,7356],3],[7357,1,"ჽ"],[7358,1,"ჾ"],[7359,1,"ჿ"],[[7360,7367],2],[[7368,7375],3],[[7376,7378],2],[7379,2],[[7380,7410],2],[[7411,7414],2],[7415,2],[[7416,7417],2],[7418,2],[[7419,7423],3],[[7424,7467],2],[7468,1,"a"],[7469,1,"æ"],[7470,1,"b"],[7471,2],[7472,1,"d"],[7473,1,"e"],[7474,1,"ǝ"],[7475,1,"g"],[7476,1,"h"],[7477,1,"i"],[7478,1,"j"],[7479,1,"k"],[7480,1,"l"],[7481,1,"m"],[7482,1,"n"],[7483,2],[7484,1,"o"],[7485,1,"ȣ"],[7486,1,"p"],[7487,1,"r"],[7488,1,"t"],[7489,1,"u"],[7490,1,"w"],[7491,1,"a"],[7492,1,"ɐ"],[7493,1,"ɑ"],[7494,1,"ᴂ"],[7495,1,"b"],[7496,1,"d"],[7497,1,"e"],[7498,1,"ə"],[7499,1,"ɛ"],[7500,1,"ɜ"],[7501,1,"g"],[7502,2],[7503,1,"k"],[7504,1,"m"],[7505,1,"ŋ"],[7506,1,"o"],[7507,1,"ɔ"],[7508,1,"ᴖ"],[7509,1,"ᴗ"],[7510,1,"p"],[7511,1,"t"],[7512,1,"u"],[7513,1,"ᴝ"],[7514,1,"ɯ"],[7515,1,"v"],[7516,1,"ᴥ"],[7517,1,"β"],[7518,1,"γ"],[7519,1,"δ"],[7520,1,"φ"],[7521,1,"χ"],[7522,1,"i"],[7523,1,"r"],[7524,1,"u"],[7525,1,"v"],[7526,1,"β"],[7527,1,"γ"],[7528,1,"ρ"],[7529,1,"φ"],[7530,1,"χ"],[7531,2],[[7532,7543],2],[7544,1,"н"],[[7545,7578],2],[7579,1,"ɒ"],[7580,1,"c"],[7581,1,"ɕ"],[7582,1,"ð"],[7583,1,"ɜ"],[7584,1,"f"],[7585,1,"ɟ"],[7586,1,"ɡ"],[7587,1,"ɥ"],[7588,1,"ɨ"],[7589,1,"ɩ"],[7590,1,"ɪ"],[7591,1,"ᵻ"],[7592,1,"ʝ"],[7593,1,"ɭ"],[7594,1,"ᶅ"],[7595,1,"ʟ"],[7596,1,"ɱ"],[7597,1,"ɰ"],[7598,1,"ɲ"],[7599,1,"ɳ"],[7600,1,"ɴ"],[7601,1,"ɵ"],[7602,1,"ɸ"],[7603,1,"ʂ"],[7604,1,"ʃ"],[7605,1,"ƫ"],[7606,1,"ʉ"],[7607,1,"ʊ"],[7608,1,"ᴜ"],[7609,1,"ʋ"],[7610,1,"ʌ"],[7611,1,"z"],[7612,1,"ʐ"],[7613,1,"ʑ"],[7614,1,"ʒ"],[7615,1,"θ"],[[7616,7619],2],[[7620,7626],2],[[7627,7654],2],[[7655,7669],2],[[7670,7673],2],[7674,2],[7675,2],[7676,2],[7677,2],[[7678,7679],2],[7680,1,"ḁ"],[7681,2],[7682,1,"ḃ"],[7683,2],[7684,1,"ḅ"],[7685,2],[7686,1,"ḇ"],[7687,2],[7688,1,"ḉ"],[7689,2],[7690,1,"ḋ"],[7691,2],[7692,1,"ḍ"],[7693,2],[7694,1,"ḏ"],[7695,2],[7696,1,"ḑ"],[7697,2],[7698,1,"ḓ"],[7699,2],[7700,1,"ḕ"],[7701,2],[7702,1,"ḗ"],[7703,2],[7704,1,"ḙ"],[7705,2],[7706,1,"ḛ"],[7707,2],[7708,1,"ḝ"],[7709,2],[7710,1,"ḟ"],[7711,2],[7712,1,"ḡ"],[7713,2],[7714,1,"ḣ"],[7715,2],[7716,1,"ḥ"],[7717,2],[7718,1,"ḧ"],[7719,2],[7720,1,"ḩ"],[7721,2],[7722,1,"ḫ"],[7723,2],[7724,1,"ḭ"],[7725,2],[7726,1,"ḯ"],[7727,2],[7728,1,"ḱ"],[7729,2],[7730,1,"ḳ"],[7731,2],[7732,1,"ḵ"],[7733,2],[7734,1,"ḷ"],[7735,2],[7736,1,"ḹ"],[7737,2],[7738,1,"ḻ"],[7739,2],[7740,1,"ḽ"],[7741,2],[7742,1,"ḿ"],[7743,2],[7744,1,"ṁ"],[7745,2],[7746,1,"ṃ"],[7747,2],[7748,1,"ṅ"],[7749,2],[7750,1,"ṇ"],[7751,2],[7752,1,"ṉ"],[7753,2],[7754,1,"ṋ"],[7755,2],[7756,1,"ṍ"],[7757,2],[7758,1,"ṏ"],[7759,2],[7760,1,"ṑ"],[7761,2],[7762,1,"ṓ"],[7763,2],[7764,1,"ṕ"],[7765,2],[7766,1,"ṗ"],[7767,2],[7768,1,"ṙ"],[7769,2],[7770,1,"ṛ"],[7771,2],[7772,1,"ṝ"],[7773,2],[7774,1,"ṟ"],[7775,2],[7776,1,"ṡ"],[7777,2],[7778,1,"ṣ"],[7779,2],[7780,1,"ṥ"],[7781,2],[7782,1,"ṧ"],[7783,2],[7784,1,"ṩ"],[7785,2],[7786,1,"ṫ"],[7787,2],[7788,1,"ṭ"],[7789,2],[7790,1,"ṯ"],[7791,2],[7792,1,"ṱ"],[7793,2],[7794,1,"ṳ"],[7795,2],[7796,1,"ṵ"],[7797,2],[7798,1,"ṷ"],[7799,2],[7800,1,"ṹ"],[7801,2],[7802,1,"ṻ"],[7803,2],[7804,1,"ṽ"],[7805,2],[7806,1,"ṿ"],[7807,2],[7808,1,"ẁ"],[7809,2],[7810,1,"ẃ"],[7811,2],[7812,1,"ẅ"],[7813,2],[7814,1,"ẇ"],[7815,2],[7816,1,"ẉ"],[7817,2],[7818,1,"ẋ"],[7819,2],[7820,1,"ẍ"],[7821,2],[7822,1,"ẏ"],[7823,2],[7824,1,"ẑ"],[7825,2],[7826,1,"ẓ"],[7827,2],[7828,1,"ẕ"],[[7829,7833],2],[7834,1,"aʾ"],[7835,1,"ṡ"],[[7836,7837],2],[7838,1,"ss"],[7839,2],[7840,1,"ạ"],[7841,2],[7842,1,"ả"],[7843,2],[7844,1,"ấ"],[7845,2],[7846,1,"ầ"],[7847,2],[7848,1,"ẩ"],[7849,2],[7850,1,"ẫ"],[7851,2],[7852,1,"ậ"],[7853,2],[7854,1,"ắ"],[7855,2],[7856,1,"ằ"],[7857,2],[7858,1,"ẳ"],[7859,2],[7860,1,"ẵ"],[7861,2],[7862,1,"ặ"],[7863,2],[7864,1,"ẹ"],[7865,2],[7866,1,"ẻ"],[7867,2],[7868,1,"ẽ"],[7869,2],[7870,1,"ế"],[7871,2],[7872,1,"ề"],[7873,2],[7874,1,"ể"],[7875,2],[7876,1,"ễ"],[7877,2],[7878,1,"ệ"],[7879,2],[7880,1,"ỉ"],[7881,2],[7882,1,"ị"],[7883,2],[7884,1,"ọ"],[7885,2],[7886,1,"ỏ"],[7887,2],[7888,1,"ố"],[7889,2],[7890,1,"ồ"],[7891,2],[7892,1,"ổ"],[7893,2],[7894,1,"ỗ"],[7895,2],[7896,1,"ộ"],[7897,2],[7898,1,"ớ"],[7899,2],[7900,1,"ờ"],[7901,2],[7902,1,"ở"],[7903,2],[7904,1,"ỡ"],[7905,2],[7906,1,"ợ"],[7907,2],[7908,1,"ụ"],[7909,2],[7910,1,"ủ"],[7911,2],[7912,1,"ứ"],[7913,2],[7914,1,"ừ"],[7915,2],[7916,1,"ử"],[7917,2],[7918,1,"ữ"],[7919,2],[7920,1,"ự"],[7921,2],[7922,1,"ỳ"],[7923,2],[7924,1,"ỵ"],[7925,2],[7926,1,"ỷ"],[7927,2],[7928,1,"ỹ"],[7929,2],[7930,1,"ỻ"],[7931,2],[7932,1,"ỽ"],[7933,2],[7934,1,"ỿ"],[7935,2],[[7936,7943],2],[7944,1,"ἀ"],[7945,1,"ἁ"],[7946,1,"ἂ"],[7947,1,"ἃ"],[7948,1,"ἄ"],[7949,1,"ἅ"],[7950,1,"ἆ"],[7951,1,"ἇ"],[[7952,7957],2],[[7958,7959],3],[7960,1,"ἐ"],[7961,1,"ἑ"],[7962,1,"ἒ"],[7963,1,"ἓ"],[7964,1,"ἔ"],[7965,1,"ἕ"],[[7966,7967],3],[[7968,7975],2],[7976,1,"ἠ"],[7977,1,"ἡ"],[7978,1,"ἢ"],[7979,1,"ἣ"],[7980,1,"ἤ"],[7981,1,"ἥ"],[7982,1,"ἦ"],[7983,1,"ἧ"],[[7984,7991],2],[7992,1,"ἰ"],[7993,1,"ἱ"],[7994,1,"ἲ"],[7995,1,"ἳ"],[7996,1,"ἴ"],[7997,1,"ἵ"],[7998,1,"ἶ"],[7999,1,"ἷ"],[[8000,8005],2],[[8006,8007],3],[8008,1,"ὀ"],[8009,1,"ὁ"],[8010,1,"ὂ"],[8011,1,"ὃ"],[8012,1,"ὄ"],[8013,1,"ὅ"],[[8014,8015],3],[[8016,8023],2],[8024,3],[8025,1,"ὑ"],[8026,3],[8027,1,"ὓ"],[8028,3],[8029,1,"ὕ"],[8030,3],[8031,1,"ὗ"],[[8032,8039],2],[8040,1,"ὠ"],[8041,1,"ὡ"],[8042,1,"ὢ"],[8043,1,"ὣ"],[8044,1,"ὤ"],[8045,1,"ὥ"],[8046,1,"ὦ"],[8047,1,"ὧ"],[8048,2],[8049,1,"ά"],[8050,2],[8051,1,"έ"],[8052,2],[8053,1,"ή"],[8054,2],[8055,1,"ί"],[8056,2],[8057,1,"ό"],[8058,2],[8059,1,"ύ"],[8060,2],[8061,1,"ώ"],[[8062,8063],3],[8064,1,"ἀι"],[8065,1,"ἁι"],[8066,1,"ἂι"],[8067,1,"ἃι"],[8068,1,"ἄι"],[8069,1,"ἅι"],[8070,1,"ἆι"],[8071,1,"ἇι"],[8072,1,"ἀι"],[8073,1,"ἁι"],[8074,1,"ἂι"],[8075,1,"ἃι"],[8076,1,"ἄι"],[8077,1,"ἅι"],[8078,1,"ἆι"],[8079,1,"ἇι"],[8080,1,"ἠι"],[8081,1,"ἡι"],[8082,1,"ἢι"],[8083,1,"ἣι"],[8084,1,"ἤι"],[8085,1,"ἥι"],[8086,1,"ἦι"],[8087,1,"ἧι"],[8088,1,"ἠι"],[8089,1,"ἡι"],[8090,1,"ἢι"],[8091,1,"ἣι"],[8092,1,"ἤι"],[8093,1,"ἥι"],[8094,1,"ἦι"],[8095,1,"ἧι"],[8096,1,"ὠι"],[8097,1,"ὡι"],[8098,1,"ὢι"],[8099,1,"ὣι"],[8100,1,"ὤι"],[8101,1,"ὥι"],[8102,1,"ὦι"],[8103,1,"ὧι"],[8104,1,"ὠι"],[8105,1,"ὡι"],[8106,1,"ὢι"],[8107,1,"ὣι"],[8108,1,"ὤι"],[8109,1,"ὥι"],[8110,1,"ὦι"],[8111,1,"ὧι"],[[8112,8113],2],[8114,1,"ὰι"],[8115,1,"αι"],[8116,1,"άι"],[8117,3],[8118,2],[8119,1,"ᾶι"],[8120,1,"ᾰ"],[8121,1,"ᾱ"],[8122,1,"ὰ"],[8123,1,"ά"],[8124,1,"αι"],[8125,5," ̓"],[8126,1,"ι"],[8127,5," ̓"],[8128,5," ͂"],[8129,5," ̈͂"],[8130,1,"ὴι"],[8131,1,"ηι"],[8132,1,"ήι"],[8133,3],[8134,2],[8135,1,"ῆι"],[8136,1,"ὲ"],[8137,1,"έ"],[8138,1,"ὴ"],[8139,1,"ή"],[8140,1,"ηι"],[8141,5," ̓̀"],[8142,5," ̓́"],[8143,5," ̓͂"],[[8144,8146],2],[8147,1,"ΐ"],[[8148,8149],3],[[8150,8151],2],[8152,1,"ῐ"],[8153,1,"ῑ"],[8154,1,"ὶ"],[8155,1,"ί"],[8156,3],[8157,5," ̔̀"],[8158,5," ̔́"],[8159,5," ̔͂"],[[8160,8162],2],[8163,1,"ΰ"],[[8164,8167],2],[8168,1,"ῠ"],[8169,1,"ῡ"],[8170,1,"ὺ"],[8171,1,"ύ"],[8172,1,"ῥ"],[8173,5," ̈̀"],[8174,5," ̈́"],[8175,5,"`"],[[8176,8177],3],[8178,1,"ὼι"],[8179,1,"ωι"],[8180,1,"ώι"],[8181,3],[8182,2],[8183,1,"ῶι"],[8184,1,"ὸ"],[8185,1,"ό"],[8186,1,"ὼ"],[8187,1,"ώ"],[8188,1,"ωι"],[8189,5," ́"],[8190,5," ̔"],[8191,3],[[8192,8202],5," "],[8203,7],[[8204,8205],6,""],[[8206,8207],3],[8208,2],[8209,1,"‐"],[[8210,8214],2],[8215,5," ̳"],[[8216,8227],2],[[8228,8230],3],[8231,2],[[8232,8238],3],[8239,5," "],[[8240,8242],2],[8243,1,"′′"],[8244,1,"′′′"],[8245,2],[8246,1,"‵‵"],[8247,1,"‵‵‵"],[[8248,8251],2],[8252,5,"!!"],[8253,2],[8254,5," ̅"],[[8255,8262],2],[8263,5,"??"],[8264,5,"?!"],[8265,5,"!?"],[[8266,8269],2],[[8270,8274],2],[[8275,8276],2],[[8277,8278],2],[8279,1,"′′′′"],[[8280,8286],2],[8287,5," "],[8288,7],[[8289,8291],3],[8292,7],[8293,3],[[8294,8297],3],[[8298,8303],3],[8304,1,"0"],[8305,1,"i"],[[8306,8307],3],[8308,1,"4"],[8309,1,"5"],[8310,1,"6"],[8311,1,"7"],[8312,1,"8"],[8313,1,"9"],[8314,5,"+"],[8315,1,"−"],[8316,5,"="],[8317,5,"("],[8318,5,")"],[8319,1,"n"],[8320,1,"0"],[8321,1,"1"],[8322,1,"2"],[8323,1,"3"],[8324,1,"4"],[8325,1,"5"],[8326,1,"6"],[8327,1,"7"],[8328,1,"8"],[8329,1,"9"],[8330,5,"+"],[8331,1,"−"],[8332,5,"="],[8333,5,"("],[8334,5,")"],[8335,3],[8336,1,"a"],[8337,1,"e"],[8338,1,"o"],[8339,1,"x"],[8340,1,"ə"],[8341,1,"h"],[8342,1,"k"],[8343,1,"l"],[8344,1,"m"],[8345,1,"n"],[8346,1,"p"],[8347,1,"s"],[8348,1,"t"],[[8349,8351],3],[[8352,8359],2],[8360,1,"rs"],[[8361,8362],2],[8363,2],[8364,2],[[8365,8367],2],[[8368,8369],2],[[8370,8373],2],[[8374,8376],2],[8377,2],[8378,2],[[8379,8381],2],[8382,2],[8383,2],[8384,2],[[8385,8399],3],[[8400,8417],2],[[8418,8419],2],[[8420,8426],2],[8427,2],[[8428,8431],2],[8432,2],[[8433,8447],3],[8448,5,"a/c"],[8449,5,"a/s"],[8450,1,"c"],[8451,1,"°c"],[8452,2],[8453,5,"c/o"],[8454,5,"c/u"],[8455,1,"ɛ"],[8456,2],[8457,1,"°f"],[8458,1,"g"],[[8459,8462],1,"h"],[8463,1,"ħ"],[[8464,8465],1,"i"],[[8466,8467],1,"l"],[8468,2],[8469,1,"n"],[8470,1,"no"],[[8471,8472],2],[8473,1,"p"],[8474,1,"q"],[[8475,8477],1,"r"],[[8478,8479],2],[8480,1,"sm"],[8481,1,"tel"],[8482,1,"tm"],[8483,2],[8484,1,"z"],[8485,2],[8486,1,"ω"],[8487,2],[8488,1,"z"],[8489,2],[8490,1,"k"],[8491,1,"å"],[8492,1,"b"],[8493,1,"c"],[8494,2],[[8495,8496],1,"e"],[8497,1,"f"],[8498,3],[8499,1,"m"],[8500,1,"o"],[8501,1,"א"],[8502,1,"ב"],[8503,1,"ג"],[8504,1,"ד"],[8505,1,"i"],[8506,2],[8507,1,"fax"],[8508,1,"π"],[[8509,8510],1,"γ"],[8511,1,"π"],[8512,1,"∑"],[[8513,8516],2],[[8517,8518],1,"d"],[8519,1,"e"],[8520,1,"i"],[8521,1,"j"],[[8522,8523],2],[8524,2],[8525,2],[8526,2],[8527,2],[8528,1,"1⁄7"],[8529,1,"1⁄9"],[8530,1,"1⁄10"],[8531,1,"1⁄3"],[8532,1,"2⁄3"],[8533,1,"1⁄5"],[8534,1,"2⁄5"],[8535,1,"3⁄5"],[8536,1,"4⁄5"],[8537,1,"1⁄6"],[8538,1,"5⁄6"],[8539,1,"1⁄8"],[8540,1,"3⁄8"],[8541,1,"5⁄8"],[8542,1,"7⁄8"],[8543,1,"1⁄"],[8544,1,"i"],[8545,1,"ii"],[8546,1,"iii"],[8547,1,"iv"],[8548,1,"v"],[8549,1,"vi"],[8550,1,"vii"],[8551,1,"viii"],[8552,1,"ix"],[8553,1,"x"],[8554,1,"xi"],[8555,1,"xii"],[8556,1,"l"],[8557,1,"c"],[8558,1,"d"],[8559,1,"m"],[8560,1,"i"],[8561,1,"ii"],[8562,1,"iii"],[8563,1,"iv"],[8564,1,"v"],[8565,1,"vi"],[8566,1,"vii"],[8567,1,"viii"],[8568,1,"ix"],[8569,1,"x"],[8570,1,"xi"],[8571,1,"xii"],[8572,1,"l"],[8573,1,"c"],[8574,1,"d"],[8575,1,"m"],[[8576,8578],2],[8579,3],[8580,2],[[8581,8584],2],[8585,1,"0⁄3"],[[8586,8587],2],[[8588,8591],3],[[8592,8682],2],[[8683,8691],2],[[8692,8703],2],[[8704,8747],2],[8748,1,"∫∫"],[8749,1,"∫∫∫"],[8750,2],[8751,1,"∮∮"],[8752,1,"∮∮∮"],[[8753,8799],2],[8800,4],[[8801,8813],2],[[8814,8815],4],[[8816,8945],2],[[8946,8959],2],[8960,2],[8961,2],[[8962,9000],2],[9001,1,"〈"],[9002,1,"〉"],[[9003,9082],2],[9083,2],[9084,2],[[9085,9114],2],[[9115,9166],2],[[9167,9168],2],[[9169,9179],2],[[9180,9191],2],[9192,2],[[9193,9203],2],[[9204,9210],2],[[9211,9214],2],[9215,2],[[9216,9252],2],[[9253,9254],2],[[9255,9279],3],[[9280,9290],2],[[9291,9311],3],[9312,1,"1"],[9313,1,"2"],[9314,1,"3"],[9315,1,"4"],[9316,1,"5"],[9317,1,"6"],[9318,1,"7"],[9319,1,"8"],[9320,1,"9"],[9321,1,"10"],[9322,1,"11"],[9323,1,"12"],[9324,1,"13"],[9325,1,"14"],[9326,1,"15"],[9327,1,"16"],[9328,1,"17"],[9329,1,"18"],[9330,1,"19"],[9331,1,"20"],[9332,5,"(1)"],[9333,5,"(2)"],[9334,5,"(3)"],[9335,5,"(4)"],[9336,5,"(5)"],[9337,5,"(6)"],[9338,5,"(7)"],[9339,5,"(8)"],[9340,5,"(9)"],[9341,5,"(10)"],[9342,5,"(11)"],[9343,5,"(12)"],[9344,5,"(13)"],[9345,5,"(14)"],[9346,5,"(15)"],[9347,5,"(16)"],[9348,5,"(17)"],[9349,5,"(18)"],[9350,5,"(19)"],[9351,5,"(20)"],[[9352,9371],3],[9372,5,"(a)"],[9373,5,"(b)"],[9374,5,"(c)"],[9375,5,"(d)"],[9376,5,"(e)"],[9377,5,"(f)"],[9378,5,"(g)"],[9379,5,"(h)"],[9380,5,"(i)"],[9381,5,"(j)"],[9382,5,"(k)"],[9383,5,"(l)"],[9384,5,"(m)"],[9385,5,"(n)"],[9386,5,"(o)"],[9387,5,"(p)"],[9388,5,"(q)"],[9389,5,"(r)"],[9390,5,"(s)"],[9391,5,"(t)"],[9392,5,"(u)"],[9393,5,"(v)"],[9394,5,"(w)"],[9395,5,"(x)"],[9396,5,"(y)"],[9397,5,"(z)"],[9398,1,"a"],[9399,1,"b"],[9400,1,"c"],[9401,1,"d"],[9402,1,"e"],[9403,1,"f"],[9404,1,"g"],[9405,1,"h"],[9406,1,"i"],[9407,1,"j"],[9408,1,"k"],[9409,1,"l"],[9410,1,"m"],[9411,1,"n"],[9412,1,"o"],[9413,1,"p"],[9414,1,"q"],[9415,1,"r"],[9416,1,"s"],[9417,1,"t"],[9418,1,"u"],[9419,1,"v"],[9420,1,"w"],[9421,1,"x"],[9422,1,"y"],[9423,1,"z"],[9424,1,"a"],[9425,1,"b"],[9426,1,"c"],[9427,1,"d"],[9428,1,"e"],[9429,1,"f"],[9430,1,"g"],[9431,1,"h"],[9432,1,"i"],[9433,1,"j"],[9434,1,"k"],[9435,1,"l"],[9436,1,"m"],[9437,1,"n"],[9438,1,"o"],[9439,1,"p"],[9440,1,"q"],[9441,1,"r"],[9442,1,"s"],[9443,1,"t"],[9444,1,"u"],[9445,1,"v"],[9446,1,"w"],[9447,1,"x"],[9448,1,"y"],[9449,1,"z"],[9450,1,"0"],[[9451,9470],2],[9471,2],[[9472,9621],2],[[9622,9631],2],[[9632,9711],2],[[9712,9719],2],[[9720,9727],2],[[9728,9747],2],[[9748,9749],2],[[9750,9751],2],[9752,2],[9753,2],[[9754,9839],2],[[9840,9841],2],[[9842,9853],2],[[9854,9855],2],[[9856,9865],2],[[9866,9873],2],[[9874,9884],2],[9885,2],[[9886,9887],2],[[9888,9889],2],[[9890,9905],2],[9906,2],[[9907,9916],2],[[9917,9919],2],[[9920,9923],2],[[9924,9933],2],[9934,2],[[9935,9953],2],[9954,2],[9955,2],[[9956,9959],2],[[9960,9983],2],[9984,2],[[9985,9988],2],[9989,2],[[9990,9993],2],[[9994,9995],2],[[9996,10023],2],[10024,2],[[10025,10059],2],[10060,2],[10061,2],[10062,2],[[10063,10066],2],[[10067,10069],2],[10070,2],[10071,2],[[10072,10078],2],[[10079,10080],2],[[10081,10087],2],[[10088,10101],2],[[10102,10132],2],[[10133,10135],2],[[10136,10159],2],[10160,2],[[10161,10174],2],[10175,2],[[10176,10182],2],[[10183,10186],2],[10187,2],[10188,2],[10189,2],[[10190,10191],2],[[10192,10219],2],[[10220,10223],2],[[10224,10239],2],[[10240,10495],2],[[10496,10763],2],[10764,1,"∫∫∫∫"],[[10765,10867],2],[10868,5,"::="],[10869,5,"=="],[10870,5,"==="],[[10871,10971],2],[10972,1,"⫝̸"],[[10973,11007],2],[[11008,11021],2],[[11022,11027],2],[[11028,11034],2],[[11035,11039],2],[[11040,11043],2],[[11044,11084],2],[[11085,11087],2],[[11088,11092],2],[[11093,11097],2],[[11098,11123],2],[[11124,11125],3],[[11126,11157],2],[11158,3],[11159,2],[[11160,11193],2],[[11194,11196],2],[[11197,11208],2],[11209,2],[[11210,11217],2],[11218,2],[[11219,11243],2],[[11244,11247],2],[[11248,11262],2],[11263,2],[11264,1,"ⰰ"],[11265,1,"ⰱ"],[11266,1,"ⰲ"],[11267,1,"ⰳ"],[11268,1,"ⰴ"],[11269,1,"ⰵ"],[11270,1,"ⰶ"],[11271,1,"ⰷ"],[11272,1,"ⰸ"],[11273,1,"ⰹ"],[11274,1,"ⰺ"],[11275,1,"ⰻ"],[11276,1,"ⰼ"],[11277,1,"ⰽ"],[11278,1,"ⰾ"],[11279,1,"ⰿ"],[11280,1,"ⱀ"],[11281,1,"ⱁ"],[11282,1,"ⱂ"],[11283,1,"ⱃ"],[11284,1,"ⱄ"],[11285,1,"ⱅ"],[11286,1,"ⱆ"],[11287,1,"ⱇ"],[11288,1,"ⱈ"],[11289,1,"ⱉ"],[11290,1,"ⱊ"],[11291,1,"ⱋ"],[11292,1,"ⱌ"],[11293,1,"ⱍ"],[11294,1,"ⱎ"],[11295,1,"ⱏ"],[11296,1,"ⱐ"],[11297,1,"ⱑ"],[11298,1,"ⱒ"],[11299,1,"ⱓ"],[11300,1,"ⱔ"],[11301,1,"ⱕ"],[11302,1,"ⱖ"],[11303,1,"ⱗ"],[11304,1,"ⱘ"],[11305,1,"ⱙ"],[11306,1,"ⱚ"],[11307,1,"ⱛ"],[11308,1,"ⱜ"],[11309,1,"ⱝ"],[11310,1,"ⱞ"],[11311,1,"ⱟ"],[[11312,11358],2],[11359,2],[11360,1,"ⱡ"],[11361,2],[11362,1,"ɫ"],[11363,1,"ᵽ"],[11364,1,"ɽ"],[[11365,11366],2],[11367,1,"ⱨ"],[11368,2],[11369,1,"ⱪ"],[11370,2],[11371,1,"ⱬ"],[11372,2],[11373,1,"ɑ"],[11374,1,"ɱ"],[11375,1,"ɐ"],[11376,1,"ɒ"],[11377,2],[11378,1,"ⱳ"],[11379,2],[11380,2],[11381,1,"ⱶ"],[[11382,11383],2],[[11384,11387],2],[11388,1,"j"],[11389,1,"v"],[11390,1,"ȿ"],[11391,1,"ɀ"],[11392,1,"ⲁ"],[11393,2],[11394,1,"ⲃ"],[11395,2],[11396,1,"ⲅ"],[11397,2],[11398,1,"ⲇ"],[11399,2],[11400,1,"ⲉ"],[11401,2],[11402,1,"ⲋ"],[11403,2],[11404,1,"ⲍ"],[11405,2],[11406,1,"ⲏ"],[11407,2],[11408,1,"ⲑ"],[11409,2],[11410,1,"ⲓ"],[11411,2],[11412,1,"ⲕ"],[11413,2],[11414,1,"ⲗ"],[11415,2],[11416,1,"ⲙ"],[11417,2],[11418,1,"ⲛ"],[11419,2],[11420,1,"ⲝ"],[11421,2],[11422,1,"ⲟ"],[11423,2],[11424,1,"ⲡ"],[11425,2],[11426,1,"ⲣ"],[11427,2],[11428,1,"ⲥ"],[11429,2],[11430,1,"ⲧ"],[11431,2],[11432,1,"ⲩ"],[11433,2],[11434,1,"ⲫ"],[11435,2],[11436,1,"ⲭ"],[11437,2],[11438,1,"ⲯ"],[11439,2],[11440,1,"ⲱ"],[11441,2],[11442,1,"ⲳ"],[11443,2],[11444,1,"ⲵ"],[11445,2],[11446,1,"ⲷ"],[11447,2],[11448,1,"ⲹ"],[11449,2],[11450,1,"ⲻ"],[11451,2],[11452,1,"ⲽ"],[11453,2],[11454,1,"ⲿ"],[11455,2],[11456,1,"ⳁ"],[11457,2],[11458,1,"ⳃ"],[11459,2],[11460,1,"ⳅ"],[11461,2],[11462,1,"ⳇ"],[11463,2],[11464,1,"ⳉ"],[11465,2],[11466,1,"ⳋ"],[11467,2],[11468,1,"ⳍ"],[11469,2],[11470,1,"ⳏ"],[11471,2],[11472,1,"ⳑ"],[11473,2],[11474,1,"ⳓ"],[11475,2],[11476,1,"ⳕ"],[11477,2],[11478,1,"ⳗ"],[11479,2],[11480,1,"ⳙ"],[11481,2],[11482,1,"ⳛ"],[11483,2],[11484,1,"ⳝ"],[11485,2],[11486,1,"ⳟ"],[11487,2],[11488,1,"ⳡ"],[11489,2],[11490,1,"ⳣ"],[[11491,11492],2],[[11493,11498],2],[11499,1,"ⳬ"],[11500,2],[11501,1,"ⳮ"],[[11502,11505],2],[11506,1,"ⳳ"],[11507,2],[[11508,11512],3],[[11513,11519],2],[[11520,11557],2],[11558,3],[11559,2],[[11560,11564],3],[11565,2],[[11566,11567],3],[[11568,11621],2],[[11622,11623],2],[[11624,11630],3],[11631,1,"ⵡ"],[11632,2],[[11633,11646],3],[11647,2],[[11648,11670],2],[[11671,11679],3],[[11680,11686],2],[11687,3],[[11688,11694],2],[11695,3],[[11696,11702],2],[11703,3],[[11704,11710],2],[11711,3],[[11712,11718],2],[11719,3],[[11720,11726],2],[11727,3],[[11728,11734],2],[11735,3],[[11736,11742],2],[11743,3],[[11744,11775],2],[[11776,11799],2],[[11800,11803],2],[[11804,11805],2],[[11806,11822],2],[11823,2],[11824,2],[11825,2],[[11826,11835],2],[[11836,11842],2],[[11843,11844],2],[[11845,11849],2],[[11850,11854],2],[11855,2],[[11856,11858],2],[[11859,11869],2],[[11870,11903],3],[[11904,11929],2],[11930,3],[[11931,11934],2],[11935,1,"母"],[[11936,12018],2],[12019,1,"龟"],[[12020,12031],3],[12032,1,"一"],[12033,1,"丨"],[12034,1,"丶"],[12035,1,"丿"],[12036,1,"乙"],[12037,1,"亅"],[12038,1,"二"],[12039,1,"亠"],[12040,1,"人"],[12041,1,"儿"],[12042,1,"入"],[12043,1,"八"],[12044,1,"冂"],[12045,1,"冖"],[12046,1,"冫"],[12047,1,"几"],[12048,1,"凵"],[12049,1,"刀"],[12050,1,"力"],[12051,1,"勹"],[12052,1,"匕"],[12053,1,"匚"],[12054,1,"匸"],[12055,1,"十"],[12056,1,"卜"],[12057,1,"卩"],[12058,1,"厂"],[12059,1,"厶"],[12060,1,"又"],[12061,1,"口"],[12062,1,"囗"],[12063,1,"土"],[12064,1,"士"],[12065,1,"夂"],[12066,1,"夊"],[12067,1,"夕"],[12068,1,"大"],[12069,1,"女"],[12070,1,"子"],[12071,1,"宀"],[12072,1,"寸"],[12073,1,"小"],[12074,1,"尢"],[12075,1,"尸"],[12076,1,"屮"],[12077,1,"山"],[12078,1,"巛"],[12079,1,"工"],[12080,1,"己"],[12081,1,"巾"],[12082,1,"干"],[12083,1,"幺"],[12084,1,"广"],[12085,1,"廴"],[12086,1,"廾"],[12087,1,"弋"],[12088,1,"弓"],[12089,1,"彐"],[12090,1,"彡"],[12091,1,"彳"],[12092,1,"心"],[12093,1,"戈"],[12094,1,"戶"],[12095,1,"手"],[12096,1,"支"],[12097,1,"攴"],[12098,1,"文"],[12099,1,"斗"],[12100,1,"斤"],[12101,1,"方"],[12102,1,"无"],[12103,1,"日"],[12104,1,"曰"],[12105,1,"月"],[12106,1,"木"],[12107,1,"欠"],[12108,1,"止"],[12109,1,"歹"],[12110,1,"殳"],[12111,1,"毋"],[12112,1,"比"],[12113,1,"毛"],[12114,1,"氏"],[12115,1,"气"],[12116,1,"水"],[12117,1,"火"],[12118,1,"爪"],[12119,1,"父"],[12120,1,"爻"],[12121,1,"爿"],[12122,1,"片"],[12123,1,"牙"],[12124,1,"牛"],[12125,1,"犬"],[12126,1,"玄"],[12127,1,"玉"],[12128,1,"瓜"],[12129,1,"瓦"],[12130,1,"甘"],[12131,1,"生"],[12132,1,"用"],[12133,1,"田"],[12134,1,"疋"],[12135,1,"疒"],[12136,1,"癶"],[12137,1,"白"],[12138,1,"皮"],[12139,1,"皿"],[12140,1,"目"],[12141,1,"矛"],[12142,1,"矢"],[12143,1,"石"],[12144,1,"示"],[12145,1,"禸"],[12146,1,"禾"],[12147,1,"穴"],[12148,1,"立"],[12149,1,"竹"],[12150,1,"米"],[12151,1,"糸"],[12152,1,"缶"],[12153,1,"网"],[12154,1,"羊"],[12155,1,"羽"],[12156,1,"老"],[12157,1,"而"],[12158,1,"耒"],[12159,1,"耳"],[12160,1,"聿"],[12161,1,"肉"],[12162,1,"臣"],[12163,1,"自"],[12164,1,"至"],[12165,1,"臼"],[12166,1,"舌"],[12167,1,"舛"],[12168,1,"舟"],[12169,1,"艮"],[12170,1,"色"],[12171,1,"艸"],[12172,1,"虍"],[12173,1,"虫"],[12174,1,"血"],[12175,1,"行"],[12176,1,"衣"],[12177,1,"襾"],[12178,1,"見"],[12179,1,"角"],[12180,1,"言"],[12181,1,"谷"],[12182,1,"豆"],[12183,1,"豕"],[12184,1,"豸"],[12185,1,"貝"],[12186,1,"赤"],[12187,1,"走"],[12188,1,"足"],[12189,1,"身"],[12190,1,"車"],[12191,1,"辛"],[12192,1,"辰"],[12193,1,"辵"],[12194,1,"邑"],[12195,1,"酉"],[12196,1,"釆"],[12197,1,"里"],[12198,1,"金"],[12199,1,"長"],[12200,1,"門"],[12201,1,"阜"],[12202,1,"隶"],[12203,1,"隹"],[12204,1,"雨"],[12205,1,"靑"],[12206,1,"非"],[12207,1,"面"],[12208,1,"革"],[12209,1,"韋"],[12210,1,"韭"],[12211,1,"音"],[12212,1,"頁"],[12213,1,"風"],[12214,1,"飛"],[12215,1,"食"],[12216,1,"首"],[12217,1,"香"],[12218,1,"馬"],[12219,1,"骨"],[12220,1,"高"],[12221,1,"髟"],[12222,1,"鬥"],[12223,1,"鬯"],[12224,1,"鬲"],[12225,1,"鬼"],[12226,1,"魚"],[12227,1,"鳥"],[12228,1,"鹵"],[12229,1,"鹿"],[12230,1,"麥"],[12231,1,"麻"],[12232,1,"黃"],[12233,1,"黍"],[12234,1,"黑"],[12235,1,"黹"],[12236,1,"黽"],[12237,1,"鼎"],[12238,1,"鼓"],[12239,1,"鼠"],[12240,1,"鼻"],[12241,1,"齊"],[12242,1,"齒"],[12243,1,"龍"],[12244,1,"龜"],[12245,1,"龠"],[[12246,12271],3],[[12272,12283],3],[[12284,12287],3],[12288,5," "],[12289,2],[12290,1,"."],[[12291,12292],2],[[12293,12295],2],[[12296,12329],2],[[12330,12333],2],[[12334,12341],2],[12342,1,"〒"],[12343,2],[12344,1,"十"],[12345,1,"卄"],[12346,1,"卅"],[12347,2],[12348,2],[12349,2],[12350,2],[12351,2],[12352,3],[[12353,12436],2],[[12437,12438],2],[[12439,12440],3],[[12441,12442],2],[12443,5," ゙"],[12444,5," ゚"],[[12445,12446],2],[12447,1,"より"],[12448,2],[[12449,12542],2],[12543,1,"コト"],[[12544,12548],3],[[12549,12588],2],[12589,2],[12590,2],[12591,2],[12592,3],[12593,1,"ᄀ"],[12594,1,"ᄁ"],[12595,1,"ᆪ"],[12596,1,"ᄂ"],[12597,1,"ᆬ"],[12598,1,"ᆭ"],[12599,1,"ᄃ"],[12600,1,"ᄄ"],[12601,1,"ᄅ"],[12602,1,"ᆰ"],[12603,1,"ᆱ"],[12604,1,"ᆲ"],[12605,1,"ᆳ"],[12606,1,"ᆴ"],[12607,1,"ᆵ"],[12608,1,"ᄚ"],[12609,1,"ᄆ"],[12610,1,"ᄇ"],[12611,1,"ᄈ"],[12612,1,"ᄡ"],[12613,1,"ᄉ"],[12614,1,"ᄊ"],[12615,1,"ᄋ"],[12616,1,"ᄌ"],[12617,1,"ᄍ"],[12618,1,"ᄎ"],[12619,1,"ᄏ"],[12620,1,"ᄐ"],[12621,1,"ᄑ"],[12622,1,"ᄒ"],[12623,1,"ᅡ"],[12624,1,"ᅢ"],[12625,1,"ᅣ"],[12626,1,"ᅤ"],[12627,1,"ᅥ"],[12628,1,"ᅦ"],[12629,1,"ᅧ"],[12630,1,"ᅨ"],[12631,1,"ᅩ"],[12632,1,"ᅪ"],[12633,1,"ᅫ"],[12634,1,"ᅬ"],[12635,1,"ᅭ"],[12636,1,"ᅮ"],[12637,1,"ᅯ"],[12638,1,"ᅰ"],[12639,1,"ᅱ"],[12640,1,"ᅲ"],[12641,1,"ᅳ"],[12642,1,"ᅴ"],[12643,1,"ᅵ"],[12644,3],[12645,1,"ᄔ"],[12646,1,"ᄕ"],[12647,1,"ᇇ"],[12648,1,"ᇈ"],[12649,1,"ᇌ"],[12650,1,"ᇎ"],[12651,1,"ᇓ"],[12652,1,"ᇗ"],[12653,1,"ᇙ"],[12654,1,"ᄜ"],[12655,1,"ᇝ"],[12656,1,"ᇟ"],[12657,1,"ᄝ"],[12658,1,"ᄞ"],[12659,1,"ᄠ"],[12660,1,"ᄢ"],[12661,1,"ᄣ"],[12662,1,"ᄧ"],[12663,1,"ᄩ"],[12664,1,"ᄫ"],[12665,1,"ᄬ"],[12666,1,"ᄭ"],[12667,1,"ᄮ"],[12668,1,"ᄯ"],[12669,1,"ᄲ"],[12670,1,"ᄶ"],[12671,1,"ᅀ"],[12672,1,"ᅇ"],[12673,1,"ᅌ"],[12674,1,"ᇱ"],[12675,1,"ᇲ"],[12676,1,"ᅗ"],[12677,1,"ᅘ"],[12678,1,"ᅙ"],[12679,1,"ᆄ"],[12680,1,"ᆅ"],[12681,1,"ᆈ"],[12682,1,"ᆑ"],[12683,1,"ᆒ"],[12684,1,"ᆔ"],[12685,1,"ᆞ"],[12686,1,"ᆡ"],[12687,3],[[12688,12689],2],[12690,1,"一"],[12691,1,"二"],[12692,1,"三"],[12693,1,"四"],[12694,1,"上"],[12695,1,"中"],[12696,1,"下"],[12697,1,"甲"],[12698,1,"乙"],[12699,1,"丙"],[12700,1,"丁"],[12701,1,"天"],[12702,1,"地"],[12703,1,"人"],[[12704,12727],2],[[12728,12730],2],[[12731,12735],2],[[12736,12751],2],[[12752,12771],2],[[12772,12783],3],[[12784,12799],2],[12800,5,"(ᄀ)"],[12801,5,"(ᄂ)"],[12802,5,"(ᄃ)"],[12803,5,"(ᄅ)"],[12804,5,"(ᄆ)"],[12805,5,"(ᄇ)"],[12806,5,"(ᄉ)"],[12807,5,"(ᄋ)"],[12808,5,"(ᄌ)"],[12809,5,"(ᄎ)"],[12810,5,"(ᄏ)"],[12811,5,"(ᄐ)"],[12812,5,"(ᄑ)"],[12813,5,"(ᄒ)"],[12814,5,"(가)"],[12815,5,"(나)"],[12816,5,"(다)"],[12817,5,"(라)"],[12818,5,"(마)"],[12819,5,"(바)"],[12820,5,"(사)"],[12821,5,"(아)"],[12822,5,"(자)"],[12823,5,"(차)"],[12824,5,"(카)"],[12825,5,"(타)"],[12826,5,"(파)"],[12827,5,"(하)"],[12828,5,"(주)"],[12829,5,"(오전)"],[12830,5,"(오후)"],[12831,3],[12832,5,"(一)"],[12833,5,"(二)"],[12834,5,"(三)"],[12835,5,"(四)"],[12836,5,"(五)"],[12837,5,"(六)"],[12838,5,"(七)"],[12839,5,"(八)"],[12840,5,"(九)"],[12841,5,"(十)"],[12842,5,"(月)"],[12843,5,"(火)"],[12844,5,"(水)"],[12845,5,"(木)"],[12846,5,"(金)"],[12847,5,"(土)"],[12848,5,"(日)"],[12849,5,"(株)"],[12850,5,"(有)"],[12851,5,"(社)"],[12852,5,"(名)"],[12853,5,"(特)"],[12854,5,"(財)"],[12855,5,"(祝)"],[12856,5,"(労)"],[12857,5,"(代)"],[12858,5,"(呼)"],[12859,5,"(学)"],[12860,5,"(監)"],[12861,5,"(企)"],[12862,5,"(資)"],[12863,5,"(協)"],[12864,5,"(祭)"],[12865,5,"(休)"],[12866,5,"(自)"],[12867,5,"(至)"],[12868,1,"問"],[12869,1,"幼"],[12870,1,"文"],[12871,1,"箏"],[[12872,12879],2],[12880,1,"pte"],[12881,1,"21"],[12882,1,"22"],[12883,1,"23"],[12884,1,"24"],[12885,1,"25"],[12886,1,"26"],[12887,1,"27"],[12888,1,"28"],[12889,1,"29"],[12890,1,"30"],[12891,1,"31"],[12892,1,"32"],[12893,1,"33"],[12894,1,"34"],[12895,1,"35"],[12896,1,"ᄀ"],[12897,1,"ᄂ"],[12898,1,"ᄃ"],[12899,1,"ᄅ"],[12900,1,"ᄆ"],[12901,1,"ᄇ"],[12902,1,"ᄉ"],[12903,1,"ᄋ"],[12904,1,"ᄌ"],[12905,1,"ᄎ"],[12906,1,"ᄏ"],[12907,1,"ᄐ"],[12908,1,"ᄑ"],[12909,1,"ᄒ"],[12910,1,"가"],[12911,1,"나"],[12912,1,"다"],[12913,1,"라"],[12914,1,"마"],[12915,1,"바"],[12916,1,"사"],[12917,1,"아"],[12918,1,"자"],[12919,1,"차"],[12920,1,"카"],[12921,1,"타"],[12922,1,"파"],[12923,1,"하"],[12924,1,"참고"],[12925,1,"주의"],[12926,1,"우"],[12927,2],[12928,1,"一"],[12929,1,"二"],[12930,1,"三"],[12931,1,"四"],[12932,1,"五"],[12933,1,"六"],[12934,1,"七"],[12935,1,"八"],[12936,1,"九"],[12937,1,"十"],[12938,1,"月"],[12939,1,"火"],[12940,1,"水"],[12941,1,"木"],[12942,1,"金"],[12943,1,"土"],[12944,1,"日"],[12945,1,"株"],[12946,1,"有"],[12947,1,"社"],[12948,1,"名"],[12949,1,"特"],[12950,1,"財"],[12951,1,"祝"],[12952,1,"労"],[12953,1,"秘"],[12954,1,"男"],[12955,1,"女"],[12956,1,"適"],[12957,1,"優"],[12958,1,"印"],[12959,1,"注"],[12960,1,"項"],[12961,1,"休"],[12962,1,"写"],[12963,1,"正"],[12964,1,"上"],[12965,1,"中"],[12966,1,"下"],[12967,1,"左"],[12968,1,"右"],[12969,1,"医"],[12970,1,"宗"],[12971,1,"学"],[12972,1,"監"],[12973,1,"企"],[12974,1,"資"],[12975,1,"協"],[12976,1,"夜"],[12977,1,"36"],[12978,1,"37"],[12979,1,"38"],[12980,1,"39"],[12981,1,"40"],[12982,1,"41"],[12983,1,"42"],[12984,1,"43"],[12985,1,"44"],[12986,1,"45"],[12987,1,"46"],[12988,1,"47"],[12989,1,"48"],[12990,1,"49"],[12991,1,"50"],[12992,1,"1月"],[12993,1,"2月"],[12994,1,"3月"],[12995,1,"4月"],[12996,1,"5月"],[12997,1,"6月"],[12998,1,"7月"],[12999,1,"8月"],[13000,1,"9月"],[13001,1,"10月"],[13002,1,"11月"],[13003,1,"12月"],[13004,1,"hg"],[13005,1,"erg"],[13006,1,"ev"],[13007,1,"ltd"],[13008,1,"ア"],[13009,1,"イ"],[13010,1,"ウ"],[13011,1,"エ"],[13012,1,"オ"],[13013,1,"カ"],[13014,1,"キ"],[13015,1,"ク"],[13016,1,"ケ"],[13017,1,"コ"],[13018,1,"サ"],[13019,1,"シ"],[13020,1,"ス"],[13021,1,"セ"],[13022,1,"ソ"],[13023,1,"タ"],[13024,1,"チ"],[13025,1,"ツ"],[13026,1,"テ"],[13027,1,"ト"],[13028,1,"ナ"],[13029,1,"ニ"],[13030,1,"ヌ"],[13031,1,"ネ"],[13032,1,"ノ"],[13033,1,"ハ"],[13034,1,"ヒ"],[13035,1,"フ"],[13036,1,"ヘ"],[13037,1,"ホ"],[13038,1,"マ"],[13039,1,"ミ"],[13040,1,"ム"],[13041,1,"メ"],[13042,1,"モ"],[13043,1,"ヤ"],[13044,1,"ユ"],[13045,1,"ヨ"],[13046,1,"ラ"],[13047,1,"リ"],[13048,1,"ル"],[13049,1,"レ"],[13050,1,"ロ"],[13051,1,"ワ"],[13052,1,"ヰ"],[13053,1,"ヱ"],[13054,1,"ヲ"],[13055,1,"令和"],[13056,1,"アパート"],[13057,1,"アルファ"],[13058,1,"アンペア"],[13059,1,"アール"],[13060,1,"イニング"],[13061,1,"インチ"],[13062,1,"ウォン"],[13063,1,"エスクード"],[13064,1,"エーカー"],[13065,1,"オンス"],[13066,1,"オーム"],[13067,1,"カイリ"],[13068,1,"カラット"],[13069,1,"カロリー"],[13070,1,"ガロン"],[13071,1,"ガンマ"],[13072,1,"ギガ"],[13073,1,"ギニー"],[13074,1,"キュリー"],[13075,1,"ギルダー"],[13076,1,"キロ"],[13077,1,"キログラム"],[13078,1,"キロメートル"],[13079,1,"キロワット"],[13080,1,"グラム"],[13081,1,"グラムトン"],[13082,1,"クルゼイロ"],[13083,1,"クローネ"],[13084,1,"ケース"],[13085,1,"コルナ"],[13086,1,"コーポ"],[13087,1,"サイクル"],[13088,1,"サンチーム"],[13089,1,"シリング"],[13090,1,"センチ"],[13091,1,"セント"],[13092,1,"ダース"],[13093,1,"デシ"],[13094,1,"ドル"],[13095,1,"トン"],[13096,1,"ナノ"],[13097,1,"ノット"],[13098,1,"ハイツ"],[13099,1,"パーセント"],[13100,1,"パーツ"],[13101,1,"バーレル"],[13102,1,"ピアストル"],[13103,1,"ピクル"],[13104,1,"ピコ"],[13105,1,"ビル"],[13106,1,"ファラッド"],[13107,1,"フィート"],[13108,1,"ブッシェル"],[13109,1,"フラン"],[13110,1,"ヘクタール"],[13111,1,"ペソ"],[13112,1,"ペニヒ"],[13113,1,"ヘルツ"],[13114,1,"ペンス"],[13115,1,"ページ"],[13116,1,"ベータ"],[13117,1,"ポイント"],[13118,1,"ボルト"],[13119,1,"ホン"],[13120,1,"ポンド"],[13121,1,"ホール"],[13122,1,"ホーン"],[13123,1,"マイクロ"],[13124,1,"マイル"],[13125,1,"マッハ"],[13126,1,"マルク"],[13127,1,"マンション"],[13128,1,"ミクロン"],[13129,1,"ミリ"],[13130,1,"ミリバール"],[13131,1,"メガ"],[13132,1,"メガトン"],[13133,1,"メートル"],[13134,1,"ヤード"],[13135,1,"ヤール"],[13136,1,"ユアン"],[13137,1,"リットル"],[13138,1,"リラ"],[13139,1,"ルピー"],[13140,1,"ルーブル"],[13141,1,"レム"],[13142,1,"レントゲン"],[13143,1,"ワット"],[13144,1,"0点"],[13145,1,"1点"],[13146,1,"2点"],[13147,1,"3点"],[13148,1,"4点"],[13149,1,"5点"],[13150,1,"6点"],[13151,1,"7点"],[13152,1,"8点"],[13153,1,"9点"],[13154,1,"10点"],[13155,1,"11点"],[13156,1,"12点"],[13157,1,"13点"],[13158,1,"14点"],[13159,1,"15点"],[13160,1,"16点"],[13161,1,"17点"],[13162,1,"18点"],[13163,1,"19点"],[13164,1,"20点"],[13165,1,"21点"],[13166,1,"22点"],[13167,1,"23点"],[13168,1,"24点"],[13169,1,"hpa"],[13170,1,"da"],[13171,1,"au"],[13172,1,"bar"],[13173,1,"ov"],[13174,1,"pc"],[13175,1,"dm"],[13176,1,"dm2"],[13177,1,"dm3"],[13178,1,"iu"],[13179,1,"平成"],[13180,1,"昭和"],[13181,1,"大正"],[13182,1,"明治"],[13183,1,"株式会社"],[13184,1,"pa"],[13185,1,"na"],[13186,1,"μa"],[13187,1,"ma"],[13188,1,"ka"],[13189,1,"kb"],[13190,1,"mb"],[13191,1,"gb"],[13192,1,"cal"],[13193,1,"kcal"],[13194,1,"pf"],[13195,1,"nf"],[13196,1,"μf"],[13197,1,"μg"],[13198,1,"mg"],[13199,1,"kg"],[13200,1,"hz"],[13201,1,"khz"],[13202,1,"mhz"],[13203,1,"ghz"],[13204,1,"thz"],[13205,1,"μl"],[13206,1,"ml"],[13207,1,"dl"],[13208,1,"kl"],[13209,1,"fm"],[13210,1,"nm"],[13211,1,"μm"],[13212,1,"mm"],[13213,1,"cm"],[13214,1,"km"],[13215,1,"mm2"],[13216,1,"cm2"],[13217,1,"m2"],[13218,1,"km2"],[13219,1,"mm3"],[13220,1,"cm3"],[13221,1,"m3"],[13222,1,"km3"],[13223,1,"m∕s"],[13224,1,"m∕s2"],[13225,1,"pa"],[13226,1,"kpa"],[13227,1,"mpa"],[13228,1,"gpa"],[13229,1,"rad"],[13230,1,"rad∕s"],[13231,1,"rad∕s2"],[13232,1,"ps"],[13233,1,"ns"],[13234,1,"μs"],[13235,1,"ms"],[13236,1,"pv"],[13237,1,"nv"],[13238,1,"μv"],[13239,1,"mv"],[13240,1,"kv"],[13241,1,"mv"],[13242,1,"pw"],[13243,1,"nw"],[13244,1,"μw"],[13245,1,"mw"],[13246,1,"kw"],[13247,1,"mw"],[13248,1,"kω"],[13249,1,"mω"],[13250,3],[13251,1,"bq"],[13252,1,"cc"],[13253,1,"cd"],[13254,1,"c∕kg"],[13255,3],[13256,1,"db"],[13257,1,"gy"],[13258,1,"ha"],[13259,1,"hp"],[13260,1,"in"],[13261,1,"kk"],[13262,1,"km"],[13263,1,"kt"],[13264,1,"lm"],[13265,1,"ln"],[13266,1,"log"],[13267,1,"lx"],[13268,1,"mb"],[13269,1,"mil"],[13270,1,"mol"],[13271,1,"ph"],[13272,3],[13273,1,"ppm"],[13274,1,"pr"],[13275,1,"sr"],[13276,1,"sv"],[13277,1,"wb"],[13278,1,"v∕m"],[13279,1,"a∕m"],[13280,1,"1日"],[13281,1,"2日"],[13282,1,"3日"],[13283,1,"4日"],[13284,1,"5日"],[13285,1,"6日"],[13286,1,"7日"],[13287,1,"8日"],[13288,1,"9日"],[13289,1,"10日"],[13290,1,"11日"],[13291,1,"12日"],[13292,1,"13日"],[13293,1,"14日"],[13294,1,"15日"],[13295,1,"16日"],[13296,1,"17日"],[13297,1,"18日"],[13298,1,"19日"],[13299,1,"20日"],[13300,1,"21日"],[13301,1,"22日"],[13302,1,"23日"],[13303,1,"24日"],[13304,1,"25日"],[13305,1,"26日"],[13306,1,"27日"],[13307,1,"28日"],[13308,1,"29日"],[13309,1,"30日"],[13310,1,"31日"],[13311,1,"gal"],[[13312,19893],2],[[19894,19903],2],[[19904,19967],2],[[19968,40869],2],[[40870,40891],2],[[40892,40899],2],[[40900,40907],2],[40908,2],[[40909,40917],2],[[40918,40938],2],[[40939,40943],2],[[40944,40956],2],[[40957,40959],2],[[40960,42124],2],[[42125,42127],3],[[42128,42145],2],[[42146,42147],2],[[42148,42163],2],[42164,2],[[42165,42176],2],[42177,2],[[42178,42180],2],[42181,2],[42182,2],[[42183,42191],3],[[42192,42237],2],[[42238,42239],2],[[42240,42508],2],[[42509,42511],2],[[42512,42539],2],[[42540,42559],3],[42560,1,"ꙁ"],[42561,2],[42562,1,"ꙃ"],[42563,2],[42564,1,"ꙅ"],[42565,2],[42566,1,"ꙇ"],[42567,2],[42568,1,"ꙉ"],[42569,2],[42570,1,"ꙋ"],[42571,2],[42572,1,"ꙍ"],[42573,2],[42574,1,"ꙏ"],[42575,2],[42576,1,"ꙑ"],[42577,2],[42578,1,"ꙓ"],[42579,2],[42580,1,"ꙕ"],[42581,2],[42582,1,"ꙗ"],[42583,2],[42584,1,"ꙙ"],[42585,2],[42586,1,"ꙛ"],[42587,2],[42588,1,"ꙝ"],[42589,2],[42590,1,"ꙟ"],[42591,2],[42592,1,"ꙡ"],[42593,2],[42594,1,"ꙣ"],[42595,2],[42596,1,"ꙥ"],[42597,2],[42598,1,"ꙧ"],[42599,2],[42600,1,"ꙩ"],[42601,2],[42602,1,"ꙫ"],[42603,2],[42604,1,"ꙭ"],[[42605,42607],2],[[42608,42611],2],[[42612,42619],2],[[42620,42621],2],[42622,2],[42623,2],[42624,1,"ꚁ"],[42625,2],[42626,1,"ꚃ"],[42627,2],[42628,1,"ꚅ"],[42629,2],[42630,1,"ꚇ"],[42631,2],[42632,1,"ꚉ"],[42633,2],[42634,1,"ꚋ"],[42635,2],[42636,1,"ꚍ"],[42637,2],[42638,1,"ꚏ"],[42639,2],[42640,1,"ꚑ"],[42641,2],[42642,1,"ꚓ"],[42643,2],[42644,1,"ꚕ"],[42645,2],[42646,1,"ꚗ"],[42647,2],[42648,1,"ꚙ"],[42649,2],[42650,1,"ꚛ"],[42651,2],[42652,1,"ъ"],[42653,1,"ь"],[42654,2],[42655,2],[[42656,42725],2],[[42726,42735],2],[[42736,42737],2],[[42738,42743],2],[[42744,42751],3],[[42752,42774],2],[[42775,42778],2],[[42779,42783],2],[[42784,42785],2],[42786,1,"ꜣ"],[42787,2],[42788,1,"ꜥ"],[42789,2],[42790,1,"ꜧ"],[42791,2],[42792,1,"ꜩ"],[42793,2],[42794,1,"ꜫ"],[42795,2],[42796,1,"ꜭ"],[42797,2],[42798,1,"ꜯ"],[[42799,42801],2],[42802,1,"ꜳ"],[42803,2],[42804,1,"ꜵ"],[42805,2],[42806,1,"ꜷ"],[42807,2],[42808,1,"ꜹ"],[42809,2],[42810,1,"ꜻ"],[42811,2],[42812,1,"ꜽ"],[42813,2],[42814,1,"ꜿ"],[42815,2],[42816,1,"ꝁ"],[42817,2],[42818,1,"ꝃ"],[42819,2],[42820,1,"ꝅ"],[42821,2],[42822,1,"ꝇ"],[42823,2],[42824,1,"ꝉ"],[42825,2],[42826,1,"ꝋ"],[42827,2],[42828,1,"ꝍ"],[42829,2],[42830,1,"ꝏ"],[42831,2],[42832,1,"ꝑ"],[42833,2],[42834,1,"ꝓ"],[42835,2],[42836,1,"ꝕ"],[42837,2],[42838,1,"ꝗ"],[42839,2],[42840,1,"ꝙ"],[42841,2],[42842,1,"ꝛ"],[42843,2],[42844,1,"ꝝ"],[42845,2],[42846,1,"ꝟ"],[42847,2],[42848,1,"ꝡ"],[42849,2],[42850,1,"ꝣ"],[42851,2],[42852,1,"ꝥ"],[42853,2],[42854,1,"ꝧ"],[42855,2],[42856,1,"ꝩ"],[42857,2],[42858,1,"ꝫ"],[42859,2],[42860,1,"ꝭ"],[42861,2],[42862,1,"ꝯ"],[42863,2],[42864,1,"ꝯ"],[[42865,42872],2],[42873,1,"ꝺ"],[42874,2],[42875,1,"ꝼ"],[42876,2],[42877,1,"ᵹ"],[42878,1,"ꝿ"],[42879,2],[42880,1,"ꞁ"],[42881,2],[42882,1,"ꞃ"],[42883,2],[42884,1,"ꞅ"],[42885,2],[42886,1,"ꞇ"],[[42887,42888],2],[[42889,42890],2],[42891,1,"ꞌ"],[42892,2],[42893,1,"ɥ"],[42894,2],[42895,2],[42896,1,"ꞑ"],[42897,2],[42898,1,"ꞓ"],[42899,2],[[42900,42901],2],[42902,1,"ꞗ"],[42903,2],[42904,1,"ꞙ"],[42905,2],[42906,1,"ꞛ"],[42907,2],[42908,1,"ꞝ"],[42909,2],[42910,1,"ꞟ"],[42911,2],[42912,1,"ꞡ"],[42913,2],[42914,1,"ꞣ"],[42915,2],[42916,1,"ꞥ"],[42917,2],[42918,1,"ꞧ"],[42919,2],[42920,1,"ꞩ"],[42921,2],[42922,1,"ɦ"],[42923,1,"ɜ"],[42924,1,"ɡ"],[42925,1,"ɬ"],[42926,1,"ɪ"],[42927,2],[42928,1,"ʞ"],[42929,1,"ʇ"],[42930,1,"ʝ"],[42931,1,"ꭓ"],[42932,1,"ꞵ"],[42933,2],[42934,1,"ꞷ"],[42935,2],[42936,1,"ꞹ"],[42937,2],[42938,1,"ꞻ"],[42939,2],[42940,1,"ꞽ"],[42941,2],[42942,1,"ꞿ"],[42943,2],[42944,1,"ꟁ"],[42945,2],[42946,1,"ꟃ"],[42947,2],[42948,1,"ꞔ"],[42949,1,"ʂ"],[42950,1,"ᶎ"],[42951,1,"ꟈ"],[42952,2],[42953,1,"ꟊ"],[42954,2],[[42955,42959],3],[42960,1,"ꟑ"],[42961,2],[42962,3],[42963,2],[42964,3],[42965,2],[42966,1,"ꟗ"],[42967,2],[42968,1,"ꟙ"],[42969,2],[[42970,42993],3],[42994,1,"c"],[42995,1,"f"],[42996,1,"q"],[42997,1,"ꟶ"],[42998,2],[42999,2],[43000,1,"ħ"],[43001,1,"œ"],[43002,2],[[43003,43007],2],[[43008,43047],2],[[43048,43051],2],[43052,2],[[43053,43055],3],[[43056,43065],2],[[43066,43071],3],[[43072,43123],2],[[43124,43127],2],[[43128,43135],3],[[43136,43204],2],[43205,2],[[43206,43213],3],[[43214,43215],2],[[43216,43225],2],[[43226,43231],3],[[43232,43255],2],[[43256,43258],2],[43259,2],[43260,2],[43261,2],[[43262,43263],2],[[43264,43309],2],[[43310,43311],2],[[43312,43347],2],[[43348,43358],3],[43359,2],[[43360,43388],2],[[43389,43391],3],[[43392,43456],2],[[43457,43469],2],[43470,3],[[43471,43481],2],[[43482,43485],3],[[43486,43487],2],[[43488,43518],2],[43519,3],[[43520,43574],2],[[43575,43583],3],[[43584,43597],2],[[43598,43599],3],[[43600,43609],2],[[43610,43611],3],[[43612,43615],2],[[43616,43638],2],[[43639,43641],2],[[43642,43643],2],[[43644,43647],2],[[43648,43714],2],[[43715,43738],3],[[43739,43741],2],[[43742,43743],2],[[43744,43759],2],[[43760,43761],2],[[43762,43766],2],[[43767,43776],3],[[43777,43782],2],[[43783,43784],3],[[43785,43790],2],[[43791,43792],3],[[43793,43798],2],[[43799,43807],3],[[43808,43814],2],[43815,3],[[43816,43822],2],[43823,3],[[43824,43866],2],[43867,2],[43868,1,"ꜧ"],[43869,1,"ꬷ"],[43870,1,"ɫ"],[43871,1,"ꭒ"],[[43872,43875],2],[[43876,43877],2],[[43878,43879],2],[43880,2],[43881,1,"ʍ"],[[43882,43883],2],[[43884,43887],3],[43888,1,"Ꭰ"],[43889,1,"Ꭱ"],[43890,1,"Ꭲ"],[43891,1,"Ꭳ"],[43892,1,"Ꭴ"],[43893,1,"Ꭵ"],[43894,1,"Ꭶ"],[43895,1,"Ꭷ"],[43896,1,"Ꭸ"],[43897,1,"Ꭹ"],[43898,1,"Ꭺ"],[43899,1,"Ꭻ"],[43900,1,"Ꭼ"],[43901,1,"Ꭽ"],[43902,1,"Ꭾ"],[43903,1,"Ꭿ"],[43904,1,"Ꮀ"],[43905,1,"Ꮁ"],[43906,1,"Ꮂ"],[43907,1,"Ꮃ"],[43908,1,"Ꮄ"],[43909,1,"Ꮅ"],[43910,1,"Ꮆ"],[43911,1,"Ꮇ"],[43912,1,"Ꮈ"],[43913,1,"Ꮉ"],[43914,1,"Ꮊ"],[43915,1,"Ꮋ"],[43916,1,"Ꮌ"],[43917,1,"Ꮍ"],[43918,1,"Ꮎ"],[43919,1,"Ꮏ"],[43920,1,"Ꮐ"],[43921,1,"Ꮑ"],[43922,1,"Ꮒ"],[43923,1,"Ꮓ"],[43924,1,"Ꮔ"],[43925,1,"Ꮕ"],[43926,1,"Ꮖ"],[43927,1,"Ꮗ"],[43928,1,"Ꮘ"],[43929,1,"Ꮙ"],[43930,1,"Ꮚ"],[43931,1,"Ꮛ"],[43932,1,"Ꮜ"],[43933,1,"Ꮝ"],[43934,1,"Ꮞ"],[43935,1,"Ꮟ"],[43936,1,"Ꮠ"],[43937,1,"Ꮡ"],[43938,1,"Ꮢ"],[43939,1,"Ꮣ"],[43940,1,"Ꮤ"],[43941,1,"Ꮥ"],[43942,1,"Ꮦ"],[43943,1,"Ꮧ"],[43944,1,"Ꮨ"],[43945,1,"Ꮩ"],[43946,1,"Ꮪ"],[43947,1,"Ꮫ"],[43948,1,"Ꮬ"],[43949,1,"Ꮭ"],[43950,1,"Ꮮ"],[43951,1,"Ꮯ"],[43952,1,"Ꮰ"],[43953,1,"Ꮱ"],[43954,1,"Ꮲ"],[43955,1,"Ꮳ"],[43956,1,"Ꮴ"],[43957,1,"Ꮵ"],[43958,1,"Ꮶ"],[43959,1,"Ꮷ"],[43960,1,"Ꮸ"],[43961,1,"Ꮹ"],[43962,1,"Ꮺ"],[43963,1,"Ꮻ"],[43964,1,"Ꮼ"],[43965,1,"Ꮽ"],[43966,1,"Ꮾ"],[43967,1,"Ꮿ"],[[43968,44010],2],[44011,2],[[44012,44013],2],[[44014,44015],3],[[44016,44025],2],[[44026,44031],3],[[44032,55203],2],[[55204,55215],3],[[55216,55238],2],[[55239,55242],3],[[55243,55291],2],[[55292,55295],3],[[55296,57343],3],[[57344,63743],3],[63744,1,"豈"],[63745,1,"更"],[63746,1,"車"],[63747,1,"賈"],[63748,1,"滑"],[63749,1,"串"],[63750,1,"句"],[[63751,63752],1,"龜"],[63753,1,"契"],[63754,1,"金"],[63755,1,"喇"],[63756,1,"奈"],[63757,1,"懶"],[63758,1,"癩"],[63759,1,"羅"],[63760,1,"蘿"],[63761,1,"螺"],[63762,1,"裸"],[63763,1,"邏"],[63764,1,"樂"],[63765,1,"洛"],[63766,1,"烙"],[63767,1,"珞"],[63768,1,"落"],[63769,1,"酪"],[63770,1,"駱"],[63771,1,"亂"],[63772,1,"卵"],[63773,1,"欄"],[63774,1,"爛"],[63775,1,"蘭"],[63776,1,"鸞"],[63777,1,"嵐"],[63778,1,"濫"],[63779,1,"藍"],[63780,1,"襤"],[63781,1,"拉"],[63782,1,"臘"],[63783,1,"蠟"],[63784,1,"廊"],[63785,1,"朗"],[63786,1,"浪"],[63787,1,"狼"],[63788,1,"郎"],[63789,1,"來"],[63790,1,"冷"],[63791,1,"勞"],[63792,1,"擄"],[63793,1,"櫓"],[63794,1,"爐"],[63795,1,"盧"],[63796,1,"老"],[63797,1,"蘆"],[63798,1,"虜"],[63799,1,"路"],[63800,1,"露"],[63801,1,"魯"],[63802,1,"鷺"],[63803,1,"碌"],[63804,1,"祿"],[63805,1,"綠"],[63806,1,"菉"],[63807,1,"錄"],[63808,1,"鹿"],[63809,1,"論"],[63810,1,"壟"],[63811,1,"弄"],[63812,1,"籠"],[63813,1,"聾"],[63814,1,"牢"],[63815,1,"磊"],[63816,1,"賂"],[63817,1,"雷"],[63818,1,"壘"],[63819,1,"屢"],[63820,1,"樓"],[63821,1,"淚"],[63822,1,"漏"],[63823,1,"累"],[63824,1,"縷"],[63825,1,"陋"],[63826,1,"勒"],[63827,1,"肋"],[63828,1,"凜"],[63829,1,"凌"],[63830,1,"稜"],[63831,1,"綾"],[63832,1,"菱"],[63833,1,"陵"],[63834,1,"讀"],[63835,1,"拏"],[63836,1,"樂"],[63837,1,"諾"],[63838,1,"丹"],[63839,1,"寧"],[63840,1,"怒"],[63841,1,"率"],[63842,1,"異"],[63843,1,"北"],[63844,1,"磻"],[63845,1,"便"],[63846,1,"復"],[63847,1,"不"],[63848,1,"泌"],[63849,1,"數"],[63850,1,"索"],[63851,1,"參"],[63852,1,"塞"],[63853,1,"省"],[63854,1,"葉"],[63855,1,"說"],[63856,1,"殺"],[63857,1,"辰"],[63858,1,"沈"],[63859,1,"拾"],[63860,1,"若"],[63861,1,"掠"],[63862,1,"略"],[63863,1,"亮"],[63864,1,"兩"],[63865,1,"凉"],[63866,1,"梁"],[63867,1,"糧"],[63868,1,"良"],[63869,1,"諒"],[63870,1,"量"],[63871,1,"勵"],[63872,1,"呂"],[63873,1,"女"],[63874,1,"廬"],[63875,1,"旅"],[63876,1,"濾"],[63877,1,"礪"],[63878,1,"閭"],[63879,1,"驪"],[63880,1,"麗"],[63881,1,"黎"],[63882,1,"力"],[63883,1,"曆"],[63884,1,"歷"],[63885,1,"轢"],[63886,1,"年"],[63887,1,"憐"],[63888,1,"戀"],[63889,1,"撚"],[63890,1,"漣"],[63891,1,"煉"],[63892,1,"璉"],[63893,1,"秊"],[63894,1,"練"],[63895,1,"聯"],[63896,1,"輦"],[63897,1,"蓮"],[63898,1,"連"],[63899,1,"鍊"],[63900,1,"列"],[63901,1,"劣"],[63902,1,"咽"],[63903,1,"烈"],[63904,1,"裂"],[63905,1,"說"],[63906,1,"廉"],[63907,1,"念"],[63908,1,"捻"],[63909,1,"殮"],[63910,1,"簾"],[63911,1,"獵"],[63912,1,"令"],[63913,1,"囹"],[63914,1,"寧"],[63915,1,"嶺"],[63916,1,"怜"],[63917,1,"玲"],[63918,1,"瑩"],[63919,1,"羚"],[63920,1,"聆"],[63921,1,"鈴"],[63922,1,"零"],[63923,1,"靈"],[63924,1,"領"],[63925,1,"例"],[63926,1,"禮"],[63927,1,"醴"],[63928,1,"隸"],[63929,1,"惡"],[63930,1,"了"],[63931,1,"僚"],[63932,1,"寮"],[63933,1,"尿"],[63934,1,"料"],[63935,1,"樂"],[63936,1,"燎"],[63937,1,"療"],[63938,1,"蓼"],[63939,1,"遼"],[63940,1,"龍"],[63941,1,"暈"],[63942,1,"阮"],[63943,1,"劉"],[63944,1,"杻"],[63945,1,"柳"],[63946,1,"流"],[63947,1,"溜"],[63948,1,"琉"],[63949,1,"留"],[63950,1,"硫"],[63951,1,"紐"],[63952,1,"類"],[63953,1,"六"],[63954,1,"戮"],[63955,1,"陸"],[63956,1,"倫"],[63957,1,"崙"],[63958,1,"淪"],[63959,1,"輪"],[63960,1,"律"],[63961,1,"慄"],[63962,1,"栗"],[63963,1,"率"],[63964,1,"隆"],[63965,1,"利"],[63966,1,"吏"],[63967,1,"履"],[63968,1,"易"],[63969,1,"李"],[63970,1,"梨"],[63971,1,"泥"],[63972,1,"理"],[63973,1,"痢"],[63974,1,"罹"],[63975,1,"裏"],[63976,1,"裡"],[63977,1,"里"],[63978,1,"離"],[63979,1,"匿"],[63980,1,"溺"],[63981,1,"吝"],[63982,1,"燐"],[63983,1,"璘"],[63984,1,"藺"],[63985,1,"隣"],[63986,1,"鱗"],[63987,1,"麟"],[63988,1,"林"],[63989,1,"淋"],[63990,1,"臨"],[63991,1,"立"],[63992,1,"笠"],[63993,1,"粒"],[63994,1,"狀"],[63995,1,"炙"],[63996,1,"識"],[63997,1,"什"],[63998,1,"茶"],[63999,1,"刺"],[64000,1,"切"],[64001,1,"度"],[64002,1,"拓"],[64003,1,"糖"],[64004,1,"宅"],[64005,1,"洞"],[64006,1,"暴"],[64007,1,"輻"],[64008,1,"行"],[64009,1,"降"],[64010,1,"見"],[64011,1,"廓"],[64012,1,"兀"],[64013,1,"嗀"],[[64014,64015],2],[64016,1,"塚"],[64017,2],[64018,1,"晴"],[[64019,64020],2],[64021,1,"凞"],[64022,1,"猪"],[64023,1,"益"],[64024,1,"礼"],[64025,1,"神"],[64026,1,"祥"],[64027,1,"福"],[64028,1,"靖"],[64029,1,"精"],[64030,1,"羽"],[64031,2],[64032,1,"蘒"],[64033,2],[64034,1,"諸"],[[64035,64036],2],[64037,1,"逸"],[64038,1,"都"],[[64039,64041],2],[64042,1,"飯"],[64043,1,"飼"],[64044,1,"館"],[64045,1,"鶴"],[64046,1,"郞"],[64047,1,"隷"],[64048,1,"侮"],[64049,1,"僧"],[64050,1,"免"],[64051,1,"勉"],[64052,1,"勤"],[64053,1,"卑"],[64054,1,"喝"],[64055,1,"嘆"],[64056,1,"器"],[64057,1,"塀"],[64058,1,"墨"],[64059,1,"層"],[64060,1,"屮"],[64061,1,"悔"],[64062,1,"慨"],[64063,1,"憎"],[64064,1,"懲"],[64065,1,"敏"],[64066,1,"既"],[64067,1,"暑"],[64068,1,"梅"],[64069,1,"海"],[64070,1,"渚"],[64071,1,"漢"],[64072,1,"煮"],[64073,1,"爫"],[64074,1,"琢"],[64075,1,"碑"],[64076,1,"社"],[64077,1,"祉"],[64078,1,"祈"],[64079,1,"祐"],[64080,1,"祖"],[64081,1,"祝"],[64082,1,"禍"],[64083,1,"禎"],[64084,1,"穀"],[64085,1,"突"],[64086,1,"節"],[64087,1,"練"],[64088,1,"縉"],[64089,1,"繁"],[64090,1,"署"],[64091,1,"者"],[64092,1,"臭"],[[64093,64094],1,"艹"],[64095,1,"著"],[64096,1,"褐"],[64097,1,"視"],[64098,1,"謁"],[64099,1,"謹"],[64100,1,"賓"],[64101,1,"贈"],[64102,1,"辶"],[64103,1,"逸"],[64104,1,"難"],[64105,1,"響"],[64106,1,"頻"],[64107,1,"恵"],[64108,1,"𤋮"],[64109,1,"舘"],[[64110,64111],3],[64112,1,"並"],[64113,1,"况"],[64114,1,"全"],[64115,1,"侀"],[64116,1,"充"],[64117,1,"冀"],[64118,1,"勇"],[64119,1,"勺"],[64120,1,"喝"],[64121,1,"啕"],[64122,1,"喙"],[64123,1,"嗢"],[64124,1,"塚"],[64125,1,"墳"],[64126,1,"奄"],[64127,1,"奔"],[64128,1,"婢"],[64129,1,"嬨"],[64130,1,"廒"],[64131,1,"廙"],[64132,1,"彩"],[64133,1,"徭"],[64134,1,"惘"],[64135,1,"慎"],[64136,1,"愈"],[64137,1,"憎"],[64138,1,"慠"],[64139,1,"懲"],[64140,1,"戴"],[64141,1,"揄"],[64142,1,"搜"],[64143,1,"摒"],[64144,1,"敖"],[64145,1,"晴"],[64146,1,"朗"],[64147,1,"望"],[64148,1,"杖"],[64149,1,"歹"],[64150,1,"殺"],[64151,1,"流"],[64152,1,"滛"],[64153,1,"滋"],[64154,1,"漢"],[64155,1,"瀞"],[64156,1,"煮"],[64157,1,"瞧"],[64158,1,"爵"],[64159,1,"犯"],[64160,1,"猪"],[64161,1,"瑱"],[64162,1,"甆"],[64163,1,"画"],[64164,1,"瘝"],[64165,1,"瘟"],[64166,1,"益"],[64167,1,"盛"],[64168,1,"直"],[64169,1,"睊"],[64170,1,"着"],[64171,1,"磌"],[64172,1,"窱"],[64173,1,"節"],[64174,1,"类"],[64175,1,"絛"],[64176,1,"練"],[64177,1,"缾"],[64178,1,"者"],[64179,1,"荒"],[64180,1,"華"],[64181,1,"蝹"],[64182,1,"襁"],[64183,1,"覆"],[64184,1,"視"],[64185,1,"調"],[64186,1,"諸"],[64187,1,"請"],[64188,1,"謁"],[64189,1,"諾"],[64190,1,"諭"],[64191,1,"謹"],[64192,1,"變"],[64193,1,"贈"],[64194,1,"輸"],[64195,1,"遲"],[64196,1,"醙"],[64197,1,"鉶"],[64198,1,"陼"],[64199,1,"難"],[64200,1,"靖"],[64201,1,"韛"],[64202,1,"響"],[64203,1,"頋"],[64204,1,"頻"],[64205,1,"鬒"],[64206,1,"龜"],[64207,1,"𢡊"],[64208,1,"𢡄"],[64209,1,"𣏕"],[64210,1,"㮝"],[64211,1,"䀘"],[64212,1,"䀹"],[64213,1,"𥉉"],[64214,1,"𥳐"],[64215,1,"𧻓"],[64216,1,"齃"],[64217,1,"龎"],[[64218,64255],3],[64256,1,"ff"],[64257,1,"fi"],[64258,1,"fl"],[64259,1,"ffi"],[64260,1,"ffl"],[[64261,64262],1,"st"],[[64263,64274],3],[64275,1,"մն"],[64276,1,"մե"],[64277,1,"մի"],[64278,1,"վն"],[64279,1,"մխ"],[[64280,64284],3],[64285,1,"יִ"],[64286,2],[64287,1,"ײַ"],[64288,1,"ע"],[64289,1,"א"],[64290,1,"ד"],[64291,1,"ה"],[64292,1,"כ"],[64293,1,"ל"],[64294,1,"ם"],[64295,1,"ר"],[64296,1,"ת"],[64297,5,"+"],[64298,1,"שׁ"],[64299,1,"שׂ"],[64300,1,"שּׁ"],[64301,1,"שּׂ"],[64302,1,"אַ"],[64303,1,"אָ"],[64304,1,"אּ"],[64305,1,"בּ"],[64306,1,"גּ"],[64307,1,"דּ"],[64308,1,"הּ"],[64309,1,"וּ"],[64310,1,"זּ"],[64311,3],[64312,1,"טּ"],[64313,1,"יּ"],[64314,1,"ךּ"],[64315,1,"כּ"],[64316,1,"לּ"],[64317,3],[64318,1,"מּ"],[64319,3],[64320,1,"נּ"],[64321,1,"סּ"],[64322,3],[64323,1,"ףּ"],[64324,1,"פּ"],[64325,3],[64326,1,"צּ"],[64327,1,"קּ"],[64328,1,"רּ"],[64329,1,"שּ"],[64330,1,"תּ"],[64331,1,"וֹ"],[64332,1,"בֿ"],[64333,1,"כֿ"],[64334,1,"פֿ"],[64335,1,"אל"],[[64336,64337],1,"ٱ"],[[64338,64341],1,"ٻ"],[[64342,64345],1,"پ"],[[64346,64349],1,"ڀ"],[[64350,64353],1,"ٺ"],[[64354,64357],1,"ٿ"],[[64358,64361],1,"ٹ"],[[64362,64365],1,"ڤ"],[[64366,64369],1,"ڦ"],[[64370,64373],1,"ڄ"],[[64374,64377],1,"ڃ"],[[64378,64381],1,"چ"],[[64382,64385],1,"ڇ"],[[64386,64387],1,"ڍ"],[[64388,64389],1,"ڌ"],[[64390,64391],1,"ڎ"],[[64392,64393],1,"ڈ"],[[64394,64395],1,"ژ"],[[64396,64397],1,"ڑ"],[[64398,64401],1,"ک"],[[64402,64405],1,"گ"],[[64406,64409],1,"ڳ"],[[64410,64413],1,"ڱ"],[[64414,64415],1,"ں"],[[64416,64419],1,"ڻ"],[[64420,64421],1,"ۀ"],[[64422,64425],1,"ہ"],[[64426,64429],1,"ھ"],[[64430,64431],1,"ے"],[[64432,64433],1,"ۓ"],[[64434,64449],2],[64450,2],[[64451,64466],3],[[64467,64470],1,"ڭ"],[[64471,64472],1,"ۇ"],[[64473,64474],1,"ۆ"],[[64475,64476],1,"ۈ"],[64477,1,"ۇٴ"],[[64478,64479],1,"ۋ"],[[64480,64481],1,"ۅ"],[[64482,64483],1,"ۉ"],[[64484,64487],1,"ې"],[[64488,64489],1,"ى"],[[64490,64491],1,"ئا"],[[64492,64493],1,"ئە"],[[64494,64495],1,"ئو"],[[64496,64497],1,"ئۇ"],[[64498,64499],1,"ئۆ"],[[64500,64501],1,"ئۈ"],[[64502,64504],1,"ئې"],[[64505,64507],1,"ئى"],[[64508,64511],1,"ی"],[64512,1,"ئج"],[64513,1,"ئح"],[64514,1,"ئم"],[64515,1,"ئى"],[64516,1,"ئي"],[64517,1,"بج"],[64518,1,"بح"],[64519,1,"بخ"],[64520,1,"بم"],[64521,1,"بى"],[64522,1,"بي"],[64523,1,"تج"],[64524,1,"تح"],[64525,1,"تخ"],[64526,1,"تم"],[64527,1,"تى"],[64528,1,"تي"],[64529,1,"ثج"],[64530,1,"ثم"],[64531,1,"ثى"],[64532,1,"ثي"],[64533,1,"جح"],[64534,1,"جم"],[64535,1,"حج"],[64536,1,"حم"],[64537,1,"خج"],[64538,1,"خح"],[64539,1,"خم"],[64540,1,"سج"],[64541,1,"سح"],[64542,1,"سخ"],[64543,1,"سم"],[64544,1,"صح"],[64545,1,"صم"],[64546,1,"ضج"],[64547,1,"ضح"],[64548,1,"ضخ"],[64549,1,"ضم"],[64550,1,"طح"],[64551,1,"طم"],[64552,1,"ظم"],[64553,1,"عج"],[64554,1,"عم"],[64555,1,"غج"],[64556,1,"غم"],[64557,1,"فج"],[64558,1,"فح"],[64559,1,"فخ"],[64560,1,"فم"],[64561,1,"فى"],[64562,1,"في"],[64563,1,"قح"],[64564,1,"قم"],[64565,1,"قى"],[64566,1,"قي"],[64567,1,"كا"],[64568,1,"كج"],[64569,1,"كح"],[64570,1,"كخ"],[64571,1,"كل"],[64572,1,"كم"],[64573,1,"كى"],[64574,1,"كي"],[64575,1,"لج"],[64576,1,"لح"],[64577,1,"لخ"],[64578,1,"لم"],[64579,1,"لى"],[64580,1,"لي"],[64581,1,"مج"],[64582,1,"مح"],[64583,1,"مخ"],[64584,1,"مم"],[64585,1,"مى"],[64586,1,"مي"],[64587,1,"نج"],[64588,1,"نح"],[64589,1,"نخ"],[64590,1,"نم"],[64591,1,"نى"],[64592,1,"ني"],[64593,1,"هج"],[64594,1,"هم"],[64595,1,"هى"],[64596,1,"هي"],[64597,1,"يج"],[64598,1,"يح"],[64599,1,"يخ"],[64600,1,"يم"],[64601,1,"يى"],[64602,1,"يي"],[64603,1,"ذٰ"],[64604,1,"رٰ"],[64605,1,"ىٰ"],[64606,5," ٌّ"],[64607,5," ٍّ"],[64608,5," َّ"],[64609,5," ُّ"],[64610,5," ِّ"],[64611,5," ّٰ"],[64612,1,"ئر"],[64613,1,"ئز"],[64614,1,"ئم"],[64615,1,"ئن"],[64616,1,"ئى"],[64617,1,"ئي"],[64618,1,"بر"],[64619,1,"بز"],[64620,1,"بم"],[64621,1,"بن"],[64622,1,"بى"],[64623,1,"بي"],[64624,1,"تر"],[64625,1,"تز"],[64626,1,"تم"],[64627,1,"تن"],[64628,1,"تى"],[64629,1,"تي"],[64630,1,"ثر"],[64631,1,"ثز"],[64632,1,"ثم"],[64633,1,"ثن"],[64634,1,"ثى"],[64635,1,"ثي"],[64636,1,"فى"],[64637,1,"في"],[64638,1,"قى"],[64639,1,"قي"],[64640,1,"كا"],[64641,1,"كل"],[64642,1,"كم"],[64643,1,"كى"],[64644,1,"كي"],[64645,1,"لم"],[64646,1,"لى"],[64647,1,"لي"],[64648,1,"ما"],[64649,1,"مم"],[64650,1,"نر"],[64651,1,"نز"],[64652,1,"نم"],[64653,1,"نن"],[64654,1,"نى"],[64655,1,"ني"],[64656,1,"ىٰ"],[64657,1,"ير"],[64658,1,"يز"],[64659,1,"يم"],[64660,1,"ين"],[64661,1,"يى"],[64662,1,"يي"],[64663,1,"ئج"],[64664,1,"ئح"],[64665,1,"ئخ"],[64666,1,"ئم"],[64667,1,"ئه"],[64668,1,"بج"],[64669,1,"بح"],[64670,1,"بخ"],[64671,1,"بم"],[64672,1,"به"],[64673,1,"تج"],[64674,1,"تح"],[64675,1,"تخ"],[64676,1,"تم"],[64677,1,"ته"],[64678,1,"ثم"],[64679,1,"جح"],[64680,1,"جم"],[64681,1,"حج"],[64682,1,"حم"],[64683,1,"خج"],[64684,1,"خم"],[64685,1,"سج"],[64686,1,"سح"],[64687,1,"سخ"],[64688,1,"سم"],[64689,1,"صح"],[64690,1,"صخ"],[64691,1,"صم"],[64692,1,"ضج"],[64693,1,"ضح"],[64694,1,"ضخ"],[64695,1,"ضم"],[64696,1,"طح"],[64697,1,"ظم"],[64698,1,"عج"],[64699,1,"عم"],[64700,1,"غج"],[64701,1,"غم"],[64702,1,"فج"],[64703,1,"فح"],[64704,1,"فخ"],[64705,1,"فم"],[64706,1,"قح"],[64707,1,"قم"],[64708,1,"كج"],[64709,1,"كح"],[64710,1,"كخ"],[64711,1,"كل"],[64712,1,"كم"],[64713,1,"لج"],[64714,1,"لح"],[64715,1,"لخ"],[64716,1,"لم"],[64717,1,"له"],[64718,1,"مج"],[64719,1,"مح"],[64720,1,"مخ"],[64721,1,"مم"],[64722,1,"نج"],[64723,1,"نح"],[64724,1,"نخ"],[64725,1,"نم"],[64726,1,"نه"],[64727,1,"هج"],[64728,1,"هم"],[64729,1,"هٰ"],[64730,1,"يج"],[64731,1,"يح"],[64732,1,"يخ"],[64733,1,"يم"],[64734,1,"يه"],[64735,1,"ئم"],[64736,1,"ئه"],[64737,1,"بم"],[64738,1,"به"],[64739,1,"تم"],[64740,1,"ته"],[64741,1,"ثم"],[64742,1,"ثه"],[64743,1,"سم"],[64744,1,"سه"],[64745,1,"شم"],[64746,1,"شه"],[64747,1,"كل"],[64748,1,"كم"],[64749,1,"لم"],[64750,1,"نم"],[64751,1,"نه"],[64752,1,"يم"],[64753,1,"يه"],[64754,1,"ـَّ"],[64755,1,"ـُّ"],[64756,1,"ـِّ"],[64757,1,"طى"],[64758,1,"طي"],[64759,1,"عى"],[64760,1,"عي"],[64761,1,"غى"],[64762,1,"غي"],[64763,1,"سى"],[64764,1,"سي"],[64765,1,"شى"],[64766,1,"شي"],[64767,1,"حى"],[64768,1,"حي"],[64769,1,"جى"],[64770,1,"جي"],[64771,1,"خى"],[64772,1,"خي"],[64773,1,"صى"],[64774,1,"صي"],[64775,1,"ضى"],[64776,1,"ضي"],[64777,1,"شج"],[64778,1,"شح"],[64779,1,"شخ"],[64780,1,"شم"],[64781,1,"شر"],[64782,1,"سر"],[64783,1,"صر"],[64784,1,"ضر"],[64785,1,"طى"],[64786,1,"طي"],[64787,1,"عى"],[64788,1,"عي"],[64789,1,"غى"],[64790,1,"غي"],[64791,1,"سى"],[64792,1,"سي"],[64793,1,"شى"],[64794,1,"شي"],[64795,1,"حى"],[64796,1,"حي"],[64797,1,"جى"],[64798,1,"جي"],[64799,1,"خى"],[64800,1,"خي"],[64801,1,"صى"],[64802,1,"صي"],[64803,1,"ضى"],[64804,1,"ضي"],[64805,1,"شج"],[64806,1,"شح"],[64807,1,"شخ"],[64808,1,"شم"],[64809,1,"شر"],[64810,1,"سر"],[64811,1,"صر"],[64812,1,"ضر"],[64813,1,"شج"],[64814,1,"شح"],[64815,1,"شخ"],[64816,1,"شم"],[64817,1,"سه"],[64818,1,"شه"],[64819,1,"طم"],[64820,1,"سج"],[64821,1,"سح"],[64822,1,"سخ"],[64823,1,"شج"],[64824,1,"شح"],[64825,1,"شخ"],[64826,1,"طم"],[64827,1,"ظم"],[[64828,64829],1,"اً"],[[64830,64831],2],[[64832,64847],2],[64848,1,"تجم"],[[64849,64850],1,"تحج"],[64851,1,"تحم"],[64852,1,"تخم"],[64853,1,"تمج"],[64854,1,"تمح"],[64855,1,"تمخ"],[[64856,64857],1,"جمح"],[64858,1,"حمي"],[64859,1,"حمى"],[64860,1,"سحج"],[64861,1,"سجح"],[64862,1,"سجى"],[[64863,64864],1,"سمح"],[64865,1,"سمج"],[[64866,64867],1,"سمم"],[[64868,64869],1,"صحح"],[64870,1,"صمم"],[[64871,64872],1,"شحم"],[64873,1,"شجي"],[[64874,64875],1,"شمخ"],[[64876,64877],1,"شمم"],[64878,1,"ضحى"],[[64879,64880],1,"ضخم"],[[64881,64882],1,"طمح"],[64883,1,"طمم"],[64884,1,"طمي"],[64885,1,"عجم"],[[64886,64887],1,"عمم"],[64888,1,"عمى"],[64889,1,"غمم"],[64890,1,"غمي"],[64891,1,"غمى"],[[64892,64893],1,"فخم"],[64894,1,"قمح"],[64895,1,"قمم"],[64896,1,"لحم"],[64897,1,"لحي"],[64898,1,"لحى"],[[64899,64900],1,"لجج"],[[64901,64902],1,"لخم"],[[64903,64904],1,"لمح"],[64905,1,"محج"],[64906,1,"محم"],[64907,1,"محي"],[64908,1,"مجح"],[64909,1,"مجم"],[64910,1,"مخج"],[64911,1,"مخم"],[[64912,64913],3],[64914,1,"مجخ"],[64915,1,"همج"],[64916,1,"همم"],[64917,1,"نحم"],[64918,1,"نحى"],[[64919,64920],1,"نجم"],[64921,1,"نجى"],[64922,1,"نمي"],[64923,1,"نمى"],[[64924,64925],1,"يمم"],[64926,1,"بخي"],[64927,1,"تجي"],[64928,1,"تجى"],[64929,1,"تخي"],[64930,1,"تخى"],[64931,1,"تمي"],[64932,1,"تمى"],[64933,1,"جمي"],[64934,1,"جحى"],[64935,1,"جمى"],[64936,1,"سخى"],[64937,1,"صحي"],[64938,1,"شحي"],[64939,1,"ضحي"],[64940,1,"لجي"],[64941,1,"لمي"],[64942,1,"يحي"],[64943,1,"يجي"],[64944,1,"يمي"],[64945,1,"ممي"],[64946,1,"قمي"],[64947,1,"نحي"],[64948,1,"قمح"],[64949,1,"لحم"],[64950,1,"عمي"],[64951,1,"كمي"],[64952,1,"نجح"],[64953,1,"مخي"],[64954,1,"لجم"],[64955,1,"كمم"],[64956,1,"لجم"],[64957,1,"نجح"],[64958,1,"جحي"],[64959,1,"حجي"],[64960,1,"مجي"],[64961,1,"فمي"],[64962,1,"بحي"],[64963,1,"كمم"],[64964,1,"عجم"],[64965,1,"صمم"],[64966,1,"سخي"],[64967,1,"نجي"],[[64968,64974],3],[64975,2],[[64976,65007],3],[65008,1,"صلے"],[65009,1,"قلے"],[65010,1,"الله"],[65011,1,"اكبر"],[65012,1,"محمد"],[65013,1,"صلعم"],[65014,1,"رسول"],[65015,1,"عليه"],[65016,1,"وسلم"],[65017,1,"صلى"],[65018,5,"صلى الله عليه وسلم"],[65019,5,"جل جلاله"],[65020,1,"ریال"],[65021,2],[[65022,65023],2],[[65024,65039],7],[65040,5,","],[65041,1,"、"],[65042,3],[65043,5,":"],[65044,5,";"],[65045,5,"!"],[65046,5,"?"],[65047,1,"〖"],[65048,1,"〗"],[65049,3],[[65050,65055],3],[[65056,65059],2],[[65060,65062],2],[[65063,65069],2],[[65070,65071],2],[65072,3],[65073,1,"—"],[65074,1,"–"],[[65075,65076],5,"_"],[65077,5,"("],[65078,5,")"],[65079,5,"{"],[65080,5,"}"],[65081,1,"〔"],[65082,1,"〕"],[65083,1,"【"],[65084,1,"】"],[65085,1,"《"],[65086,1,"》"],[65087,1,"〈"],[65088,1,"〉"],[65089,1,"「"],[65090,1,"」"],[65091,1,"『"],[65092,1,"』"],[[65093,65094],2],[65095,5,"["],[65096,5,"]"],[[65097,65100],5," ̅"],[[65101,65103],5,"_"],[65104,5,","],[65105,1,"、"],[65106,3],[65107,3],[65108,5,";"],[65109,5,":"],[65110,5,"?"],[65111,5,"!"],[65112,1,"—"],[65113,5,"("],[65114,5,")"],[65115,5,"{"],[65116,5,"}"],[65117,1,"〔"],[65118,1,"〕"],[65119,5,"#"],[65120,5,"&"],[65121,5,"*"],[65122,5,"+"],[65123,1,"-"],[65124,5,"<"],[65125,5,">"],[65126,5,"="],[65127,3],[65128,5,"\\"],[65129,5,"$"],[65130,5,"%"],[65131,5,"@"],[[65132,65135],3],[65136,5," ً"],[65137,1,"ـً"],[65138,5," ٌ"],[65139,2],[65140,5," ٍ"],[65141,3],[65142,5," َ"],[65143,1,"ـَ"],[65144,5," ُ"],[65145,1,"ـُ"],[65146,5," ِ"],[65147,1,"ـِ"],[65148,5," ّ"],[65149,1,"ـّ"],[65150,5," ْ"],[65151,1,"ـْ"],[65152,1,"ء"],[[65153,65154],1,"آ"],[[65155,65156],1,"أ"],[[65157,65158],1,"ؤ"],[[65159,65160],1,"إ"],[[65161,65164],1,"ئ"],[[65165,65166],1,"ا"],[[65167,65170],1,"ب"],[[65171,65172],1,"ة"],[[65173,65176],1,"ت"],[[65177,65180],1,"ث"],[[65181,65184],1,"ج"],[[65185,65188],1,"ح"],[[65189,65192],1,"خ"],[[65193,65194],1,"د"],[[65195,65196],1,"ذ"],[[65197,65198],1,"ر"],[[65199,65200],1,"ز"],[[65201,65204],1,"س"],[[65205,65208],1,"ش"],[[65209,65212],1,"ص"],[[65213,65216],1,"ض"],[[65217,65220],1,"ط"],[[65221,65224],1,"ظ"],[[65225,65228],1,"ع"],[[65229,65232],1,"غ"],[[65233,65236],1,"ف"],[[65237,65240],1,"ق"],[[65241,65244],1,"ك"],[[65245,65248],1,"ل"],[[65249,65252],1,"م"],[[65253,65256],1,"ن"],[[65257,65260],1,"ه"],[[65261,65262],1,"و"],[[65263,65264],1,"ى"],[[65265,65268],1,"ي"],[[65269,65270],1,"لآ"],[[65271,65272],1,"لأ"],[[65273,65274],1,"لإ"],[[65275,65276],1,"لا"],[[65277,65278],3],[65279,7],[65280,3],[65281,5,"!"],[65282,5,"\""],[65283,5,"#"],[65284,5,"$"],[65285,5,"%"],[65286,5,"&"],[65287,5,"'"],[65288,5,"("],[65289,5,")"],[65290,5,"*"],[65291,5,"+"],[65292,5,","],[65293,1,"-"],[65294,1,"."],[65295,5,"/"],[65296,1,"0"],[65297,1,"1"],[65298,1,"2"],[65299,1,"3"],[65300,1,"4"],[65301,1,"5"],[65302,1,"6"],[65303,1,"7"],[65304,1,"8"],[65305,1,"9"],[65306,5,":"],[65307,5,";"],[65308,5,"<"],[65309,5,"="],[65310,5,">"],[65311,5,"?"],[65312,5,"@"],[65313,1,"a"],[65314,1,"b"],[65315,1,"c"],[65316,1,"d"],[65317,1,"e"],[65318,1,"f"],[65319,1,"g"],[65320,1,"h"],[65321,1,"i"],[65322,1,"j"],[65323,1,"k"],[65324,1,"l"],[65325,1,"m"],[65326,1,"n"],[65327,1,"o"],[65328,1,"p"],[65329,1,"q"],[65330,1,"r"],[65331,1,"s"],[65332,1,"t"],[65333,1,"u"],[65334,1,"v"],[65335,1,"w"],[65336,1,"x"],[65337,1,"y"],[65338,1,"z"],[65339,5,"["],[65340,5,"\\"],[65341,5,"]"],[65342,5,"^"],[65343,5,"_"],[65344,5,"`"],[65345,1,"a"],[65346,1,"b"],[65347,1,"c"],[65348,1,"d"],[65349,1,"e"],[65350,1,"f"],[65351,1,"g"],[65352,1,"h"],[65353,1,"i"],[65354,1,"j"],[65355,1,"k"],[65356,1,"l"],[65357,1,"m"],[65358,1,"n"],[65359,1,"o"],[65360,1,"p"],[65361,1,"q"],[65362,1,"r"],[65363,1,"s"],[65364,1,"t"],[65365,1,"u"],[65366,1,"v"],[65367,1,"w"],[65368,1,"x"],[65369,1,"y"],[65370,1,"z"],[65371,5,"{"],[65372,5,"|"],[65373,5,"}"],[65374,5,"~"],[65375,1,"⦅"],[65376,1,"⦆"],[65377,1,"."],[65378,1,"「"],[65379,1,"」"],[65380,1,"、"],[65381,1,"・"],[65382,1,"ヲ"],[65383,1,"ァ"],[65384,1,"ィ"],[65385,1,"ゥ"],[65386,1,"ェ"],[65387,1,"ォ"],[65388,1,"ャ"],[65389,1,"ュ"],[65390,1,"ョ"],[65391,1,"ッ"],[65392,1,"ー"],[65393,1,"ア"],[65394,1,"イ"],[65395,1,"ウ"],[65396,1,"エ"],[65397,1,"オ"],[65398,1,"カ"],[65399,1,"キ"],[65400,1,"ク"],[65401,1,"ケ"],[65402,1,"コ"],[65403,1,"サ"],[65404,1,"シ"],[65405,1,"ス"],[65406,1,"セ"],[65407,1,"ソ"],[65408,1,"タ"],[65409,1,"チ"],[65410,1,"ツ"],[65411,1,"テ"],[65412,1,"ト"],[65413,1,"ナ"],[65414,1,"ニ"],[65415,1,"ヌ"],[65416,1,"ネ"],[65417,1,"ノ"],[65418,1,"ハ"],[65419,1,"ヒ"],[65420,1,"フ"],[65421,1,"ヘ"],[65422,1,"ホ"],[65423,1,"マ"],[65424,1,"ミ"],[65425,1,"ム"],[65426,1,"メ"],[65427,1,"モ"],[65428,1,"ヤ"],[65429,1,"ユ"],[65430,1,"ヨ"],[65431,1,"ラ"],[65432,1,"リ"],[65433,1,"ル"],[65434,1,"レ"],[65435,1,"ロ"],[65436,1,"ワ"],[65437,1,"ン"],[65438,1,"゙"],[65439,1,"゚"],[65440,3],[65441,1,"ᄀ"],[65442,1,"ᄁ"],[65443,1,"ᆪ"],[65444,1,"ᄂ"],[65445,1,"ᆬ"],[65446,1,"ᆭ"],[65447,1,"ᄃ"],[65448,1,"ᄄ"],[65449,1,"ᄅ"],[65450,1,"ᆰ"],[65451,1,"ᆱ"],[65452,1,"ᆲ"],[65453,1,"ᆳ"],[65454,1,"ᆴ"],[65455,1,"ᆵ"],[65456,1,"ᄚ"],[65457,1,"ᄆ"],[65458,1,"ᄇ"],[65459,1,"ᄈ"],[65460,1,"ᄡ"],[65461,1,"ᄉ"],[65462,1,"ᄊ"],[65463,1,"ᄋ"],[65464,1,"ᄌ"],[65465,1,"ᄍ"],[65466,1,"ᄎ"],[65467,1,"ᄏ"],[65468,1,"ᄐ"],[65469,1,"ᄑ"],[65470,1,"ᄒ"],[[65471,65473],3],[65474,1,"ᅡ"],[65475,1,"ᅢ"],[65476,1,"ᅣ"],[65477,1,"ᅤ"],[65478,1,"ᅥ"],[65479,1,"ᅦ"],[[65480,65481],3],[65482,1,"ᅧ"],[65483,1,"ᅨ"],[65484,1,"ᅩ"],[65485,1,"ᅪ"],[65486,1,"ᅫ"],[65487,1,"ᅬ"],[[65488,65489],3],[65490,1,"ᅭ"],[65491,1,"ᅮ"],[65492,1,"ᅯ"],[65493,1,"ᅰ"],[65494,1,"ᅱ"],[65495,1,"ᅲ"],[[65496,65497],3],[65498,1,"ᅳ"],[65499,1,"ᅴ"],[65500,1,"ᅵ"],[[65501,65503],3],[65504,1,"¢"],[65505,1,"£"],[65506,1,"¬"],[65507,5," ̄"],[65508,1,"¦"],[65509,1,"¥"],[65510,1,"₩"],[65511,3],[65512,1,"│"],[65513,1,"←"],[65514,1,"↑"],[65515,1,"→"],[65516,1,"↓"],[65517,1,"■"],[65518,1,"○"],[[65519,65528],3],[[65529,65531],3],[65532,3],[65533,3],[[65534,65535],3],[[65536,65547],2],[65548,3],[[65549,65574],2],[65575,3],[[65576,65594],2],[65595,3],[[65596,65597],2],[65598,3],[[65599,65613],2],[[65614,65615],3],[[65616,65629],2],[[65630,65663],3],[[65664,65786],2],[[65787,65791],3],[[65792,65794],2],[[65795,65798],3],[[65799,65843],2],[[65844,65846],3],[[65847,65855],2],[[65856,65930],2],[[65931,65932],2],[[65933,65934],2],[65935,3],[[65936,65947],2],[65948,2],[[65949,65951],3],[65952,2],[[65953,65999],3],[[66000,66044],2],[66045,2],[[66046,66175],3],[[66176,66204],2],[[66205,66207],3],[[66208,66256],2],[[66257,66271],3],[66272,2],[[66273,66299],2],[[66300,66303],3],[[66304,66334],2],[66335,2],[[66336,66339],2],[[66340,66348],3],[[66349,66351],2],[[66352,66368],2],[66369,2],[[66370,66377],2],[66378,2],[[66379,66383],3],[[66384,66426],2],[[66427,66431],3],[[66432,66461],2],[66462,3],[66463,2],[[66464,66499],2],[[66500,66503],3],[[66504,66511],2],[[66512,66517],2],[[66518,66559],3],[66560,1,"𐐨"],[66561,1,"𐐩"],[66562,1,"𐐪"],[66563,1,"𐐫"],[66564,1,"𐐬"],[66565,1,"𐐭"],[66566,1,"𐐮"],[66567,1,"𐐯"],[66568,1,"𐐰"],[66569,1,"𐐱"],[66570,1,"𐐲"],[66571,1,"𐐳"],[66572,1,"𐐴"],[66573,1,"𐐵"],[66574,1,"𐐶"],[66575,1,"𐐷"],[66576,1,"𐐸"],[66577,1,"𐐹"],[66578,1,"𐐺"],[66579,1,"𐐻"],[66580,1,"𐐼"],[66581,1,"𐐽"],[66582,1,"𐐾"],[66583,1,"𐐿"],[66584,1,"𐑀"],[66585,1,"𐑁"],[66586,1,"𐑂"],[66587,1,"𐑃"],[66588,1,"𐑄"],[66589,1,"𐑅"],[66590,1,"𐑆"],[66591,1,"𐑇"],[66592,1,"𐑈"],[66593,1,"𐑉"],[66594,1,"𐑊"],[66595,1,"𐑋"],[66596,1,"𐑌"],[66597,1,"𐑍"],[66598,1,"𐑎"],[66599,1,"𐑏"],[[66600,66637],2],[[66638,66717],2],[[66718,66719],3],[[66720,66729],2],[[66730,66735],3],[66736,1,"𐓘"],[66737,1,"𐓙"],[66738,1,"𐓚"],[66739,1,"𐓛"],[66740,1,"𐓜"],[66741,1,"𐓝"],[66742,1,"𐓞"],[66743,1,"𐓟"],[66744,1,"𐓠"],[66745,1,"𐓡"],[66746,1,"𐓢"],[66747,1,"𐓣"],[66748,1,"𐓤"],[66749,1,"𐓥"],[66750,1,"𐓦"],[66751,1,"𐓧"],[66752,1,"𐓨"],[66753,1,"𐓩"],[66754,1,"𐓪"],[66755,1,"𐓫"],[66756,1,"𐓬"],[66757,1,"𐓭"],[66758,1,"𐓮"],[66759,1,"𐓯"],[66760,1,"𐓰"],[66761,1,"𐓱"],[66762,1,"𐓲"],[66763,1,"𐓳"],[66764,1,"𐓴"],[66765,1,"𐓵"],[66766,1,"𐓶"],[66767,1,"𐓷"],[66768,1,"𐓸"],[66769,1,"𐓹"],[66770,1,"𐓺"],[66771,1,"𐓻"],[[66772,66775],3],[[66776,66811],2],[[66812,66815],3],[[66816,66855],2],[[66856,66863],3],[[66864,66915],2],[[66916,66926],3],[66927,2],[66928,1,"𐖗"],[66929,1,"𐖘"],[66930,1,"𐖙"],[66931,1,"𐖚"],[66932,1,"𐖛"],[66933,1,"𐖜"],[66934,1,"𐖝"],[66935,1,"𐖞"],[66936,1,"𐖟"],[66937,1,"𐖠"],[66938,1,"𐖡"],[66939,3],[66940,1,"𐖣"],[66941,1,"𐖤"],[66942,1,"𐖥"],[66943,1,"𐖦"],[66944,1,"𐖧"],[66945,1,"𐖨"],[66946,1,"𐖩"],[66947,1,"𐖪"],[66948,1,"𐖫"],[66949,1,"𐖬"],[66950,1,"𐖭"],[66951,1,"𐖮"],[66952,1,"𐖯"],[66953,1,"𐖰"],[66954,1,"𐖱"],[66955,3],[66956,1,"𐖳"],[66957,1,"𐖴"],[66958,1,"𐖵"],[66959,1,"𐖶"],[66960,1,"𐖷"],[66961,1,"𐖸"],[66962,1,"𐖹"],[66963,3],[66964,1,"𐖻"],[66965,1,"𐖼"],[66966,3],[[66967,66977],2],[66978,3],[[66979,66993],2],[66994,3],[[66995,67001],2],[67002,3],[[67003,67004],2],[[67005,67071],3],[[67072,67382],2],[[67383,67391],3],[[67392,67413],2],[[67414,67423],3],[[67424,67431],2],[[67432,67455],3],[67456,2],[67457,1,"ː"],[67458,1,"ˑ"],[67459,1,"æ"],[67460,1,"ʙ"],[67461,1,"ɓ"],[67462,3],[67463,1,"ʣ"],[67464,1,"ꭦ"],[67465,1,"ʥ"],[67466,1,"ʤ"],[67467,1,"ɖ"],[67468,1,"ɗ"],[67469,1,"ᶑ"],[67470,1,"ɘ"],[67471,1,"ɞ"],[67472,1,"ʩ"],[67473,1,"ɤ"],[67474,1,"ɢ"],[67475,1,"ɠ"],[67476,1,"ʛ"],[67477,1,"ħ"],[67478,1,"ʜ"],[67479,1,"ɧ"],[67480,1,"ʄ"],[67481,1,"ʪ"],[67482,1,"ʫ"],[67483,1,"ɬ"],[67484,1,"𝼄"],[67485,1,"ꞎ"],[67486,1,"ɮ"],[67487,1,"𝼅"],[67488,1,"ʎ"],[67489,1,"𝼆"],[67490,1,"ø"],[67491,1,"ɶ"],[67492,1,"ɷ"],[67493,1,"q"],[67494,1,"ɺ"],[67495,1,"𝼈"],[67496,1,"ɽ"],[67497,1,"ɾ"],[67498,1,"ʀ"],[67499,1,"ʨ"],[67500,1,"ʦ"],[67501,1,"ꭧ"],[67502,1,"ʧ"],[67503,1,"ʈ"],[67504,1,"ⱱ"],[67505,3],[67506,1,"ʏ"],[67507,1,"ʡ"],[67508,1,"ʢ"],[67509,1,"ʘ"],[67510,1,"ǀ"],[67511,1,"ǁ"],[67512,1,"ǂ"],[67513,1,"𝼊"],[67514,1,"𝼞"],[[67515,67583],3],[[67584,67589],2],[[67590,67591],3],[67592,2],[67593,3],[[67594,67637],2],[67638,3],[[67639,67640],2],[[67641,67643],3],[67644,2],[[67645,67646],3],[67647,2],[[67648,67669],2],[67670,3],[[67671,67679],2],[[67680,67702],2],[[67703,67711],2],[[67712,67742],2],[[67743,67750],3],[[67751,67759],2],[[67760,67807],3],[[67808,67826],2],[67827,3],[[67828,67829],2],[[67830,67834],3],[[67835,67839],2],[[67840,67861],2],[[67862,67865],2],[[67866,67867],2],[[67868,67870],3],[67871,2],[[67872,67897],2],[[67898,67902],3],[67903,2],[[67904,67967],3],[[67968,68023],2],[[68024,68027],3],[[68028,68029],2],[[68030,68031],2],[[68032,68047],2],[[68048,68049],3],[[68050,68095],2],[[68096,68099],2],[68100,3],[[68101,68102],2],[[68103,68107],3],[[68108,68115],2],[68116,3],[[68117,68119],2],[68120,3],[[68121,68147],2],[[68148,68149],2],[[68150,68151],3],[[68152,68154],2],[[68155,68158],3],[68159,2],[[68160,68167],2],[68168,2],[[68169,68175],3],[[68176,68184],2],[[68185,68191],3],[[68192,68220],2],[[68221,68223],2],[[68224,68252],2],[[68253,68255],2],[[68256,68287],3],[[68288,68295],2],[68296,2],[[68297,68326],2],[[68327,68330],3],[[68331,68342],2],[[68343,68351],3],[[68352,68405],2],[[68406,68408],3],[[68409,68415],2],[[68416,68437],2],[[68438,68439],3],[[68440,68447],2],[[68448,68466],2],[[68467,68471],3],[[68472,68479],2],[[68480,68497],2],[[68498,68504],3],[[68505,68508],2],[[68509,68520],3],[[68521,68527],2],[[68528,68607],3],[[68608,68680],2],[[68681,68735],3],[68736,1,"𐳀"],[68737,1,"𐳁"],[68738,1,"𐳂"],[68739,1,"𐳃"],[68740,1,"𐳄"],[68741,1,"𐳅"],[68742,1,"𐳆"],[68743,1,"𐳇"],[68744,1,"𐳈"],[68745,1,"𐳉"],[68746,1,"𐳊"],[68747,1,"𐳋"],[68748,1,"𐳌"],[68749,1,"𐳍"],[68750,1,"𐳎"],[68751,1,"𐳏"],[68752,1,"𐳐"],[68753,1,"𐳑"],[68754,1,"𐳒"],[68755,1,"𐳓"],[68756,1,"𐳔"],[68757,1,"𐳕"],[68758,1,"𐳖"],[68759,1,"𐳗"],[68760,1,"𐳘"],[68761,1,"𐳙"],[68762,1,"𐳚"],[68763,1,"𐳛"],[68764,1,"𐳜"],[68765,1,"𐳝"],[68766,1,"𐳞"],[68767,1,"𐳟"],[68768,1,"𐳠"],[68769,1,"𐳡"],[68770,1,"𐳢"],[68771,1,"𐳣"],[68772,1,"𐳤"],[68773,1,"𐳥"],[68774,1,"𐳦"],[68775,1,"𐳧"],[68776,1,"𐳨"],[68777,1,"𐳩"],[68778,1,"𐳪"],[68779,1,"𐳫"],[68780,1,"𐳬"],[68781,1,"𐳭"],[68782,1,"𐳮"],[68783,1,"𐳯"],[68784,1,"𐳰"],[68785,1,"𐳱"],[68786,1,"𐳲"],[[68787,68799],3],[[68800,68850],2],[[68851,68857],3],[[68858,68863],2],[[68864,68903],2],[[68904,68911],3],[[68912,68921],2],[[68922,69215],3],[[69216,69246],2],[69247,3],[[69248,69289],2],[69290,3],[[69291,69292],2],[69293,2],[[69294,69295],3],[[69296,69297],2],[[69298,69372],3],[[69373,69375],2],[[69376,69404],2],[[69405,69414],2],[69415,2],[[69416,69423],3],[[69424,69456],2],[[69457,69465],2],[[69466,69487],3],[[69488,69509],2],[[69510,69513],2],[[69514,69551],3],[[69552,69572],2],[[69573,69579],2],[[69580,69599],3],[[69600,69622],2],[[69623,69631],3],[[69632,69702],2],[[69703,69709],2],[[69710,69713],3],[[69714,69733],2],[[69734,69743],2],[[69744,69749],2],[[69750,69758],3],[69759,2],[[69760,69818],2],[[69819,69820],2],[69821,3],[[69822,69825],2],[69826,2],[[69827,69836],3],[69837,3],[[69838,69839],3],[[69840,69864],2],[[69865,69871],3],[[69872,69881],2],[[69882,69887],3],[[69888,69940],2],[69941,3],[[69942,69951],2],[[69952,69955],2],[[69956,69958],2],[69959,2],[[69960,69967],3],[[69968,70003],2],[[70004,70005],2],[70006,2],[[70007,70015],3],[[70016,70084],2],[[70085,70088],2],[[70089,70092],2],[70093,2],[[70094,70095],2],[[70096,70105],2],[70106,2],[70107,2],[70108,2],[[70109,70111],2],[70112,3],[[70113,70132],2],[[70133,70143],3],[[70144,70161],2],[70162,3],[[70163,70199],2],[[70200,70205],2],[70206,2],[[70207,70209],2],[[70210,70271],3],[[70272,70278],2],[70279,3],[70280,2],[70281,3],[[70282,70285],2],[70286,3],[[70287,70301],2],[70302,3],[[70303,70312],2],[70313,2],[[70314,70319],3],[[70320,70378],2],[[70379,70383],3],[[70384,70393],2],[[70394,70399],3],[70400,2],[[70401,70403],2],[70404,3],[[70405,70412],2],[[70413,70414],3],[[70415,70416],2],[[70417,70418],3],[[70419,70440],2],[70441,3],[[70442,70448],2],[70449,3],[[70450,70451],2],[70452,3],[[70453,70457],2],[70458,3],[70459,2],[[70460,70468],2],[[70469,70470],3],[[70471,70472],2],[[70473,70474],3],[[70475,70477],2],[[70478,70479],3],[70480,2],[[70481,70486],3],[70487,2],[[70488,70492],3],[[70493,70499],2],[[70500,70501],3],[[70502,70508],2],[[70509,70511],3],[[70512,70516],2],[[70517,70655],3],[[70656,70730],2],[[70731,70735],2],[[70736,70745],2],[70746,2],[70747,2],[70748,3],[70749,2],[70750,2],[70751,2],[[70752,70753],2],[[70754,70783],3],[[70784,70853],2],[70854,2],[70855,2],[[70856,70863],3],[[70864,70873],2],[[70874,71039],3],[[71040,71093],2],[[71094,71095],3],[[71096,71104],2],[[71105,71113],2],[[71114,71127],2],[[71128,71133],2],[[71134,71167],3],[[71168,71232],2],[[71233,71235],2],[71236,2],[[71237,71247],3],[[71248,71257],2],[[71258,71263],3],[[71264,71276],2],[[71277,71295],3],[[71296,71351],2],[71352,2],[71353,2],[[71354,71359],3],[[71360,71369],2],[[71370,71423],3],[[71424,71449],2],[71450,2],[[71451,71452],3],[[71453,71467],2],[[71468,71471],3],[[71472,71481],2],[[71482,71487],2],[[71488,71494],2],[[71495,71679],3],[[71680,71738],2],[71739,2],[[71740,71839],3],[71840,1,"𑣀"],[71841,1,"𑣁"],[71842,1,"𑣂"],[71843,1,"𑣃"],[71844,1,"𑣄"],[71845,1,"𑣅"],[71846,1,"𑣆"],[71847,1,"𑣇"],[71848,1,"𑣈"],[71849,1,"𑣉"],[71850,1,"𑣊"],[71851,1,"𑣋"],[71852,1,"𑣌"],[71853,1,"𑣍"],[71854,1,"𑣎"],[71855,1,"𑣏"],[71856,1,"𑣐"],[71857,1,"𑣑"],[71858,1,"𑣒"],[71859,1,"𑣓"],[71860,1,"𑣔"],[71861,1,"𑣕"],[71862,1,"𑣖"],[71863,1,"𑣗"],[71864,1,"𑣘"],[71865,1,"𑣙"],[71866,1,"𑣚"],[71867,1,"𑣛"],[71868,1,"𑣜"],[71869,1,"𑣝"],[71870,1,"𑣞"],[71871,1,"𑣟"],[[71872,71913],2],[[71914,71922],2],[[71923,71934],3],[71935,2],[[71936,71942],2],[[71943,71944],3],[71945,2],[[71946,71947],3],[[71948,71955],2],[71956,3],[[71957,71958],2],[71959,3],[[71960,71989],2],[71990,3],[[71991,71992],2],[[71993,71994],3],[[71995,72003],2],[[72004,72006],2],[[72007,72015],3],[[72016,72025],2],[[72026,72095],3],[[72096,72103],2],[[72104,72105],3],[[72106,72151],2],[[72152,72153],3],[[72154,72161],2],[72162,2],[[72163,72164],2],[[72165,72191],3],[[72192,72254],2],[[72255,72262],2],[72263,2],[[72264,72271],3],[[72272,72323],2],[[72324,72325],2],[[72326,72345],2],[[72346,72348],2],[72349,2],[[72350,72354],2],[[72355,72367],3],[[72368,72383],2],[[72384,72440],2],[[72441,72447],3],[[72448,72457],2],[[72458,72703],3],[[72704,72712],2],[72713,3],[[72714,72758],2],[72759,3],[[72760,72768],2],[[72769,72773],2],[[72774,72783],3],[[72784,72793],2],[[72794,72812],2],[[72813,72815],3],[[72816,72817],2],[[72818,72847],2],[[72848,72849],3],[[72850,72871],2],[72872,3],[[72873,72886],2],[[72887,72959],3],[[72960,72966],2],[72967,3],[[72968,72969],2],[72970,3],[[72971,73014],2],[[73015,73017],3],[73018,2],[73019,3],[[73020,73021],2],[73022,3],[[73023,73031],2],[[73032,73039],3],[[73040,73049],2],[[73050,73055],3],[[73056,73061],2],[73062,3],[[73063,73064],2],[73065,3],[[73066,73102],2],[73103,3],[[73104,73105],2],[73106,3],[[73107,73112],2],[[73113,73119],3],[[73120,73129],2],[[73130,73439],3],[[73440,73462],2],[[73463,73464],2],[[73465,73471],3],[[73472,73488],2],[73489,3],[[73490,73530],2],[[73531,73533],3],[[73534,73538],2],[[73539,73551],2],[[73552,73561],2],[[73562,73647],3],[73648,2],[[73649,73663],3],[[73664,73713],2],[[73714,73726],3],[73727,2],[[73728,74606],2],[[74607,74648],2],[74649,2],[[74650,74751],3],[[74752,74850],2],[[74851,74862],2],[74863,3],[[74864,74867],2],[74868,2],[[74869,74879],3],[[74880,75075],2],[[75076,77711],3],[[77712,77808],2],[[77809,77810],2],[[77811,77823],3],[[77824,78894],2],[78895,2],[[78896,78904],3],[[78905,78911],3],[[78912,78933],2],[[78934,82943],3],[[82944,83526],2],[[83527,92159],3],[[92160,92728],2],[[92729,92735],3],[[92736,92766],2],[92767,3],[[92768,92777],2],[[92778,92781],3],[[92782,92783],2],[[92784,92862],2],[92863,3],[[92864,92873],2],[[92874,92879],3],[[92880,92909],2],[[92910,92911],3],[[92912,92916],2],[92917,2],[[92918,92927],3],[[92928,92982],2],[[92983,92991],2],[[92992,92995],2],[[92996,92997],2],[[92998,93007],3],[[93008,93017],2],[93018,3],[[93019,93025],2],[93026,3],[[93027,93047],2],[[93048,93052],3],[[93053,93071],2],[[93072,93759],3],[93760,1,"𖹠"],[93761,1,"𖹡"],[93762,1,"𖹢"],[93763,1,"𖹣"],[93764,1,"𖹤"],[93765,1,"𖹥"],[93766,1,"𖹦"],[93767,1,"𖹧"],[93768,1,"𖹨"],[93769,1,"𖹩"],[93770,1,"𖹪"],[93771,1,"𖹫"],[93772,1,"𖹬"],[93773,1,"𖹭"],[93774,1,"𖹮"],[93775,1,"𖹯"],[93776,1,"𖹰"],[93777,1,"𖹱"],[93778,1,"𖹲"],[93779,1,"𖹳"],[93780,1,"𖹴"],[93781,1,"𖹵"],[93782,1,"𖹶"],[93783,1,"𖹷"],[93784,1,"𖹸"],[93785,1,"𖹹"],[93786,1,"𖹺"],[93787,1,"𖹻"],[93788,1,"𖹼"],[93789,1,"𖹽"],[93790,1,"𖹾"],[93791,1,"𖹿"],[[93792,93823],2],[[93824,93850],2],[[93851,93951],3],[[93952,94020],2],[[94021,94026],2],[[94027,94030],3],[94031,2],[[94032,94078],2],[[94079,94087],2],[[94088,94094],3],[[94095,94111],2],[[94112,94175],3],[94176,2],[94177,2],[94178,2],[94179,2],[94180,2],[[94181,94191],3],[[94192,94193],2],[[94194,94207],3],[[94208,100332],2],[[100333,100337],2],[[100338,100343],2],[[100344,100351],3],[[100352,101106],2],[[101107,101589],2],[[101590,101631],3],[[101632,101640],2],[[101641,110575],3],[[110576,110579],2],[110580,3],[[110581,110587],2],[110588,3],[[110589,110590],2],[110591,3],[[110592,110593],2],[[110594,110878],2],[[110879,110882],2],[[110883,110897],3],[110898,2],[[110899,110927],3],[[110928,110930],2],[[110931,110932],3],[110933,2],[[110934,110947],3],[[110948,110951],2],[[110952,110959],3],[[110960,111355],2],[[111356,113663],3],[[113664,113770],2],[[113771,113775],3],[[113776,113788],2],[[113789,113791],3],[[113792,113800],2],[[113801,113807],3],[[113808,113817],2],[[113818,113819],3],[113820,2],[[113821,113822],2],[113823,2],[[113824,113827],7],[[113828,118527],3],[[118528,118573],2],[[118574,118575],3],[[118576,118598],2],[[118599,118607],3],[[118608,118723],2],[[118724,118783],3],[[118784,119029],2],[[119030,119039],3],[[119040,119078],2],[[119079,119080],3],[119081,2],[[119082,119133],2],[119134,1,"𝅗𝅥"],[119135,1,"𝅘𝅥"],[119136,1,"𝅘𝅥𝅮"],[119137,1,"𝅘𝅥𝅯"],[119138,1,"𝅘𝅥𝅰"],[119139,1,"𝅘𝅥𝅱"],[119140,1,"𝅘𝅥𝅲"],[[119141,119154],2],[[119155,119162],3],[[119163,119226],2],[119227,1,"𝆹𝅥"],[119228,1,"𝆺𝅥"],[119229,1,"𝆹𝅥𝅮"],[119230,1,"𝆺𝅥𝅮"],[119231,1,"𝆹𝅥𝅯"],[119232,1,"𝆺𝅥𝅯"],[[119233,119261],2],[[119262,119272],2],[[119273,119274],2],[[119275,119295],3],[[119296,119365],2],[[119366,119487],3],[[119488,119507],2],[[119508,119519],3],[[119520,119539],2],[[119540,119551],3],[[119552,119638],2],[[119639,119647],3],[[119648,119665],2],[[119666,119672],2],[[119673,119807],3],[119808,1,"a"],[119809,1,"b"],[119810,1,"c"],[119811,1,"d"],[119812,1,"e"],[119813,1,"f"],[119814,1,"g"],[119815,1,"h"],[119816,1,"i"],[119817,1,"j"],[119818,1,"k"],[119819,1,"l"],[119820,1,"m"],[119821,1,"n"],[119822,1,"o"],[119823,1,"p"],[119824,1,"q"],[119825,1,"r"],[119826,1,"s"],[119827,1,"t"],[119828,1,"u"],[119829,1,"v"],[119830,1,"w"],[119831,1,"x"],[119832,1,"y"],[119833,1,"z"],[119834,1,"a"],[119835,1,"b"],[119836,1,"c"],[119837,1,"d"],[119838,1,"e"],[119839,1,"f"],[119840,1,"g"],[119841,1,"h"],[119842,1,"i"],[119843,1,"j"],[119844,1,"k"],[119845,1,"l"],[119846,1,"m"],[119847,1,"n"],[119848,1,"o"],[119849,1,"p"],[119850,1,"q"],[119851,1,"r"],[119852,1,"s"],[119853,1,"t"],[119854,1,"u"],[119855,1,"v"],[119856,1,"w"],[119857,1,"x"],[119858,1,"y"],[119859,1,"z"],[119860,1,"a"],[119861,1,"b"],[119862,1,"c"],[119863,1,"d"],[119864,1,"e"],[119865,1,"f"],[119866,1,"g"],[119867,1,"h"],[119868,1,"i"],[119869,1,"j"],[119870,1,"k"],[119871,1,"l"],[119872,1,"m"],[119873,1,"n"],[119874,1,"o"],[119875,1,"p"],[119876,1,"q"],[119877,1,"r"],[119878,1,"s"],[119879,1,"t"],[119880,1,"u"],[119881,1,"v"],[119882,1,"w"],[119883,1,"x"],[119884,1,"y"],[119885,1,"z"],[119886,1,"a"],[119887,1,"b"],[119888,1,"c"],[119889,1,"d"],[119890,1,"e"],[119891,1,"f"],[119892,1,"g"],[119893,3],[119894,1,"i"],[119895,1,"j"],[119896,1,"k"],[119897,1,"l"],[119898,1,"m"],[119899,1,"n"],[119900,1,"o"],[119901,1,"p"],[119902,1,"q"],[119903,1,"r"],[119904,1,"s"],[119905,1,"t"],[119906,1,"u"],[119907,1,"v"],[119908,1,"w"],[119909,1,"x"],[119910,1,"y"],[119911,1,"z"],[119912,1,"a"],[119913,1,"b"],[119914,1,"c"],[119915,1,"d"],[119916,1,"e"],[119917,1,"f"],[119918,1,"g"],[119919,1,"h"],[119920,1,"i"],[119921,1,"j"],[119922,1,"k"],[119923,1,"l"],[119924,1,"m"],[119925,1,"n"],[119926,1,"o"],[119927,1,"p"],[119928,1,"q"],[119929,1,"r"],[119930,1,"s"],[119931,1,"t"],[119932,1,"u"],[119933,1,"v"],[119934,1,"w"],[119935,1,"x"],[119936,1,"y"],[119937,1,"z"],[119938,1,"a"],[119939,1,"b"],[119940,1,"c"],[119941,1,"d"],[119942,1,"e"],[119943,1,"f"],[119944,1,"g"],[119945,1,"h"],[119946,1,"i"],[119947,1,"j"],[119948,1,"k"],[119949,1,"l"],[119950,1,"m"],[119951,1,"n"],[119952,1,"o"],[119953,1,"p"],[119954,1,"q"],[119955,1,"r"],[119956,1,"s"],[119957,1,"t"],[119958,1,"u"],[119959,1,"v"],[119960,1,"w"],[119961,1,"x"],[119962,1,"y"],[119963,1,"z"],[119964,1,"a"],[119965,3],[119966,1,"c"],[119967,1,"d"],[[119968,119969],3],[119970,1,"g"],[[119971,119972],3],[119973,1,"j"],[119974,1,"k"],[[119975,119976],3],[119977,1,"n"],[119978,1,"o"],[119979,1,"p"],[119980,1,"q"],[119981,3],[119982,1,"s"],[119983,1,"t"],[119984,1,"u"],[119985,1,"v"],[119986,1,"w"],[119987,1,"x"],[119988,1,"y"],[119989,1,"z"],[119990,1,"a"],[119991,1,"b"],[119992,1,"c"],[119993,1,"d"],[119994,3],[119995,1,"f"],[119996,3],[119997,1,"h"],[119998,1,"i"],[119999,1,"j"],[120000,1,"k"],[120001,1,"l"],[120002,1,"m"],[120003,1,"n"],[120004,3],[120005,1,"p"],[120006,1,"q"],[120007,1,"r"],[120008,1,"s"],[120009,1,"t"],[120010,1,"u"],[120011,1,"v"],[120012,1,"w"],[120013,1,"x"],[120014,1,"y"],[120015,1,"z"],[120016,1,"a"],[120017,1,"b"],[120018,1,"c"],[120019,1,"d"],[120020,1,"e"],[120021,1,"f"],[120022,1,"g"],[120023,1,"h"],[120024,1,"i"],[120025,1,"j"],[120026,1,"k"],[120027,1,"l"],[120028,1,"m"],[120029,1,"n"],[120030,1,"o"],[120031,1,"p"],[120032,1,"q"],[120033,1,"r"],[120034,1,"s"],[120035,1,"t"],[120036,1,"u"],[120037,1,"v"],[120038,1,"w"],[120039,1,"x"],[120040,1,"y"],[120041,1,"z"],[120042,1,"a"],[120043,1,"b"],[120044,1,"c"],[120045,1,"d"],[120046,1,"e"],[120047,1,"f"],[120048,1,"g"],[120049,1,"h"],[120050,1,"i"],[120051,1,"j"],[120052,1,"k"],[120053,1,"l"],[120054,1,"m"],[120055,1,"n"],[120056,1,"o"],[120057,1,"p"],[120058,1,"q"],[120059,1,"r"],[120060,1,"s"],[120061,1,"t"],[120062,1,"u"],[120063,1,"v"],[120064,1,"w"],[120065,1,"x"],[120066,1,"y"],[120067,1,"z"],[120068,1,"a"],[120069,1,"b"],[120070,3],[120071,1,"d"],[120072,1,"e"],[120073,1,"f"],[120074,1,"g"],[[120075,120076],3],[120077,1,"j"],[120078,1,"k"],[120079,1,"l"],[120080,1,"m"],[120081,1,"n"],[120082,1,"o"],[120083,1,"p"],[120084,1,"q"],[120085,3],[120086,1,"s"],[120087,1,"t"],[120088,1,"u"],[120089,1,"v"],[120090,1,"w"],[120091,1,"x"],[120092,1,"y"],[120093,3],[120094,1,"a"],[120095,1,"b"],[120096,1,"c"],[120097,1,"d"],[120098,1,"e"],[120099,1,"f"],[120100,1,"g"],[120101,1,"h"],[120102,1,"i"],[120103,1,"j"],[120104,1,"k"],[120105,1,"l"],[120106,1,"m"],[120107,1,"n"],[120108,1,"o"],[120109,1,"p"],[120110,1,"q"],[120111,1,"r"],[120112,1,"s"],[120113,1,"t"],[120114,1,"u"],[120115,1,"v"],[120116,1,"w"],[120117,1,"x"],[120118,1,"y"],[120119,1,"z"],[120120,1,"a"],[120121,1,"b"],[120122,3],[120123,1,"d"],[120124,1,"e"],[120125,1,"f"],[120126,1,"g"],[120127,3],[120128,1,"i"],[120129,1,"j"],[120130,1,"k"],[120131,1,"l"],[120132,1,"m"],[120133,3],[120134,1,"o"],[[120135,120137],3],[120138,1,"s"],[120139,1,"t"],[120140,1,"u"],[120141,1,"v"],[120142,1,"w"],[120143,1,"x"],[120144,1,"y"],[120145,3],[120146,1,"a"],[120147,1,"b"],[120148,1,"c"],[120149,1,"d"],[120150,1,"e"],[120151,1,"f"],[120152,1,"g"],[120153,1,"h"],[120154,1,"i"],[120155,1,"j"],[120156,1,"k"],[120157,1,"l"],[120158,1,"m"],[120159,1,"n"],[120160,1,"o"],[120161,1,"p"],[120162,1,"q"],[120163,1,"r"],[120164,1,"s"],[120165,1,"t"],[120166,1,"u"],[120167,1,"v"],[120168,1,"w"],[120169,1,"x"],[120170,1,"y"],[120171,1,"z"],[120172,1,"a"],[120173,1,"b"],[120174,1,"c"],[120175,1,"d"],[120176,1,"e"],[120177,1,"f"],[120178,1,"g"],[120179,1,"h"],[120180,1,"i"],[120181,1,"j"],[120182,1,"k"],[120183,1,"l"],[120184,1,"m"],[120185,1,"n"],[120186,1,"o"],[120187,1,"p"],[120188,1,"q"],[120189,1,"r"],[120190,1,"s"],[120191,1,"t"],[120192,1,"u"],[120193,1,"v"],[120194,1,"w"],[120195,1,"x"],[120196,1,"y"],[120197,1,"z"],[120198,1,"a"],[120199,1,"b"],[120200,1,"c"],[120201,1,"d"],[120202,1,"e"],[120203,1,"f"],[120204,1,"g"],[120205,1,"h"],[120206,1,"i"],[120207,1,"j"],[120208,1,"k"],[120209,1,"l"],[120210,1,"m"],[120211,1,"n"],[120212,1,"o"],[120213,1,"p"],[120214,1,"q"],[120215,1,"r"],[120216,1,"s"],[120217,1,"t"],[120218,1,"u"],[120219,1,"v"],[120220,1,"w"],[120221,1,"x"],[120222,1,"y"],[120223,1,"z"],[120224,1,"a"],[120225,1,"b"],[120226,1,"c"],[120227,1,"d"],[120228,1,"e"],[120229,1,"f"],[120230,1,"g"],[120231,1,"h"],[120232,1,"i"],[120233,1,"j"],[120234,1,"k"],[120235,1,"l"],[120236,1,"m"],[120237,1,"n"],[120238,1,"o"],[120239,1,"p"],[120240,1,"q"],[120241,1,"r"],[120242,1,"s"],[120243,1,"t"],[120244,1,"u"],[120245,1,"v"],[120246,1,"w"],[120247,1,"x"],[120248,1,"y"],[120249,1,"z"],[120250,1,"a"],[120251,1,"b"],[120252,1,"c"],[120253,1,"d"],[120254,1,"e"],[120255,1,"f"],[120256,1,"g"],[120257,1,"h"],[120258,1,"i"],[120259,1,"j"],[120260,1,"k"],[120261,1,"l"],[120262,1,"m"],[120263,1,"n"],[120264,1,"o"],[120265,1,"p"],[120266,1,"q"],[120267,1,"r"],[120268,1,"s"],[120269,1,"t"],[120270,1,"u"],[120271,1,"v"],[120272,1,"w"],[120273,1,"x"],[120274,1,"y"],[120275,1,"z"],[120276,1,"a"],[120277,1,"b"],[120278,1,"c"],[120279,1,"d"],[120280,1,"e"],[120281,1,"f"],[120282,1,"g"],[120283,1,"h"],[120284,1,"i"],[120285,1,"j"],[120286,1,"k"],[120287,1,"l"],[120288,1,"m"],[120289,1,"n"],[120290,1,"o"],[120291,1,"p"],[120292,1,"q"],[120293,1,"r"],[120294,1,"s"],[120295,1,"t"],[120296,1,"u"],[120297,1,"v"],[120298,1,"w"],[120299,1,"x"],[120300,1,"y"],[120301,1,"z"],[120302,1,"a"],[120303,1,"b"],[120304,1,"c"],[120305,1,"d"],[120306,1,"e"],[120307,1,"f"],[120308,1,"g"],[120309,1,"h"],[120310,1,"i"],[120311,1,"j"],[120312,1,"k"],[120313,1,"l"],[120314,1,"m"],[120315,1,"n"],[120316,1,"o"],[120317,1,"p"],[120318,1,"q"],[120319,1,"r"],[120320,1,"s"],[120321,1,"t"],[120322,1,"u"],[120323,1,"v"],[120324,1,"w"],[120325,1,"x"],[120326,1,"y"],[120327,1,"z"],[120328,1,"a"],[120329,1,"b"],[120330,1,"c"],[120331,1,"d"],[120332,1,"e"],[120333,1,"f"],[120334,1,"g"],[120335,1,"h"],[120336,1,"i"],[120337,1,"j"],[120338,1,"k"],[120339,1,"l"],[120340,1,"m"],[120341,1,"n"],[120342,1,"o"],[120343,1,"p"],[120344,1,"q"],[120345,1,"r"],[120346,1,"s"],[120347,1,"t"],[120348,1,"u"],[120349,1,"v"],[120350,1,"w"],[120351,1,"x"],[120352,1,"y"],[120353,1,"z"],[120354,1,"a"],[120355,1,"b"],[120356,1,"c"],[120357,1,"d"],[120358,1,"e"],[120359,1,"f"],[120360,1,"g"],[120361,1,"h"],[120362,1,"i"],[120363,1,"j"],[120364,1,"k"],[120365,1,"l"],[120366,1,"m"],[120367,1,"n"],[120368,1,"o"],[120369,1,"p"],[120370,1,"q"],[120371,1,"r"],[120372,1,"s"],[120373,1,"t"],[120374,1,"u"],[120375,1,"v"],[120376,1,"w"],[120377,1,"x"],[120378,1,"y"],[120379,1,"z"],[120380,1,"a"],[120381,1,"b"],[120382,1,"c"],[120383,1,"d"],[120384,1,"e"],[120385,1,"f"],[120386,1,"g"],[120387,1,"h"],[120388,1,"i"],[120389,1,"j"],[120390,1,"k"],[120391,1,"l"],[120392,1,"m"],[120393,1,"n"],[120394,1,"o"],[120395,1,"p"],[120396,1,"q"],[120397,1,"r"],[120398,1,"s"],[120399,1,"t"],[120400,1,"u"],[120401,1,"v"],[120402,1,"w"],[120403,1,"x"],[120404,1,"y"],[120405,1,"z"],[120406,1,"a"],[120407,1,"b"],[120408,1,"c"],[120409,1,"d"],[120410,1,"e"],[120411,1,"f"],[120412,1,"g"],[120413,1,"h"],[120414,1,"i"],[120415,1,"j"],[120416,1,"k"],[120417,1,"l"],[120418,1,"m"],[120419,1,"n"],[120420,1,"o"],[120421,1,"p"],[120422,1,"q"],[120423,1,"r"],[120424,1,"s"],[120425,1,"t"],[120426,1,"u"],[120427,1,"v"],[120428,1,"w"],[120429,1,"x"],[120430,1,"y"],[120431,1,"z"],[120432,1,"a"],[120433,1,"b"],[120434,1,"c"],[120435,1,"d"],[120436,1,"e"],[120437,1,"f"],[120438,1,"g"],[120439,1,"h"],[120440,1,"i"],[120441,1,"j"],[120442,1,"k"],[120443,1,"l"],[120444,1,"m"],[120445,1,"n"],[120446,1,"o"],[120447,1,"p"],[120448,1,"q"],[120449,1,"r"],[120450,1,"s"],[120451,1,"t"],[120452,1,"u"],[120453,1,"v"],[120454,1,"w"],[120455,1,"x"],[120456,1,"y"],[120457,1,"z"],[120458,1,"a"],[120459,1,"b"],[120460,1,"c"],[120461,1,"d"],[120462,1,"e"],[120463,1,"f"],[120464,1,"g"],[120465,1,"h"],[120466,1,"i"],[120467,1,"j"],[120468,1,"k"],[120469,1,"l"],[120470,1,"m"],[120471,1,"n"],[120472,1,"o"],[120473,1,"p"],[120474,1,"q"],[120475,1,"r"],[120476,1,"s"],[120477,1,"t"],[120478,1,"u"],[120479,1,"v"],[120480,1,"w"],[120481,1,"x"],[120482,1,"y"],[120483,1,"z"],[120484,1,"ı"],[120485,1,"ȷ"],[[120486,120487],3],[120488,1,"α"],[120489,1,"β"],[120490,1,"γ"],[120491,1,"δ"],[120492,1,"ε"],[120493,1,"ζ"],[120494,1,"η"],[120495,1,"θ"],[120496,1,"ι"],[120497,1,"κ"],[120498,1,"λ"],[120499,1,"μ"],[120500,1,"ν"],[120501,1,"ξ"],[120502,1,"ο"],[120503,1,"π"],[120504,1,"ρ"],[120505,1,"θ"],[120506,1,"σ"],[120507,1,"τ"],[120508,1,"υ"],[120509,1,"φ"],[120510,1,"χ"],[120511,1,"ψ"],[120512,1,"ω"],[120513,1,"∇"],[120514,1,"α"],[120515,1,"β"],[120516,1,"γ"],[120517,1,"δ"],[120518,1,"ε"],[120519,1,"ζ"],[120520,1,"η"],[120521,1,"θ"],[120522,1,"ι"],[120523,1,"κ"],[120524,1,"λ"],[120525,1,"μ"],[120526,1,"ν"],[120527,1,"ξ"],[120528,1,"ο"],[120529,1,"π"],[120530,1,"ρ"],[[120531,120532],1,"σ"],[120533,1,"τ"],[120534,1,"υ"],[120535,1,"φ"],[120536,1,"χ"],[120537,1,"ψ"],[120538,1,"ω"],[120539,1,"∂"],[120540,1,"ε"],[120541,1,"θ"],[120542,1,"κ"],[120543,1,"φ"],[120544,1,"ρ"],[120545,1,"π"],[120546,1,"α"],[120547,1,"β"],[120548,1,"γ"],[120549,1,"δ"],[120550,1,"ε"],[120551,1,"ζ"],[120552,1,"η"],[120553,1,"θ"],[120554,1,"ι"],[120555,1,"κ"],[120556,1,"λ"],[120557,1,"μ"],[120558,1,"ν"],[120559,1,"ξ"],[120560,1,"ο"],[120561,1,"π"],[120562,1,"ρ"],[120563,1,"θ"],[120564,1,"σ"],[120565,1,"τ"],[120566,1,"υ"],[120567,1,"φ"],[120568,1,"χ"],[120569,1,"ψ"],[120570,1,"ω"],[120571,1,"∇"],[120572,1,"α"],[120573,1,"β"],[120574,1,"γ"],[120575,1,"δ"],[120576,1,"ε"],[120577,1,"ζ"],[120578,1,"η"],[120579,1,"θ"],[120580,1,"ι"],[120581,1,"κ"],[120582,1,"λ"],[120583,1,"μ"],[120584,1,"ν"],[120585,1,"ξ"],[120586,1,"ο"],[120587,1,"π"],[120588,1,"ρ"],[[120589,120590],1,"σ"],[120591,1,"τ"],[120592,1,"υ"],[120593,1,"φ"],[120594,1,"χ"],[120595,1,"ψ"],[120596,1,"ω"],[120597,1,"∂"],[120598,1,"ε"],[120599,1,"θ"],[120600,1,"κ"],[120601,1,"φ"],[120602,1,"ρ"],[120603,1,"π"],[120604,1,"α"],[120605,1,"β"],[120606,1,"γ"],[120607,1,"δ"],[120608,1,"ε"],[120609,1,"ζ"],[120610,1,"η"],[120611,1,"θ"],[120612,1,"ι"],[120613,1,"κ"],[120614,1,"λ"],[120615,1,"μ"],[120616,1,"ν"],[120617,1,"ξ"],[120618,1,"ο"],[120619,1,"π"],[120620,1,"ρ"],[120621,1,"θ"],[120622,1,"σ"],[120623,1,"τ"],[120624,1,"υ"],[120625,1,"φ"],[120626,1,"χ"],[120627,1,"ψ"],[120628,1,"ω"],[120629,1,"∇"],[120630,1,"α"],[120631,1,"β"],[120632,1,"γ"],[120633,1,"δ"],[120634,1,"ε"],[120635,1,"ζ"],[120636,1,"η"],[120637,1,"θ"],[120638,1,"ι"],[120639,1,"κ"],[120640,1,"λ"],[120641,1,"μ"],[120642,1,"ν"],[120643,1,"ξ"],[120644,1,"ο"],[120645,1,"π"],[120646,1,"ρ"],[[120647,120648],1,"σ"],[120649,1,"τ"],[120650,1,"υ"],[120651,1,"φ"],[120652,1,"χ"],[120653,1,"ψ"],[120654,1,"ω"],[120655,1,"∂"],[120656,1,"ε"],[120657,1,"θ"],[120658,1,"κ"],[120659,1,"φ"],[120660,1,"ρ"],[120661,1,"π"],[120662,1,"α"],[120663,1,"β"],[120664,1,"γ"],[120665,1,"δ"],[120666,1,"ε"],[120667,1,"ζ"],[120668,1,"η"],[120669,1,"θ"],[120670,1,"ι"],[120671,1,"κ"],[120672,1,"λ"],[120673,1,"μ"],[120674,1,"ν"],[120675,1,"ξ"],[120676,1,"ο"],[120677,1,"π"],[120678,1,"ρ"],[120679,1,"θ"],[120680,1,"σ"],[120681,1,"τ"],[120682,1,"υ"],[120683,1,"φ"],[120684,1,"χ"],[120685,1,"ψ"],[120686,1,"ω"],[120687,1,"∇"],[120688,1,"α"],[120689,1,"β"],[120690,1,"γ"],[120691,1,"δ"],[120692,1,"ε"],[120693,1,"ζ"],[120694,1,"η"],[120695,1,"θ"],[120696,1,"ι"],[120697,1,"κ"],[120698,1,"λ"],[120699,1,"μ"],[120700,1,"ν"],[120701,1,"ξ"],[120702,1,"ο"],[120703,1,"π"],[120704,1,"ρ"],[[120705,120706],1,"σ"],[120707,1,"τ"],[120708,1,"υ"],[120709,1,"φ"],[120710,1,"χ"],[120711,1,"ψ"],[120712,1,"ω"],[120713,1,"∂"],[120714,1,"ε"],[120715,1,"θ"],[120716,1,"κ"],[120717,1,"φ"],[120718,1,"ρ"],[120719,1,"π"],[120720,1,"α"],[120721,1,"β"],[120722,1,"γ"],[120723,1,"δ"],[120724,1,"ε"],[120725,1,"ζ"],[120726,1,"η"],[120727,1,"θ"],[120728,1,"ι"],[120729,1,"κ"],[120730,1,"λ"],[120731,1,"μ"],[120732,1,"ν"],[120733,1,"ξ"],[120734,1,"ο"],[120735,1,"π"],[120736,1,"ρ"],[120737,1,"θ"],[120738,1,"σ"],[120739,1,"τ"],[120740,1,"υ"],[120741,1,"φ"],[120742,1,"χ"],[120743,1,"ψ"],[120744,1,"ω"],[120745,1,"∇"],[120746,1,"α"],[120747,1,"β"],[120748,1,"γ"],[120749,1,"δ"],[120750,1,"ε"],[120751,1,"ζ"],[120752,1,"η"],[120753,1,"θ"],[120754,1,"ι"],[120755,1,"κ"],[120756,1,"λ"],[120757,1,"μ"],[120758,1,"ν"],[120759,1,"ξ"],[120760,1,"ο"],[120761,1,"π"],[120762,1,"ρ"],[[120763,120764],1,"σ"],[120765,1,"τ"],[120766,1,"υ"],[120767,1,"φ"],[120768,1,"χ"],[120769,1,"ψ"],[120770,1,"ω"],[120771,1,"∂"],[120772,1,"ε"],[120773,1,"θ"],[120774,1,"κ"],[120775,1,"φ"],[120776,1,"ρ"],[120777,1,"π"],[[120778,120779],1,"ϝ"],[[120780,120781],3],[120782,1,"0"],[120783,1,"1"],[120784,1,"2"],[120785,1,"3"],[120786,1,"4"],[120787,1,"5"],[120788,1,"6"],[120789,1,"7"],[120790,1,"8"],[120791,1,"9"],[120792,1,"0"],[120793,1,"1"],[120794,1,"2"],[120795,1,"3"],[120796,1,"4"],[120797,1,"5"],[120798,1,"6"],[120799,1,"7"],[120800,1,"8"],[120801,1,"9"],[120802,1,"0"],[120803,1,"1"],[120804,1,"2"],[120805,1,"3"],[120806,1,"4"],[120807,1,"5"],[120808,1,"6"],[120809,1,"7"],[120810,1,"8"],[120811,1,"9"],[120812,1,"0"],[120813,1,"1"],[120814,1,"2"],[120815,1,"3"],[120816,1,"4"],[120817,1,"5"],[120818,1,"6"],[120819,1,"7"],[120820,1,"8"],[120821,1,"9"],[120822,1,"0"],[120823,1,"1"],[120824,1,"2"],[120825,1,"3"],[120826,1,"4"],[120827,1,"5"],[120828,1,"6"],[120829,1,"7"],[120830,1,"8"],[120831,1,"9"],[[120832,121343],2],[[121344,121398],2],[[121399,121402],2],[[121403,121452],2],[[121453,121460],2],[121461,2],[[121462,121475],2],[121476,2],[[121477,121483],2],[[121484,121498],3],[[121499,121503],2],[121504,3],[[121505,121519],2],[[121520,122623],3],[[122624,122654],2],[[122655,122660],3],[[122661,122666],2],[[122667,122879],3],[[122880,122886],2],[122887,3],[[122888,122904],2],[[122905,122906],3],[[122907,122913],2],[122914,3],[[122915,122916],2],[122917,3],[[122918,122922],2],[[122923,122927],3],[122928,1,"а"],[122929,1,"б"],[122930,1,"в"],[122931,1,"г"],[122932,1,"д"],[122933,1,"е"],[122934,1,"ж"],[122935,1,"з"],[122936,1,"и"],[122937,1,"к"],[122938,1,"л"],[122939,1,"м"],[122940,1,"о"],[122941,1,"п"],[122942,1,"р"],[122943,1,"с"],[122944,1,"т"],[122945,1,"у"],[122946,1,"ф"],[122947,1,"х"],[122948,1,"ц"],[122949,1,"ч"],[122950,1,"ш"],[122951,1,"ы"],[122952,1,"э"],[122953,1,"ю"],[122954,1,"ꚉ"],[122955,1,"ә"],[122956,1,"і"],[122957,1,"ј"],[122958,1,"ө"],[122959,1,"ү"],[122960,1,"ӏ"],[122961,1,"а"],[122962,1,"б"],[122963,1,"в"],[122964,1,"г"],[122965,1,"д"],[122966,1,"е"],[122967,1,"ж"],[122968,1,"з"],[122969,1,"и"],[122970,1,"к"],[122971,1,"л"],[122972,1,"о"],[122973,1,"п"],[122974,1,"с"],[122975,1,"у"],[122976,1,"ф"],[122977,1,"х"],[122978,1,"ц"],[122979,1,"ч"],[122980,1,"ш"],[122981,1,"ъ"],[122982,1,"ы"],[122983,1,"ґ"],[122984,1,"і"],[122985,1,"ѕ"],[122986,1,"џ"],[122987,1,"ҫ"],[122988,1,"ꙑ"],[122989,1,"ұ"],[[122990,123022],3],[123023,2],[[123024,123135],3],[[123136,123180],2],[[123181,123183],3],[[123184,123197],2],[[123198,123199],3],[[123200,123209],2],[[123210,123213],3],[123214,2],[123215,2],[[123216,123535],3],[[123536,123566],2],[[123567,123583],3],[[123584,123641],2],[[123642,123646],3],[123647,2],[[123648,124111],3],[[124112,124153],2],[[124154,124895],3],[[124896,124902],2],[124903,3],[[124904,124907],2],[124908,3],[[124909,124910],2],[124911,3],[[124912,124926],2],[124927,3],[[124928,125124],2],[[125125,125126],3],[[125127,125135],2],[[125136,125142],2],[[125143,125183],3],[125184,1,"𞤢"],[125185,1,"𞤣"],[125186,1,"𞤤"],[125187,1,"𞤥"],[125188,1,"𞤦"],[125189,1,"𞤧"],[125190,1,"𞤨"],[125191,1,"𞤩"],[125192,1,"𞤪"],[125193,1,"𞤫"],[125194,1,"𞤬"],[125195,1,"𞤭"],[125196,1,"𞤮"],[125197,1,"𞤯"],[125198,1,"𞤰"],[125199,1,"𞤱"],[125200,1,"𞤲"],[125201,1,"𞤳"],[125202,1,"𞤴"],[125203,1,"𞤵"],[125204,1,"𞤶"],[125205,1,"𞤷"],[125206,1,"𞤸"],[125207,1,"𞤹"],[125208,1,"𞤺"],[125209,1,"𞤻"],[125210,1,"𞤼"],[125211,1,"𞤽"],[125212,1,"𞤾"],[125213,1,"𞤿"],[125214,1,"𞥀"],[125215,1,"𞥁"],[125216,1,"𞥂"],[125217,1,"𞥃"],[[125218,125258],2],[125259,2],[[125260,125263],3],[[125264,125273],2],[[125274,125277],3],[[125278,125279],2],[[125280,126064],3],[[126065,126132],2],[[126133,126208],3],[[126209,126269],2],[[126270,126463],3],[126464,1,"ا"],[126465,1,"ب"],[126466,1,"ج"],[126467,1,"د"],[126468,3],[126469,1,"و"],[126470,1,"ز"],[126471,1,"ح"],[126472,1,"ط"],[126473,1,"ي"],[126474,1,"ك"],[126475,1,"ل"],[126476,1,"م"],[126477,1,"ن"],[126478,1,"س"],[126479,1,"ع"],[126480,1,"ف"],[126481,1,"ص"],[126482,1,"ق"],[126483,1,"ر"],[126484,1,"ش"],[126485,1,"ت"],[126486,1,"ث"],[126487,1,"خ"],[126488,1,"ذ"],[126489,1,"ض"],[126490,1,"ظ"],[126491,1,"غ"],[126492,1,"ٮ"],[126493,1,"ں"],[126494,1,"ڡ"],[126495,1,"ٯ"],[126496,3],[126497,1,"ب"],[126498,1,"ج"],[126499,3],[126500,1,"ه"],[[126501,126502],3],[126503,1,"ح"],[126504,3],[126505,1,"ي"],[126506,1,"ك"],[126507,1,"ل"],[126508,1,"م"],[126509,1,"ن"],[126510,1,"س"],[126511,1,"ع"],[126512,1,"ف"],[126513,1,"ص"],[126514,1,"ق"],[126515,3],[126516,1,"ش"],[126517,1,"ت"],[126518,1,"ث"],[126519,1,"خ"],[126520,3],[126521,1,"ض"],[126522,3],[126523,1,"غ"],[[126524,126529],3],[126530,1,"ج"],[[126531,126534],3],[126535,1,"ح"],[126536,3],[126537,1,"ي"],[126538,3],[126539,1,"ل"],[126540,3],[126541,1,"ن"],[126542,1,"س"],[126543,1,"ع"],[126544,3],[126545,1,"ص"],[126546,1,"ق"],[126547,3],[126548,1,"ش"],[[126549,126550],3],[126551,1,"خ"],[126552,3],[126553,1,"ض"],[126554,3],[126555,1,"غ"],[126556,3],[126557,1,"ں"],[126558,3],[126559,1,"ٯ"],[126560,3],[126561,1,"ب"],[126562,1,"ج"],[126563,3],[126564,1,"ه"],[[126565,126566],3],[126567,1,"ح"],[126568,1,"ط"],[126569,1,"ي"],[126570,1,"ك"],[126571,3],[126572,1,"م"],[126573,1,"ن"],[126574,1,"س"],[126575,1,"ع"],[126576,1,"ف"],[126577,1,"ص"],[126578,1,"ق"],[126579,3],[126580,1,"ش"],[126581,1,"ت"],[126582,1,"ث"],[126583,1,"خ"],[126584,3],[126585,1,"ض"],[126586,1,"ظ"],[126587,1,"غ"],[126588,1,"ٮ"],[126589,3],[126590,1,"ڡ"],[126591,3],[126592,1,"ا"],[126593,1,"ب"],[126594,1,"ج"],[126595,1,"د"],[126596,1,"ه"],[126597,1,"و"],[126598,1,"ز"],[126599,1,"ح"],[126600,1,"ط"],[126601,1,"ي"],[126602,3],[126603,1,"ل"],[126604,1,"م"],[126605,1,"ن"],[126606,1,"س"],[126607,1,"ع"],[126608,1,"ف"],[126609,1,"ص"],[126610,1,"ق"],[126611,1,"ر"],[126612,1,"ش"],[126613,1,"ت"],[126614,1,"ث"],[126615,1,"خ"],[126616,1,"ذ"],[126617,1,"ض"],[126618,1,"ظ"],[126619,1,"غ"],[[126620,126624],3],[126625,1,"ب"],[126626,1,"ج"],[126627,1,"د"],[126628,3],[126629,1,"و"],[126630,1,"ز"],[126631,1,"ح"],[126632,1,"ط"],[126633,1,"ي"],[126634,3],[126635,1,"ل"],[126636,1,"م"],[126637,1,"ن"],[126638,1,"س"],[126639,1,"ع"],[126640,1,"ف"],[126641,1,"ص"],[126642,1,"ق"],[126643,1,"ر"],[126644,1,"ش"],[126645,1,"ت"],[126646,1,"ث"],[126647,1,"خ"],[126648,1,"ذ"],[126649,1,"ض"],[126650,1,"ظ"],[126651,1,"غ"],[[126652,126703],3],[[126704,126705],2],[[126706,126975],3],[[126976,127019],2],[[127020,127023],3],[[127024,127123],2],[[127124,127135],3],[[127136,127150],2],[[127151,127152],3],[[127153,127166],2],[127167,2],[127168,3],[[127169,127183],2],[127184,3],[[127185,127199],2],[[127200,127221],2],[[127222,127231],3],[127232,3],[127233,5,"0,"],[127234,5,"1,"],[127235,5,"2,"],[127236,5,"3,"],[127237,5,"4,"],[127238,5,"5,"],[127239,5,"6,"],[127240,5,"7,"],[127241,5,"8,"],[127242,5,"9,"],[[127243,127244],2],[[127245,127247],2],[127248,5,"(a)"],[127249,5,"(b)"],[127250,5,"(c)"],[127251,5,"(d)"],[127252,5,"(e)"],[127253,5,"(f)"],[127254,5,"(g)"],[127255,5,"(h)"],[127256,5,"(i)"],[127257,5,"(j)"],[127258,5,"(k)"],[127259,5,"(l)"],[127260,5,"(m)"],[127261,5,"(n)"],[127262,5,"(o)"],[127263,5,"(p)"],[127264,5,"(q)"],[127265,5,"(r)"],[127266,5,"(s)"],[127267,5,"(t)"],[127268,5,"(u)"],[127269,5,"(v)"],[127270,5,"(w)"],[127271,5,"(x)"],[127272,5,"(y)"],[127273,5,"(z)"],[127274,1,"〔s〕"],[127275,1,"c"],[127276,1,"r"],[127277,1,"cd"],[127278,1,"wz"],[127279,2],[127280,1,"a"],[127281,1,"b"],[127282,1,"c"],[127283,1,"d"],[127284,1,"e"],[127285,1,"f"],[127286,1,"g"],[127287,1,"h"],[127288,1,"i"],[127289,1,"j"],[127290,1,"k"],[127291,1,"l"],[127292,1,"m"],[127293,1,"n"],[127294,1,"o"],[127295,1,"p"],[127296,1,"q"],[127297,1,"r"],[127298,1,"s"],[127299,1,"t"],[127300,1,"u"],[127301,1,"v"],[127302,1,"w"],[127303,1,"x"],[127304,1,"y"],[127305,1,"z"],[127306,1,"hv"],[127307,1,"mv"],[127308,1,"sd"],[127309,1,"ss"],[127310,1,"ppv"],[127311,1,"wc"],[[127312,127318],2],[127319,2],[[127320,127326],2],[127327,2],[[127328,127337],2],[127338,1,"mc"],[127339,1,"md"],[127340,1,"mr"],[[127341,127343],2],[[127344,127352],2],[127353,2],[127354,2],[[127355,127356],2],[[127357,127358],2],[127359,2],[[127360,127369],2],[[127370,127373],2],[[127374,127375],2],[127376,1,"dj"],[[127377,127386],2],[[127387,127404],2],[127405,2],[[127406,127461],3],[[127462,127487],2],[127488,1,"ほか"],[127489,1,"ココ"],[127490,1,"サ"],[[127491,127503],3],[127504,1,"手"],[127505,1,"字"],[127506,1,"双"],[127507,1,"デ"],[127508,1,"二"],[127509,1,"多"],[127510,1,"解"],[127511,1,"天"],[127512,1,"交"],[127513,1,"映"],[127514,1,"無"],[127515,1,"料"],[127516,1,"前"],[127517,1,"後"],[127518,1,"再"],[127519,1,"新"],[127520,1,"初"],[127521,1,"終"],[127522,1,"生"],[127523,1,"販"],[127524,1,"声"],[127525,1,"吹"],[127526,1,"演"],[127527,1,"投"],[127528,1,"捕"],[127529,1,"一"],[127530,1,"三"],[127531,1,"遊"],[127532,1,"左"],[127533,1,"中"],[127534,1,"右"],[127535,1,"指"],[127536,1,"走"],[127537,1,"打"],[127538,1,"禁"],[127539,1,"空"],[127540,1,"合"],[127541,1,"満"],[127542,1,"有"],[127543,1,"月"],[127544,1,"申"],[127545,1,"割"],[127546,1,"営"],[127547,1,"配"],[[127548,127551],3],[127552,1,"〔本〕"],[127553,1,"〔三〕"],[127554,1,"〔二〕"],[127555,1,"〔安〕"],[127556,1,"〔点〕"],[127557,1,"〔打〕"],[127558,1,"〔盗〕"],[127559,1,"〔勝〕"],[127560,1,"〔敗〕"],[[127561,127567],3],[127568,1,"得"],[127569,1,"可"],[[127570,127583],3],[[127584,127589],2],[[127590,127743],3],[[127744,127776],2],[[127777,127788],2],[[127789,127791],2],[[127792,127797],2],[127798,2],[[127799,127868],2],[127869,2],[[127870,127871],2],[[127872,127891],2],[[127892,127903],2],[[127904,127940],2],[127941,2],[[127942,127946],2],[[127947,127950],2],[[127951,127955],2],[[127956,127967],2],[[127968,127984],2],[[127985,127991],2],[[127992,127999],2],[[128000,128062],2],[128063,2],[128064,2],[128065,2],[[128066,128247],2],[128248,2],[[128249,128252],2],[[128253,128254],2],[128255,2],[[128256,128317],2],[[128318,128319],2],[[128320,128323],2],[[128324,128330],2],[[128331,128335],2],[[128336,128359],2],[[128360,128377],2],[128378,2],[[128379,128419],2],[128420,2],[[128421,128506],2],[[128507,128511],2],[128512,2],[[128513,128528],2],[128529,2],[[128530,128532],2],[128533,2],[128534,2],[128535,2],[128536,2],[128537,2],[128538,2],[128539,2],[[128540,128542],2],[128543,2],[[128544,128549],2],[[128550,128551],2],[[128552,128555],2],[128556,2],[128557,2],[[128558,128559],2],[[128560,128563],2],[128564,2],[[128565,128576],2],[[128577,128578],2],[[128579,128580],2],[[128581,128591],2],[[128592,128639],2],[[128640,128709],2],[[128710,128719],2],[128720,2],[[128721,128722],2],[[128723,128724],2],[128725,2],[[128726,128727],2],[[128728,128731],3],[128732,2],[[128733,128735],2],[[128736,128748],2],[[128749,128751],3],[[128752,128755],2],[[128756,128758],2],[[128759,128760],2],[128761,2],[128762,2],[[128763,128764],2],[[128765,128767],3],[[128768,128883],2],[[128884,128886],2],[[128887,128890],3],[[128891,128895],2],[[128896,128980],2],[[128981,128984],2],[128985,2],[[128986,128991],3],[[128992,129003],2],[[129004,129007],3],[129008,2],[[129009,129023],3],[[129024,129035],2],[[129036,129039],3],[[129040,129095],2],[[129096,129103],3],[[129104,129113],2],[[129114,129119],3],[[129120,129159],2],[[129160,129167],3],[[129168,129197],2],[[129198,129199],3],[[129200,129201],2],[[129202,129279],3],[[129280,129291],2],[129292,2],[[129293,129295],2],[[129296,129304],2],[[129305,129310],2],[129311,2],[[129312,129319],2],[[129320,129327],2],[129328,2],[[129329,129330],2],[[129331,129342],2],[129343,2],[[129344,129355],2],[129356,2],[[129357,129359],2],[[129360,129374],2],[[129375,129387],2],[[129388,129392],2],[129393,2],[129394,2],[[129395,129398],2],[[129399,129400],2],[129401,2],[129402,2],[129403,2],[[129404,129407],2],[[129408,129412],2],[[129413,129425],2],[[129426,129431],2],[[129432,129442],2],[[129443,129444],2],[[129445,129450],2],[[129451,129453],2],[[129454,129455],2],[[129456,129465],2],[[129466,129471],2],[129472,2],[[129473,129474],2],[[129475,129482],2],[129483,2],[129484,2],[[129485,129487],2],[[129488,129510],2],[[129511,129535],2],[[129536,129619],2],[[129620,129631],3],[[129632,129645],2],[[129646,129647],3],[[129648,129651],2],[129652,2],[[129653,129655],2],[[129656,129658],2],[[129659,129660],2],[[129661,129663],3],[[129664,129666],2],[[129667,129670],2],[[129671,129672],2],[[129673,129679],3],[[129680,129685],2],[[129686,129704],2],[[129705,129708],2],[[129709,129711],2],[[129712,129718],2],[[129719,129722],2],[[129723,129725],2],[129726,3],[129727,2],[[129728,129730],2],[[129731,129733],2],[[129734,129741],3],[[129742,129743],2],[[129744,129750],2],[[129751,129753],2],[[129754,129755],2],[[129756,129759],3],[[129760,129767],2],[129768,2],[[129769,129775],3],[[129776,129782],2],[[129783,129784],2],[[129785,129791],3],[[129792,129938],2],[129939,3],[[129940,129994],2],[[129995,130031],3],[130032,1,"0"],[130033,1,"1"],[130034,1,"2"],[130035,1,"3"],[130036,1,"4"],[130037,1,"5"],[130038,1,"6"],[130039,1,"7"],[130040,1,"8"],[130041,1,"9"],[[130042,131069],3],[[131070,131071],3],[[131072,173782],2],[[173783,173789],2],[[173790,173791],2],[[173792,173823],3],[[173824,177972],2],[[177973,177976],2],[177977,2],[[177978,177983],3],[[177984,178205],2],[[178206,178207],3],[[178208,183969],2],[[183970,183983],3],[[183984,191456],2],[[191457,194559],3],[194560,1,"丽"],[194561,1,"丸"],[194562,1,"乁"],[194563,1,"𠄢"],[194564,1,"你"],[194565,1,"侮"],[194566,1,"侻"],[194567,1,"倂"],[194568,1,"偺"],[194569,1,"備"],[194570,1,"僧"],[194571,1,"像"],[194572,1,"㒞"],[194573,1,"𠘺"],[194574,1,"免"],[194575,1,"兔"],[194576,1,"兤"],[194577,1,"具"],[194578,1,"𠔜"],[194579,1,"㒹"],[194580,1,"內"],[194581,1,"再"],[194582,1,"𠕋"],[194583,1,"冗"],[194584,1,"冤"],[194585,1,"仌"],[194586,1,"冬"],[194587,1,"况"],[194588,1,"𩇟"],[194589,1,"凵"],[194590,1,"刃"],[194591,1,"㓟"],[194592,1,"刻"],[194593,1,"剆"],[194594,1,"割"],[194595,1,"剷"],[194596,1,"㔕"],[194597,1,"勇"],[194598,1,"勉"],[194599,1,"勤"],[194600,1,"勺"],[194601,1,"包"],[194602,1,"匆"],[194603,1,"北"],[194604,1,"卉"],[194605,1,"卑"],[194606,1,"博"],[194607,1,"即"],[194608,1,"卽"],[[194609,194611],1,"卿"],[194612,1,"𠨬"],[194613,1,"灰"],[194614,1,"及"],[194615,1,"叟"],[194616,1,"𠭣"],[194617,1,"叫"],[194618,1,"叱"],[194619,1,"吆"],[194620,1,"咞"],[194621,1,"吸"],[194622,1,"呈"],[194623,1,"周"],[194624,1,"咢"],[194625,1,"哶"],[194626,1,"唐"],[194627,1,"啓"],[194628,1,"啣"],[[194629,194630],1,"善"],[194631,1,"喙"],[194632,1,"喫"],[194633,1,"喳"],[194634,1,"嗂"],[194635,1,"圖"],[194636,1,"嘆"],[194637,1,"圗"],[194638,1,"噑"],[194639,1,"噴"],[194640,1,"切"],[194641,1,"壮"],[194642,1,"城"],[194643,1,"埴"],[194644,1,"堍"],[194645,1,"型"],[194646,1,"堲"],[194647,1,"報"],[194648,1,"墬"],[194649,1,"𡓤"],[194650,1,"売"],[194651,1,"壷"],[194652,1,"夆"],[194653,1,"多"],[194654,1,"夢"],[194655,1,"奢"],[194656,1,"𡚨"],[194657,1,"𡛪"],[194658,1,"姬"],[194659,1,"娛"],[194660,1,"娧"],[194661,1,"姘"],[194662,1,"婦"],[194663,1,"㛮"],[194664,3],[194665,1,"嬈"],[[194666,194667],1,"嬾"],[194668,1,"𡧈"],[194669,1,"寃"],[194670,1,"寘"],[194671,1,"寧"],[194672,1,"寳"],[194673,1,"𡬘"],[194674,1,"寿"],[194675,1,"将"],[194676,3],[194677,1,"尢"],[194678,1,"㞁"],[194679,1,"屠"],[194680,1,"屮"],[194681,1,"峀"],[194682,1,"岍"],[194683,1,"𡷤"],[194684,1,"嵃"],[194685,1,"𡷦"],[194686,1,"嵮"],[194687,1,"嵫"],[194688,1,"嵼"],[194689,1,"巡"],[194690,1,"巢"],[194691,1,"㠯"],[194692,1,"巽"],[194693,1,"帨"],[194694,1,"帽"],[194695,1,"幩"],[194696,1,"㡢"],[194697,1,"𢆃"],[194698,1,"㡼"],[194699,1,"庰"],[194700,1,"庳"],[194701,1,"庶"],[194702,1,"廊"],[194703,1,"𪎒"],[194704,1,"廾"],[[194705,194706],1,"𢌱"],[194707,1,"舁"],[[194708,194709],1,"弢"],[194710,1,"㣇"],[194711,1,"𣊸"],[194712,1,"𦇚"],[194713,1,"形"],[194714,1,"彫"],[194715,1,"㣣"],[194716,1,"徚"],[194717,1,"忍"],[194718,1,"志"],[194719,1,"忹"],[194720,1,"悁"],[194721,1,"㤺"],[194722,1,"㤜"],[194723,1,"悔"],[194724,1,"𢛔"],[194725,1,"惇"],[194726,1,"慈"],[194727,1,"慌"],[194728,1,"慎"],[194729,1,"慌"],[194730,1,"慺"],[194731,1,"憎"],[194732,1,"憲"],[194733,1,"憤"],[194734,1,"憯"],[194735,1,"懞"],[194736,1,"懲"],[194737,1,"懶"],[194738,1,"成"],[194739,1,"戛"],[194740,1,"扝"],[194741,1,"抱"],[194742,1,"拔"],[194743,1,"捐"],[194744,1,"𢬌"],[194745,1,"挽"],[194746,1,"拼"],[194747,1,"捨"],[194748,1,"掃"],[194749,1,"揤"],[194750,1,"𢯱"],[194751,1,"搢"],[194752,1,"揅"],[194753,1,"掩"],[194754,1,"㨮"],[194755,1,"摩"],[194756,1,"摾"],[194757,1,"撝"],[194758,1,"摷"],[194759,1,"㩬"],[194760,1,"敏"],[194761,1,"敬"],[194762,1,"𣀊"],[194763,1,"旣"],[194764,1,"書"],[194765,1,"晉"],[194766,1,"㬙"],[194767,1,"暑"],[194768,1,"㬈"],[194769,1,"㫤"],[194770,1,"冒"],[194771,1,"冕"],[194772,1,"最"],[194773,1,"暜"],[194774,1,"肭"],[194775,1,"䏙"],[194776,1,"朗"],[194777,1,"望"],[194778,1,"朡"],[194779,1,"杞"],[194780,1,"杓"],[194781,1,"𣏃"],[194782,1,"㭉"],[194783,1,"柺"],[194784,1,"枅"],[194785,1,"桒"],[194786,1,"梅"],[194787,1,"𣑭"],[194788,1,"梎"],[194789,1,"栟"],[194790,1,"椔"],[194791,1,"㮝"],[194792,1,"楂"],[194793,1,"榣"],[194794,1,"槪"],[194795,1,"檨"],[194796,1,"𣚣"],[194797,1,"櫛"],[194798,1,"㰘"],[194799,1,"次"],[194800,1,"𣢧"],[194801,1,"歔"],[194802,1,"㱎"],[194803,1,"歲"],[194804,1,"殟"],[194805,1,"殺"],[194806,1,"殻"],[194807,1,"𣪍"],[194808,1,"𡴋"],[194809,1,"𣫺"],[194810,1,"汎"],[194811,1,"𣲼"],[194812,1,"沿"],[194813,1,"泍"],[194814,1,"汧"],[194815,1,"洖"],[194816,1,"派"],[194817,1,"海"],[194818,1,"流"],[194819,1,"浩"],[194820,1,"浸"],[194821,1,"涅"],[194822,1,"𣴞"],[194823,1,"洴"],[194824,1,"港"],[194825,1,"湮"],[194826,1,"㴳"],[194827,1,"滋"],[194828,1,"滇"],[194829,1,"𣻑"],[194830,1,"淹"],[194831,1,"潮"],[194832,1,"𣽞"],[194833,1,"𣾎"],[194834,1,"濆"],[194835,1,"瀹"],[194836,1,"瀞"],[194837,1,"瀛"],[194838,1,"㶖"],[194839,1,"灊"],[194840,1,"災"],[194841,1,"灷"],[194842,1,"炭"],[194843,1,"𠔥"],[194844,1,"煅"],[194845,1,"𤉣"],[194846,1,"熜"],[194847,3],[194848,1,"爨"],[194849,1,"爵"],[194850,1,"牐"],[194851,1,"𤘈"],[194852,1,"犀"],[194853,1,"犕"],[194854,1,"𤜵"],[194855,1,"𤠔"],[194856,1,"獺"],[194857,1,"王"],[194858,1,"㺬"],[194859,1,"玥"],[[194860,194861],1,"㺸"],[194862,1,"瑇"],[194863,1,"瑜"],[194864,1,"瑱"],[194865,1,"璅"],[194866,1,"瓊"],[194867,1,"㼛"],[194868,1,"甤"],[194869,1,"𤰶"],[194870,1,"甾"],[194871,1,"𤲒"],[194872,1,"異"],[194873,1,"𢆟"],[194874,1,"瘐"],[194875,1,"𤾡"],[194876,1,"𤾸"],[194877,1,"𥁄"],[194878,1,"㿼"],[194879,1,"䀈"],[194880,1,"直"],[194881,1,"𥃳"],[194882,1,"𥃲"],[194883,1,"𥄙"],[194884,1,"𥄳"],[194885,1,"眞"],[[194886,194887],1,"真"],[194888,1,"睊"],[194889,1,"䀹"],[194890,1,"瞋"],[194891,1,"䁆"],[194892,1,"䂖"],[194893,1,"𥐝"],[194894,1,"硎"],[194895,1,"碌"],[194896,1,"磌"],[194897,1,"䃣"],[194898,1,"𥘦"],[194899,1,"祖"],[194900,1,"𥚚"],[194901,1,"𥛅"],[194902,1,"福"],[194903,1,"秫"],[194904,1,"䄯"],[194905,1,"穀"],[194906,1,"穊"],[194907,1,"穏"],[194908,1,"𥥼"],[[194909,194910],1,"𥪧"],[194911,3],[194912,1,"䈂"],[194913,1,"𥮫"],[194914,1,"篆"],[194915,1,"築"],[194916,1,"䈧"],[194917,1,"𥲀"],[194918,1,"糒"],[194919,1,"䊠"],[194920,1,"糨"],[194921,1,"糣"],[194922,1,"紀"],[194923,1,"𥾆"],[194924,1,"絣"],[194925,1,"䌁"],[194926,1,"緇"],[194927,1,"縂"],[194928,1,"繅"],[194929,1,"䌴"],[194930,1,"𦈨"],[194931,1,"𦉇"],[194932,1,"䍙"],[194933,1,"𦋙"],[194934,1,"罺"],[194935,1,"𦌾"],[194936,1,"羕"],[194937,1,"翺"],[194938,1,"者"],[194939,1,"𦓚"],[194940,1,"𦔣"],[194941,1,"聠"],[194942,1,"𦖨"],[194943,1,"聰"],[194944,1,"𣍟"],[194945,1,"䏕"],[194946,1,"育"],[194947,1,"脃"],[194948,1,"䐋"],[194949,1,"脾"],[194950,1,"媵"],[194951,1,"𦞧"],[194952,1,"𦞵"],[194953,1,"𣎓"],[194954,1,"𣎜"],[194955,1,"舁"],[194956,1,"舄"],[194957,1,"辞"],[194958,1,"䑫"],[194959,1,"芑"],[194960,1,"芋"],[194961,1,"芝"],[194962,1,"劳"],[194963,1,"花"],[194964,1,"芳"],[194965,1,"芽"],[194966,1,"苦"],[194967,1,"𦬼"],[194968,1,"若"],[194969,1,"茝"],[194970,1,"荣"],[194971,1,"莭"],[194972,1,"茣"],[194973,1,"莽"],[194974,1,"菧"],[194975,1,"著"],[194976,1,"荓"],[194977,1,"菊"],[194978,1,"菌"],[194979,1,"菜"],[194980,1,"𦰶"],[194981,1,"𦵫"],[194982,1,"𦳕"],[194983,1,"䔫"],[194984,1,"蓱"],[194985,1,"蓳"],[194986,1,"蔖"],[194987,1,"𧏊"],[194988,1,"蕤"],[194989,1,"𦼬"],[194990,1,"䕝"],[194991,1,"䕡"],[194992,1,"𦾱"],[194993,1,"𧃒"],[194994,1,"䕫"],[194995,1,"虐"],[194996,1,"虜"],[194997,1,"虧"],[194998,1,"虩"],[194999,1,"蚩"],[195000,1,"蚈"],[195001,1,"蜎"],[195002,1,"蛢"],[195003,1,"蝹"],[195004,1,"蜨"],[195005,1,"蝫"],[195006,1,"螆"],[195007,3],[195008,1,"蟡"],[195009,1,"蠁"],[195010,1,"䗹"],[195011,1,"衠"],[195012,1,"衣"],[195013,1,"𧙧"],[195014,1,"裗"],[195015,1,"裞"],[195016,1,"䘵"],[195017,1,"裺"],[195018,1,"㒻"],[195019,1,"𧢮"],[195020,1,"𧥦"],[195021,1,"䚾"],[195022,1,"䛇"],[195023,1,"誠"],[195024,1,"諭"],[195025,1,"變"],[195026,1,"豕"],[195027,1,"𧲨"],[195028,1,"貫"],[195029,1,"賁"],[195030,1,"贛"],[195031,1,"起"],[195032,1,"𧼯"],[195033,1,"𠠄"],[195034,1,"跋"],[195035,1,"趼"],[195036,1,"跰"],[195037,1,"𠣞"],[195038,1,"軔"],[195039,1,"輸"],[195040,1,"𨗒"],[195041,1,"𨗭"],[195042,1,"邔"],[195043,1,"郱"],[195044,1,"鄑"],[195045,1,"𨜮"],[195046,1,"鄛"],[195047,1,"鈸"],[195048,1,"鋗"],[195049,1,"鋘"],[195050,1,"鉼"],[195051,1,"鏹"],[195052,1,"鐕"],[195053,1,"𨯺"],[195054,1,"開"],[195055,1,"䦕"],[195056,1,"閷"],[195057,1,"𨵷"],[195058,1,"䧦"],[195059,1,"雃"],[195060,1,"嶲"],[195061,1,"霣"],[195062,1,"𩅅"],[195063,1,"𩈚"],[195064,1,"䩮"],[195065,1,"䩶"],[195066,1,"韠"],[195067,1,"𩐊"],[195068,1,"䪲"],[195069,1,"𩒖"],[[195070,195071],1,"頋"],[195072,1,"頩"],[195073,1,"𩖶"],[195074,1,"飢"],[195075,1,"䬳"],[195076,1,"餩"],[195077,1,"馧"],[195078,1,"駂"],[195079,1,"駾"],[195080,1,"䯎"],[195081,1,"𩬰"],[195082,1,"鬒"],[195083,1,"鱀"],[195084,1,"鳽"],[195085,1,"䳎"],[195086,1,"䳭"],[195087,1,"鵧"],[195088,1,"𪃎"],[195089,1,"䳸"],[195090,1,"𪄅"],[195091,1,"𪈎"],[195092,1,"𪊑"],[195093,1,"麻"],[195094,1,"䵖"],[195095,1,"黹"],[195096,1,"黾"],[195097,1,"鼅"],[195098,1,"鼏"],[195099,1,"鼖"],[195100,1,"鼻"],[195101,1,"𪘀"],[[195102,196605],3],[[196606,196607],3],[[196608,201546],2],[[201547,201551],3],[[201552,205743],2],[[205744,262141],3],[[262142,262143],3],[[262144,327677],3],[[327678,327679],3],[[327680,393213],3],[[393214,393215],3],[[393216,458749],3],[[458750,458751],3],[[458752,524285],3],[[524286,524287],3],[[524288,589821],3],[[589822,589823],3],[[589824,655357],3],[[655358,655359],3],[[655360,720893],3],[[720894,720895],3],[[720896,786429],3],[[786430,786431],3],[[786432,851965],3],[[851966,851967],3],[[851968,917501],3],[[917502,917503],3],[917504,3],[917505,3],[[917506,917535],3],[[917536,917631],3],[[917632,917759],3],[[917760,917999],7],[[918000,983037],3],[[983038,983039],3],[[983040,1048573],3],[[1048574,1048575],3],[[1048576,1114109],3],[[1114110,1114111],3]] \ No newline at end of file diff --git a/nodejs/node_modules/tr46/lib/regexes.js b/nodejs/node_modules/tr46/lib/regexes.js new file mode 100644 index 00000000..14a5bf98 --- /dev/null +++ b/nodejs/node_modules/tr46/lib/regexes.js @@ -0,0 +1,29 @@ +"use strict"; + +const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10EFD}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{11241}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{11F00}\u{11F01}\u{11F03}\u{11F34}-\u{11F3A}\u{11F3E}-\u{11F42}\u{13440}\u{13447}-\u{13455}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; +const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}]/u; +const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{1E900}-\u{1E943}]/u; +const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0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ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11F02}-\u{11F10}\u{11F12}-\u{11F35}\u{11F3E}\u{11F3F}\u{11F41}\u{11F43}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1343F}\u{13441}-\u{13446}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E4D0}-\u{1E4EB}\u{1E4F0}-\u{1E4F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; +const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u0898-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20C0\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD8F\uFD92-\uFDC7\uFDCF\uFDF0-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10EFD}-\u{10F27}\u{10F30}-\u{10F59}\u{10F70}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11FD5}-\u{11FF1}\u{13440}\u{13447}-\u{13455}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1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000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10F}\u{1F12F}\u{1F16A}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F776}\u{1F77B}-\u{1F7D9}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FA88}\u{1FA90}-\u{1FABD}\u{1FABF}-\u{1FAC5}\u{1FACE}-\u{1FADB}\u{1FAE0}-\u{1FAE8}\u{1FAF0}-\u{1FAF8}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; +const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10EFD}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{13440}\u{13447}-\u{13455}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; +const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u; +const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u0890\u0891\u08E2\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}]/u; +const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0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5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u1715\u171F-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ACE\u1B00-\u1B4C\u1B50-\u1B7E\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20C0\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E3\u31F0-\u321E\u3220-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E-\uFD4F\uFDCF\uFDFD-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10EFD}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{1104D}\u{11052}-\u{11075}\u{1107F}-\u{110C2}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{11241}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{11746}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11F00}-\u{11F10}\u{11F12}-\u{11F3A}\u{11F3E}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{13455}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1EA}\u{1D200}-\u{1D245}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E030}-\u{1E06D}\u{1E08F}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AE}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E4D0}-\u{1E4F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F776}\u{1F77B}-\u{1F7D9}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FA88}\u{1FA90}-\u{1FABD}\u{1FABF}-\u{1FAC5}\u{1FACE}-\u{1FADB}\u{1FAE0}-\u{1FAE8}\u{1FAF0}-\u{1FAF8}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; +const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3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\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{1123F}\u{11240}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11B00}-\u{11B09}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11F02}-\u{11F10}\u{11F12}-\u{11F35}\u{11F3E}\u{11F3F}\u{11F41}\u{11F43}-\u{11F59}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1343F}\u{13441}-\u{13446}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B132}\u{1B150}-\u{1B152}\u{1B155}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2C0}-\u{1D2D3}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1DF25}-\u{1DF2A}\u{1E030}-\u{1E06D}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E4D0}-\u{1E4EB}\u{1E4F0}-\u{1E4F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B739}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{31350}-\u{323AF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10EFD}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11F00}\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{13440}\u{13447}-\u{13455}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; + +module.exports = { + combiningMarks, + combiningClassVirama, + validZWNJ, + bidiDomain, + bidiS1LTR, + bidiS1RTL, + bidiS2, + bidiS3, + bidiS4EN, + bidiS4AN, + bidiS5, + bidiS6 +}; diff --git a/nodejs/node_modules/tr46/lib/statusMapping.js b/nodejs/node_modules/tr46/lib/statusMapping.js new file mode 100644 index 00000000..cfed6d6a --- /dev/null +++ b/nodejs/node_modules/tr46/lib/statusMapping.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports.STATUS_MAPPING = { + mapped: 1, + valid: 2, + disallowed: 3, + disallowed_STD3_valid: 4, + disallowed_STD3_mapped: 5, + deviation: 6, + ignored: 7 +}; diff --git a/nodejs/node_modules/tr46/package.json b/nodejs/node_modules/tr46/package.json new file mode 100644 index 00000000..1b59d728 --- /dev/null +++ b/nodejs/node_modules/tr46/package.json @@ -0,0 +1,45 @@ +{ + "name": "tr46", + "version": "4.1.1", + "engines": { + "node": ">=14" + }, + "description": "An implementation of the Unicode UTS #46: Unicode IDNA Compatibility Processing", + "main": "index.js", + "files": [ + "index.js", + "lib/" + ], + "scripts": { + "test": "mocha", + "lint": "eslint .", + "pretest": "node scripts/getLatestTests.js", + "prepublish": "node scripts/generateMappingTable.js && node scripts/generateRegexes.js" + }, + "repository": "https://github.com/jsdom/tr46", + "keywords": [ + "unicode", + "tr46", + "uts46", + "punycode", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "contributors": [ + "Timothy Gu " + ], + "license": "MIT", + "dependencies": { + "punycode": "^2.3.0" + }, + "devDependencies": { + "@domenic/eslint-config": "^3.0.0", + "@unicode/unicode-15.0.0": "^1.3.1", + "eslint": "^8.32.0", + "minipass-fetch": "^3.0.1", + "mocha": "^10.2.0", + "regenerate": "^1.4.2" + }, + "unicodeVersion": "15.0.0" +} diff --git a/nodejs/node_modules/triple-beam/.nyc_output/c579bf8f-6820-47a5-b2da-a11267eb8435.json b/nodejs/node_modules/triple-beam/.nyc_output/c579bf8f-6820-47a5-b2da-a11267eb8435.json new file mode 100644 index 00000000..00aab89c --- /dev/null +++ b/nodejs/node_modules/triple-beam/.nyc_output/c579bf8f-6820-47a5-b2da-a11267eb8435.json @@ -0,0 +1 @@ +{"/Users/dabh/triple-beam/index.js":{"path":"/Users/dabh/triple-beam/index.js","statementMap":{"0":{"start":{"line":11,"column":0},"end":{"line":13,"column":3}},"1":{"start":{"line":23,"column":0},"end":{"line":25,"column":3}},"2":{"start":{"line":34,"column":0},"end":{"line":36,"column":3}},"3":{"start":{"line":44,"column":0},"end":{"line":46,"column":3}}},"fnMap":{},"branchMap":{},"s":{"0":1,"1":1,"2":1,"3":1},"f":{},"b":{},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"cc95d94182fb79b1be57a24c1394db64cdb2ae43","contentHash":"fc4e5a28fd95e03cae6b5495203bb1875d4000296fe4308cb90943317c6cd273"},"/Users/dabh/triple-beam/config/index.js":{"path":"/Users/dabh/triple-beam/config/index.js","statementMap":{"0":{"start":{"line":14,"column":0},"end":{"line":16,"column":3}},"1":{"start":{"line":22,"column":0},"end":{"line":24,"column":3}},"2":{"start":{"line":30,"column":0},"end":{"line":32,"column":3}}},"fnMap":{},"branchMap":{},"s":{"0":1,"1":1,"2":1},"f":{},"b":{},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"153b0bdac58673ccf1f21070117bb797c37a2456","contentHash":"162d744ed325a346a9b0913721d2f61535053e170a78dc205aef5ae6aef820de"},"/Users/dabh/triple-beam/config/cli.js":{"path":"/Users/dabh/triple-beam/config/cli.js","statementMap":{"0":{"start":{"line":14,"column":0},"end":{"line":25,"column":2}},"1":{"start":{"line":31,"column":0},"end":{"line":42,"column":2}}},"fnMap":{},"branchMap":{},"s":{"0":1,"1":1},"f":{},"b":{},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"4843c10f2957d007fb3125cc3a04d3b940a44851","contentHash":"3c526501a0b8bf50d0bbc28e6d4a1baf4c1798586fe1154292a1d9ba3a77efaf"},"/Users/dabh/triple-beam/config/npm.js":{"path":"/Users/dabh/triple-beam/config/npm.js","statementMap":{"0":{"start":{"line":14,"column":0},"end":{"line":22,"column":2}},"1":{"start":{"line":28,"column":0},"end":{"line":36,"column":2}}},"fnMap":{},"branchMap":{},"s":{"0":1,"1":1},"f":{},"b":{},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"56fb16df83c6d6275045feafabbe26c61f098c4b","contentHash":"07a4e369cf657d332a918f7ca96bcc1b831720e571cc2902aec1feed0c598920"},"/Users/dabh/triple-beam/config/syslog.js":{"path":"/Users/dabh/triple-beam/config/syslog.js","statementMap":{"0":{"start":{"line":14,"column":0},"end":{"line":23,"column":2}},"1":{"start":{"line":29,"column":0},"end":{"line":38,"column":2}}},"fnMap":{},"branchMap":{},"s":{"0":1,"1":1},"f":{},"b":{},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"4a8f05f93061e8c418dd384c10b82586a7f6e950","contentHash":"6177cc185f053def4bdb52172b771267aa2ee7ff9e11208e7f88ec323f1b058a"}} \ No newline at end of file diff --git a/nodejs/node_modules/triple-beam/.nyc_output/processinfo/c579bf8f-6820-47a5-b2da-a11267eb8435.json b/nodejs/node_modules/triple-beam/.nyc_output/processinfo/c579bf8f-6820-47a5-b2da-a11267eb8435.json new file mode 100644 index 00000000..02a59af0 --- /dev/null +++ b/nodejs/node_modules/triple-beam/.nyc_output/processinfo/c579bf8f-6820-47a5-b2da-a11267eb8435.json @@ -0,0 +1 @@ +{"parent":null,"pid":28538,"argv":["/Users/dabh/.nvm/versions/node/v16.18.0/bin/node","/Users/dabh/triple-beam/node_modules/.bin/mocha","test.js"],"execArgv":[],"cwd":"/Users/dabh/triple-beam","time":1689003099183,"ppid":28537,"coverageFilename":"/Users/dabh/triple-beam/.nyc_output/c579bf8f-6820-47a5-b2da-a11267eb8435.json","externalId":"","uuid":"c579bf8f-6820-47a5-b2da-a11267eb8435","files":["/Users/dabh/triple-beam/index.js","/Users/dabh/triple-beam/config/index.js","/Users/dabh/triple-beam/config/cli.js","/Users/dabh/triple-beam/config/npm.js","/Users/dabh/triple-beam/config/syslog.js"]} \ No newline at end of file diff --git a/nodejs/node_modules/triple-beam/.nyc_output/processinfo/index.json b/nodejs/node_modules/triple-beam/.nyc_output/processinfo/index.json new file mode 100644 index 00000000..5464526f --- /dev/null +++ b/nodejs/node_modules/triple-beam/.nyc_output/processinfo/index.json @@ -0,0 +1 @@ +{"processes":{"c579bf8f-6820-47a5-b2da-a11267eb8435":{"parent":null,"children":[]}},"files":{"/Users/dabh/triple-beam/index.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/index.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/cli.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/npm.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/syslog.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"]},"externalIds":{}} \ No newline at end of file diff --git a/nodejs/node_modules/triple-beam/CHANGELOG.md b/nodejs/node_modules/triple-beam/CHANGELOG.md new file mode 100644 index 00000000..9c5e54ac --- /dev/null +++ b/nodejs/node_modules/triple-beam/CHANGELOG.md @@ -0,0 +1,22 @@ +# CHANGELOG + +### 1.3.0 + +- [#4] Add `SPLAT` symbol. +- [#3] Add linting & TravisCI. + +### 1.2.0 + +- [#2] Move configs from `winston.config.{npm,syslog,npm}` into `triple-beam`. + +### 1.1.0 + +- Expose a `MESSAGE` Symbol, nothing more. + +### 1.0.1 + +- Use `Symbol.for` because that is how they work apparently. + +### 1.0.0 + +- Initial version. Defines a `LEVEL` Symbol, nothing more. diff --git a/nodejs/node_modules/triple-beam/LICENSE b/nodejs/node_modules/triple-beam/LICENSE new file mode 100644 index 00000000..1a1238aa --- /dev/null +++ b/nodejs/node_modules/triple-beam/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 winstonjs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/triple-beam/README.md b/nodejs/node_modules/triple-beam/README.md new file mode 100644 index 00000000..19543164 --- /dev/null +++ b/nodejs/node_modules/triple-beam/README.md @@ -0,0 +1,34 @@ +# triple-beam + +Definitions of levels for logging purposes & shareable Symbol constants. + +## Usage + +``` js +const { LEVEL } = require('triple-beam'); +const colors = require('colors/safe'); + +const info = { + [LEVEL]: 'error', + level: 'error', + message: 'hey a logging message!' +}; + +// Colorize your log level! +info.level = colors.green(info.level); + +// And still have an unmutated copy of your level! +console.log(info.level === 'error'); // false +console.log(info[LEVEL] === 'error'); // true +``` + +## Tests + +Tests are written with `mocha`, `assume`, and `nyc`. They can be run with `npm`: + +``` +npm test +``` + +##### LICENSE: MIT +##### AUTHOR: [Charlie Robbins](https://github.com/indexzero) diff --git a/nodejs/node_modules/triple-beam/config/cli.js b/nodejs/node_modules/triple-beam/config/cli.js new file mode 100644 index 00000000..028c117e --- /dev/null +++ b/nodejs/node_modules/triple-beam/config/cli.js @@ -0,0 +1,42 @@ +/** + * cli.js: Config that conform to commonly used CLI logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Default levels for the CLI configuration. + * @type {Object} + */ +exports.levels = { + error: 0, + warn: 1, + help: 2, + data: 3, + info: 4, + debug: 5, + prompt: 6, + verbose: 7, + input: 8, + silly: 9 +}; + +/** + * Default colors for the CLI configuration. + * @type {Object} + */ +exports.colors = { + error: 'red', + warn: 'yellow', + help: 'cyan', + data: 'grey', + info: 'green', + debug: 'blue', + prompt: 'grey', + verbose: 'cyan', + input: 'grey', + silly: 'magenta' +}; diff --git a/nodejs/node_modules/triple-beam/config/index.js b/nodejs/node_modules/triple-beam/config/index.js new file mode 100644 index 00000000..96b6566d --- /dev/null +++ b/nodejs/node_modules/triple-beam/config/index.js @@ -0,0 +1,32 @@ +/** + * index.js: Default settings for all levels that winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Export config set for the CLI. + * @type {Object} + */ +Object.defineProperty(exports, 'cli', { + value: require('./cli') +}); + +/** + * Export config set for npm. + * @type {Object} + */ +Object.defineProperty(exports, 'npm', { + value: require('./npm') +}); + +/** + * Export config set for the syslog. + * @type {Object} + */ +Object.defineProperty(exports, 'syslog', { + value: require('./syslog') +}); diff --git a/nodejs/node_modules/triple-beam/config/npm.js b/nodejs/node_modules/triple-beam/config/npm.js new file mode 100644 index 00000000..01f88ab4 --- /dev/null +++ b/nodejs/node_modules/triple-beam/config/npm.js @@ -0,0 +1,36 @@ +/** + * npm.js: Config that conform to npm logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Default levels for the npm configuration. + * @type {Object} + */ +exports.levels = { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 +}; + +/** + * Default levels for the npm configuration. + * @type {Object} + */ +exports.colors = { + error: 'red', + warn: 'yellow', + info: 'green', + http: 'green', + verbose: 'cyan', + debug: 'blue', + silly: 'magenta' +}; diff --git a/nodejs/node_modules/triple-beam/config/syslog.js b/nodejs/node_modules/triple-beam/config/syslog.js new file mode 100644 index 00000000..9c7b82f5 --- /dev/null +++ b/nodejs/node_modules/triple-beam/config/syslog.js @@ -0,0 +1,38 @@ +/** + * syslog.js: Config that conform to syslog logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Default levels for the syslog configuration. + * @type {Object} + */ +exports.levels = { + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 +}; + +/** + * Default levels for the syslog configuration. + * @type {Object} + */ +exports.colors = { + emerg: 'red', + alert: 'yellow', + crit: 'red', + error: 'red', + warning: 'red', + notice: 'yellow', + info: 'green', + debug: 'blue' +}; diff --git a/nodejs/node_modules/triple-beam/index.js b/nodejs/node_modules/triple-beam/index.js new file mode 100644 index 00000000..cf89cf06 --- /dev/null +++ b/nodejs/node_modules/triple-beam/index.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * A shareable symbol constant that can be used + * as a non-enumerable / semi-hidden level identifier + * to allow the readable level property to be mutable for + * operations like colorization + * + * @type {Symbol} + */ +Object.defineProperty(exports, 'LEVEL', { + value: Symbol.for('level') +}); + +/** + * A shareable symbol constant that can be used + * as a non-enumerable / semi-hidden message identifier + * to allow the final message property to not have + * side effects on another. + * + * @type {Symbol} + */ +Object.defineProperty(exports, 'MESSAGE', { + value: Symbol.for('message') +}); + +/** + * A shareable symbol constant that can be used + * as a non-enumerable / semi-hidden message identifier + * to allow the extracted splat property be hidden + * + * @type {Symbol} + */ +Object.defineProperty(exports, 'SPLAT', { + value: Symbol.for('splat') +}); + +/** + * A shareable object constant that can be used + * as a standard configuration for winston@3. + * + * @type {Object} + */ +Object.defineProperty(exports, 'configs', { + value: require('./config') +}); diff --git a/nodejs/node_modules/triple-beam/package.json b/nodejs/node_modules/triple-beam/package.json new file mode 100644 index 00000000..a606435d --- /dev/null +++ b/nodejs/node_modules/triple-beam/package.json @@ -0,0 +1,40 @@ +{ + "name": "triple-beam", + "version": "1.4.1", + "description": "Definitions of levels for logging purposes & shareable Symbol constants.", + "main": "index.js", + "scripts": { + "lint": "eslint config/*.js index.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", + "pretest": "npm run lint", + "test": "nyc mocha test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/winstonjs/triple-beam.git" + }, + "keywords": [ + "winstonjs", + "winston", + "logging", + "logform", + "symbols", + "logs", + "levels" + ], + "author": "Charlie Robbins ", + "license": "MIT", + "bugs": { + "url": "https://github.com/winstonjs/triple-beam/issues" + }, + "homepage": "https://github.com/winstonjs/triple-beam#readme", + "devDependencies": { + "assume": "^2.0.1", + "@dabh/eslint-config-populist": "^5.0.0", + "mocha": "^10.2.0", + "nyc": "^15.1.0", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">= 14.0.0" + } +} diff --git a/nodejs/node_modules/util-deprecate/History.md b/nodejs/node_modules/util-deprecate/History.md new file mode 100644 index 00000000..acc86753 --- /dev/null +++ b/nodejs/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/nodejs/node_modules/util-deprecate/LICENSE b/nodejs/node_modules/util-deprecate/LICENSE new file mode 100644 index 00000000..6a60e8c2 --- /dev/null +++ b/nodejs/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/util-deprecate/README.md b/nodejs/node_modules/util-deprecate/README.md new file mode 100644 index 00000000..75622fa7 --- /dev/null +++ b/nodejs/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/util-deprecate/browser.js b/nodejs/node_modules/util-deprecate/browser.js new file mode 100644 index 00000000..549ae2f0 --- /dev/null +++ b/nodejs/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/nodejs/node_modules/util-deprecate/node.js b/nodejs/node_modules/util-deprecate/node.js new file mode 100644 index 00000000..5e6fcff5 --- /dev/null +++ b/nodejs/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/nodejs/node_modules/util-deprecate/package.json b/nodejs/node_modules/util-deprecate/package.json new file mode 100644 index 00000000..2e79f89a --- /dev/null +++ b/nodejs/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/nodejs/node_modules/webidl-conversions/LICENSE.md b/nodejs/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 00000000..d4a994f5 --- /dev/null +++ b/nodejs/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/nodejs/node_modules/webidl-conversions/README.md b/nodejs/node_modules/webidl-conversions/README.md new file mode 100644 index 00000000..16cc3931 --- /dev/null +++ b/nodejs/node_modules/webidl-conversions/README.md @@ -0,0 +1,99 @@ +# Web IDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +"use strict"; +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a Web IDL operation declared as + +```webidl +undefined doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) + +If we are dealing with multiple JavaScript realms (such as those created using Node.js' [vm](https://nodejs.org/api/vm.html) module or the HTML `iframe` element), and exceptions from another realm need to be thrown, one can supply an object option `globals` containing the following properties: + +```js +{ + globals: { + Number, + String, + TypeError + } +} +``` + +Those specific functions will be used when throwing exceptions. + +Specific conversions may also accept other options, the details of which can be found below. + +## Conversions implemented + +Conversions for all of the basic types from the Web IDL specification are implemented: + +- [`any`](https://heycam.github.io/webidl/#es-any) +- [`undefined`](https://heycam.github.io/webidl/#es-undefined) +- [`boolean`](https://heycam.github.io/webidl/#es-boolean) +- [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter +- [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) +- [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) +- [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter +- [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) +- [`object`](https://heycam.github.io/webidl/#es-object) +- [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter + +Additionally, for convenience, the following derived type definitions are implemented: + +- [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter +- [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) +- [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) + +Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. + +### A note on the `long long` types + +The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers. Conversions are still accurate as we make use of BigInt in the conversion process, but in the case of `unsigned long long` we simply cannot represent some possible output values in JavaScript. For example, converting the JavaScript number `-1` to a Web IDL `unsigned long long` is supposed to produce the Web IDL value `18446744073709551615`. Since we are representing our Web IDL values in JavaScript, we can't represent `18446744073709551615`, so we instead the best we could do is `18446744073709551616` as the output. + +To mitigate this, we could return the raw BigInt value from the conversion function, but right now it is not implemented. If your use case requires such precision, [file an issue](https://github.com/jsdom/webidl-conversions/issues/new). + +On the other hand, `long long` conversion is always accurate, since the input value can never be more precise than the output value. + +### A note on `BufferSource` types + +All of the `BufferSource` types will throw when the relevant `ArrayBuffer` has been detached. This technically is not part of the [specified conversion algorithm](https://heycam.github.io/webidl/#es-buffer-source-types), but instead part of the [getting a reference/getting a copy](https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-reference%E2%91%A0) algorithms. We've consolidated them here for convenience and ease of implementation, but if there is a need to separate them in the future, please open an issue so we can investigate. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't use this + +Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/jsdom/jsdom) project. diff --git a/nodejs/node_modules/webidl-conversions/lib/index.js b/nodejs/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 00000000..0229347c --- /dev/null +++ b/nodejs/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,450 @@ +"use strict"; + +function makeException(ErrorType, message, options) { + if (options.globals) { + ErrorType = options.globals[ErrorType.name]; + } + return new ErrorType(`${options.context ? options.context : "Value"} ${message}.`); +} + +function toNumber(value, options) { + if (typeof value === "bigint") { + throw makeException(TypeError, "is a BigInt which cannot be converted to a number", options); + } + if (!options.globals) { + return Number(value); + } + return options.globals.Number(value); +} + +// Round x to the nearest integer, choosing the even integer if it lies halfway between two. +function evenRound(x) { + // There are four cases for numbers with fractional part being .5: + // + // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example + // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 + // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 + // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 + // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 + // (where n is a non-negative integer) + // + // Branch here for cases 1 and 4 + if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || + (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { + return censorNegativeZero(Math.floor(x)); + } + + return censorNegativeZero(Math.round(x)); +} + +function integerPart(n) { + return censorNegativeZero(Math.trunc(n)); +} + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function modulo(x, y) { + // https://tc39.github.io/ecma262/#eqn-modulo + // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos + const signMightNotMatch = x % y; + if (sign(y) !== sign(signMightNotMatch)) { + return signMightNotMatch + y; + } + return signMightNotMatch; +} + +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} + +function createIntegerConversion(bitLength, { unsigned }) { + let lowerBound, upperBound; + if (unsigned) { + lowerBound = 0; + upperBound = 2 ** bitLength - 1; + } else { + lowerBound = -(2 ** (bitLength - 1)); + upperBound = 2 ** (bitLength - 1) - 1; + } + + const twoToTheBitLength = 2 ** bitLength; + const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1); + + return (value, options = {}) => { + let x = toNumber(value, options); + x = censorNegativeZero(x); + + if (options.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", options); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw makeException( + TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, + options + ); + } + + return x; + } + + if (!Number.isNaN(x) && options.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + x = integerPart(x); + + // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if + // possible. Hopefully it's an optimization for the non-64-bitLength cases too. + if (x >= lowerBound && x <= upperBound) { + return x; + } + + // These will not work great for bitLength of 64, but oh well. See the README for more details. + x = modulo(x, twoToTheBitLength); + if (!unsigned && x >= twoToOneLessThanTheBitLength) { + return x - twoToTheBitLength; + } + return x; + }; +} + +function createLongLongConversion(bitLength, { unsigned }) { + const upperBound = Number.MAX_SAFE_INTEGER; + const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER; + const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; + + return (value, options = {}) => { + let x = toNumber(value, options); + x = censorNegativeZero(x); + + if (options.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", options); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw makeException( + TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, + options + ); + } + + return x; + } + + if (!Number.isNaN(x) && options.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + let xBigInt = BigInt(integerPart(x)); + xBigInt = asBigIntN(bitLength, xBigInt); + return Number(xBigInt); + }; +} + +exports.any = value => { + return value; +}; + +exports.undefined = () => { + return undefined; +}; + +exports.boolean = value => { + return Boolean(value); +}; + +exports.byte = createIntegerConversion(8, { unsigned: false }); +exports.octet = createIntegerConversion(8, { unsigned: true }); + +exports.short = createIntegerConversion(16, { unsigned: false }); +exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); + +exports.long = createIntegerConversion(32, { unsigned: false }); +exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); + +exports["long long"] = createLongLongConversion(64, { unsigned: false }); +exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); + +exports.double = (value, options = {}) => { + const x = toNumber(value, options); + + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", options); + } + + return x; +}; + +exports["unrestricted double"] = (value, options = {}) => { + const x = toNumber(value, options); + + return x; +}; + +exports.float = (value, options = {}) => { + const x = toNumber(value, options); + + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", options); + } + + if (Object.is(x, -0)) { + return x; + } + + const y = Math.fround(x); + + if (!Number.isFinite(y)) { + throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options); + } + + return y; +}; + +exports["unrestricted float"] = (value, options = {}) => { + const x = toNumber(value, options); + + if (isNaN(x)) { + return x; + } + + if (Object.is(x, -0)) { + return x; + } + + return Math.fround(x); +}; + +exports.DOMString = (value, options = {}) => { + if (options.treatNullAsEmptyString && value === null) { + return ""; + } + + if (typeof value === "symbol") { + throw makeException(TypeError, "is a symbol, which cannot be converted to a string", options); + } + + const StringCtor = options.globals ? options.globals.String : String; + return StringCtor(value); +}; + +exports.ByteString = (value, options = {}) => { + const x = exports.DOMString(value, options); + let c; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw makeException(TypeError, "is not a valid ByteString", options); + } + } + + return x; +}; + +exports.USVString = (value, options = {}) => { + const S = exports.DOMString(value, options); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + + return U.join(""); +}; + +exports.object = (value, options = {}) => { + if (value === null || (typeof value !== "object" && typeof value !== "function")) { + throw makeException(TypeError, "is not an object", options); + } + + return value; +}; + +const abByteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +const sabByteLengthGetter = + typeof SharedArrayBuffer === "function" ? + Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get : + null; + +function isNonSharedArrayBuffer(value) { + try { + // This will throw on SharedArrayBuffers, but not detached ArrayBuffers. + // (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678) + abByteLengthGetter.call(value); + + return true; + } catch { + return false; + } +} + +function isSharedArrayBuffer(value) { + try { + sabByteLengthGetter.call(value); + return true; + } catch { + return false; + } +} + +function isArrayBufferDetached(value) { + try { + // eslint-disable-next-line no-new + new Uint8Array(value); + return false; + } catch { + return true; + } +} + +exports.ArrayBuffer = (value, options = {}) => { + if (!isNonSharedArrayBuffer(value)) { + if (options.allowShared && !isSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", options); + } + throw makeException(TypeError, "is not an ArrayBuffer", options); + } + if (isArrayBufferDetached(value)) { + throw makeException(TypeError, "is a detached ArrayBuffer", options); + } + + return value; +}; + +const dvByteLengthGetter = + Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; +exports.DataView = (value, options = {}) => { + try { + dvByteLengthGetter.call(value); + } catch (e) { + throw makeException(TypeError, "is not a DataView", options); + } + + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", options); + } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is backed by a detached ArrayBuffer", options); + } + + return value; +}; + +// Returns the unforgeable `TypedArray` constructor name or `undefined`, +// if the `this` value isn't a valid `TypedArray` object. +// +// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag +const typedArrayNameGetter = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf(Uint8Array).prototype, + Symbol.toStringTag +).get; +[ + Int8Array, + Int16Array, + Int32Array, + Uint8Array, + Uint16Array, + Uint32Array, + Uint8ClampedArray, + Float32Array, + Float64Array +].forEach(func => { + const { name } = func; + const article = /^[AEIOU]/u.test(name) ? "an" : "a"; + exports[name] = (value, options = {}) => { + if (!ArrayBuffer.isView(value) || typedArrayNameGetter.call(value) !== name) { + throw makeException(TypeError, `is not ${article} ${name} object`, options); + } + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + + return value; + }; +}); + +// Common definitions + +exports.ArrayBufferView = (value, options = {}) => { + if (!ArrayBuffer.isView(value)) { + throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", options); + } + + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + return value; +}; + +exports.BufferSource = (value, options = {}) => { + if (ArrayBuffer.isView(value)) { + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + return value; + } + + if (!options.allowShared && !isNonSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer or a view on one", options); + } + if (options.allowShared && !isSharedArrayBuffer(value) && !isNonSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBuffer, or a view on one", options); + } + if (isArrayBufferDetached(value)) { + throw makeException(TypeError, "is a detached ArrayBuffer", options); + } + + return value; +}; + +exports.DOMTimeStamp = exports["unsigned long long"]; diff --git a/nodejs/node_modules/webidl-conversions/package.json b/nodejs/node_modules/webidl-conversions/package.json new file mode 100644 index 00000000..20747bb4 --- /dev/null +++ b/nodejs/node_modules/webidl-conversions/package.json @@ -0,0 +1,35 @@ +{ + "name": "webidl-conversions", + "version": "7.0.0", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "lint": "eslint .", + "test": "mocha test/*.js", + "test-no-sab": "mocha --parallel --jobs 2 --require test/helpers/delete-sab.js test/*.js", + "coverage": "nyc mocha test/*.js" + }, + "_scripts_comments": { + "test-no-sab": "Node.js internals are broken by deleting SharedArrayBuffer if you run tests on the main thread. Using Mocha's parallel mode avoids this." + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "@domenic/eslint-config": "^1.3.0", + "eslint": "^7.32.0", + "mocha": "^9.1.1", + "nyc": "^15.1.0" + }, + "engines": { + "node": ">=12" + } +} diff --git a/nodejs/node_modules/whatwg-url/LICENSE.txt b/nodejs/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 00000000..8e8c25c3 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sebastian Mayr + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/whatwg-url/README.md b/nodejs/node_modules/whatwg-url/README.md new file mode 100644 index 00000000..07a5fa53 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/README.md @@ -0,0 +1,106 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/jsdom/jsdom). + +## Specification conformance + +whatwg-url is currently up to date with the URL spec up to commit [eee49fd](https://github.com/whatwg/url/commit/eee49fdf4f99d59f717cbeb0bce29fda930196d4). + +For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). + +whatwg-url does not yet implement any encoding handling beyond UTF-8. That is, the _encoding override_ parameter does not exist in our API. + +## API + +### The `URL` and `URLSearchParams` classes + +The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [URL path serializer](https://url.spec.whatwg.org/#url-path-serializer): `serializePath(urlRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Has an opaque path](https://url.spec.whatwg.org/#url-opaque-path): `hasAnOpaquePath(urlRecord)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` +- [Percent decode bytes](https://url.spec.whatwg.org/#percent-decode): `percentDecodeBytes(uint8Array)` +- [Percent decode a string](https://url.spec.whatwg.org/#percent-decode-string): `percentDecodeString(string)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"opaque path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array of strings, or a string) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. + +### `whatwg-url/webidl2js-wrapper` module + +This module exports the `URL` and `URLSearchParams` [interface wrappers API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). + +## Development instructions + +First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: + + npm install + +To run tests: + + npm test + +To generate a coverage report: + + npm run coverage + +To build and run the live viewer: + + npm run prepare + npm run build-live-viewer + +Serve the contents of the `live-viewer` directory using any web server. + +## Supporting whatwg-url + +The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: + +- [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. +- Contributing directly to the project. diff --git a/nodejs/node_modules/whatwg-url/index.js b/nodejs/node_modules/whatwg-url/index.js new file mode 100644 index 00000000..c470e48e --- /dev/null +++ b/nodejs/node_modules/whatwg-url/index.js @@ -0,0 +1,27 @@ +"use strict"; + +const { URL, URLSearchParams } = require("./webidl2js-wrapper"); +const urlStateMachine = require("./lib/url-state-machine"); +const percentEncoding = require("./lib/percent-encoding"); + +const sharedGlobalObject = { Array, Object, Promise, String, TypeError }; +URL.install(sharedGlobalObject, ["Window"]); +URLSearchParams.install(sharedGlobalObject, ["Window"]); + +exports.URL = sharedGlobalObject.URL; +exports.URLSearchParams = sharedGlobalObject.URLSearchParams; + +exports.parseURL = urlStateMachine.parseURL; +exports.basicURLParse = urlStateMachine.basicURLParse; +exports.serializeURL = urlStateMachine.serializeURL; +exports.serializePath = urlStateMachine.serializePath; +exports.serializeHost = urlStateMachine.serializeHost; +exports.serializeInteger = urlStateMachine.serializeInteger; +exports.serializeURLOrigin = urlStateMachine.serializeURLOrigin; +exports.setTheUsername = urlStateMachine.setTheUsername; +exports.setThePassword = urlStateMachine.setThePassword; +exports.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort; +exports.hasAnOpaquePath = urlStateMachine.hasAnOpaquePath; + +exports.percentDecodeString = percentEncoding.percentDecodeString; +exports.percentDecodeBytes = percentEncoding.percentDecodeBytes; diff --git a/nodejs/node_modules/whatwg-url/lib/Function.js b/nodejs/node_modules/whatwg-url/lib/Function.js new file mode 100644 index 00000000..ea8712fd --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/Function.js @@ -0,0 +1,42 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new globalObject.TypeError(context + " is not a function"); + } + + function invokeTheCallbackFunction(...args) { + const thisArg = utils.tryWrapperForImpl(this); + let callResult; + + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } + + callResult = Reflect.apply(value, thisArg, args); + + callResult = conversions["any"](callResult, { context: context, globals: globalObject }); + + return callResult; + } + + invokeTheCallbackFunction.construct = (...args) => { + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } + + let callResult = Reflect.construct(value, args); + + callResult = conversions["any"](callResult, { context: context, globals: globalObject }); + + return callResult; + }; + + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; + + return invokeTheCallbackFunction; +}; diff --git a/nodejs/node_modules/whatwg-url/lib/URL-impl.js b/nodejs/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 00000000..eb66cae5 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,246 @@ +"use strict"; +const usm = require("./url-state-machine"); +const urlencoded = require("./urlencoded"); +const URLSearchParams = require("./URLSearchParams"); + +exports.implementation = class URLImpl { + // Unlike the spec, we duplicate some code between the constructor and canParse, because we want to give useful error + // messages in the constructor that distinguish between the different causes of failure. + constructor(globalObject, constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === null) { + throw new TypeError(`Invalid base URL: ${base}`); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${url}`); + } + + const query = parsedURL.query !== null ? parsedURL.query : ""; + + this._url = parsedURL; + + // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips + // question mark by default. Therefore the doNotStripQMark hack is used. + this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true }); + this._query._url = this; + } + + static canParse(url, base) { + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === null) { + return false; + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === null) { + return false; + } + + return true; + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${v}`); + } + + this._url = parsedURL; + + this._query._list.splice(0); + const { query } = parsedURL; + if (query !== null) { + this._query._list = urlencoded.parseUrlencodedString(query); + } + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return `${this._url.scheme}:`; + } + + set protocol(v) { + usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return `${usm.serializeHost(url.host)}:${usm.serializeInteger(url.port)}`; + } + + set host(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + return usm.serializePath(this._url); + } + + set pathname(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return `?${this._url.query}`; + } + + set search(v) { + const url = this._url; + + if (v === "") { + url.query = null; + this._query._list = []; + this._potentiallyStripTrailingSpacesFromAnOpaquePath(); + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + this._query._list = urlencoded.parseUrlencodedString(input); + } + + get searchParams() { + return this._query; + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return `#${this._url.fragment}`; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + this._potentiallyStripTrailingSpacesFromAnOpaquePath(); + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } + + _potentiallyStripTrailingSpacesFromAnOpaquePath() { + if (!usm.hasAnOpaquePath(this._url)) { + return; + } + + if (this._url.fragment !== null) { + return; + } + + if (this._url.query !== null) { + return; + } + + this._url.path = this._url.path.replace(/\u0020+$/u, ""); + } +}; diff --git a/nodejs/node_modules/whatwg-url/lib/URL.js b/nodejs/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 00000000..ea5e6166 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,471 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; + +const interfaceName = "URL"; + +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new globalObject.TypeError(`${context} is not of type 'URL'.`); +}; + +function makeWrapper(globalObject, newTarget) { + let proto; + if (newTarget !== undefined) { + proto = newTarget.prototype; + } + + if (!utils.isObject(proto)) { + proto = globalObject[ctorRegistrySymbol]["URL"].prototype; + } + + return Object.create(proto); +} + +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; + +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; + +exports._internalSetup = (wrapper, globalObject) => {}; + +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; + +exports.new = (globalObject, newTarget) => { + const wrapper = makeWrapper(globalObject, newTarget); + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; + +const exposed = new Set(["Window", "Worker"]); + +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } + + const ctorRegistry = utils.initCtorRegistry(globalObject); + class URL { + constructor(url) { + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to construct 'URL': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URL': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URL': parameter 2", + globals: globalObject + }); + } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } + + toJSON() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'toJSON' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol].toJSON(); + } + + get href() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get href' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["href"]; + } + + set href(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set href' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'href' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["href"] = V; + } + + toString() { + const esValue = this; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'toString' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["href"]; + } + + get origin() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get origin' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["origin"]; + } + + get protocol() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get protocol' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["protocol"]; + } + + set protocol(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set protocol' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'protocol' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["protocol"] = V; + } + + get username() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get username' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["username"]; + } + + set username(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set username' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'username' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["username"] = V; + } + + get password() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get password' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["password"]; + } + + set password(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set password' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'password' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["password"] = V; + } + + get host() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get host' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["host"]; + } + + set host(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set host' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'host' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["host"] = V; + } + + get hostname() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get hostname' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["hostname"]; + } + + set hostname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set hostname' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'hostname' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["hostname"] = V; + } + + get port() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get port' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["port"]; + } + + set port(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set port' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'port' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["port"] = V; + } + + get pathname() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get pathname' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["pathname"]; + } + + set pathname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set pathname' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'pathname' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["pathname"] = V; + } + + get search() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get search' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["search"]; + } + + set search(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set search' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'search' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["search"] = V; + } + + get searchParams() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get searchParams' called on an object that is not a valid instance of URL."); + } + + return utils.getSameObject(this, "searchParams", () => { + return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]); + }); + } + + get hash() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get hash' called on an object that is not a valid instance of URL."); + } + + return esValue[implSymbol]["hash"]; + } + + set hash(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set hash' called on an object that is not a valid instance of URL."); + } + + V = conversions["USVString"](V, { + context: "Failed to set the 'hash' property on 'URL': The provided value", + globals: globalObject + }); + + esValue[implSymbol]["hash"] = V; + } + + static canParse(url) { + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'canParse' on 'URL': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'canParse' on 'URL': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'canParse' on 'URL': parameter 2", + globals: globalObject + }); + } + args.push(curArg); + } + return Impl.implementation.canParse(...args); + } + } + Object.defineProperties(URL.prototype, { + toJSON: { enumerable: true }, + href: { enumerable: true }, + toString: { enumerable: true }, + origin: { enumerable: true }, + protocol: { enumerable: true }, + username: { enumerable: true }, + password: { enumerable: true }, + host: { enumerable: true }, + hostname: { enumerable: true }, + port: { enumerable: true }, + pathname: { enumerable: true }, + search: { enumerable: true }, + searchParams: { enumerable: true }, + hash: { enumerable: true }, + [Symbol.toStringTag]: { value: "URL", configurable: true } + }); + Object.defineProperties(URL, { canParse: { enumerable: true } }); + ctorRegistry[interfaceName] = URL; + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URL + }); + + if (globalNames.includes("Window")) { + Object.defineProperty(globalObject, "webkitURL", { + configurable: true, + writable: true, + value: URL + }); + } +}; + +const Impl = require("./URL-impl.js"); diff --git a/nodejs/node_modules/whatwg-url/lib/URLSearchParams-impl.js b/nodejs/node_modules/whatwg-url/lib/URLSearchParams-impl.js new file mode 100644 index 00000000..934c4ff1 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/URLSearchParams-impl.js @@ -0,0 +1,139 @@ +"use strict"; +const urlencoded = require("./urlencoded"); + +exports.implementation = class URLSearchParamsImpl { + constructor(globalObject, constructorArgs, { doNotStripQMark = false }) { + let init = constructorArgs[0]; + this._list = []; + this._url = null; + + if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { + init = init.slice(1); + } + + if (Array.isArray(init)) { + for (const pair of init) { + if (pair.length !== 2) { + throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " + + "contain exactly two elements."); + } + this._list.push([pair[0], pair[1]]); + } + } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { + for (const name of Object.keys(init)) { + const value = init[name]; + this._list.push([name, value]); + } + } else { + this._list = urlencoded.parseUrlencodedString(init); + } + } + + _updateSteps() { + if (this._url !== null) { + let serializedQuery = urlencoded.serializeUrlencoded(this._list); + if (serializedQuery === "") { + serializedQuery = null; + } + + this._url._url.query = serializedQuery; + + if (serializedQuery === null) { + this._url._potentiallyStripTrailingSpacesFromAnOpaquePath(); + } + } + } + + get size() { + return this._list.length; + } + + append(name, value) { + this._list.push([name, value]); + this._updateSteps(); + } + + delete(name, value) { + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name && (value === undefined || this._list[i][1] === value)) { + this._list.splice(i, 1); + } else { + i++; + } + } + this._updateSteps(); + } + + get(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return tuple[1]; + } + } + return null; + } + + getAll(name) { + const output = []; + for (const tuple of this._list) { + if (tuple[0] === name) { + output.push(tuple[1]); + } + } + return output; + } + + has(name, value) { + for (const tuple of this._list) { + if (tuple[0] === name && (value === undefined || tuple[1] === value)) { + return true; + } + } + return false; + } + + set(name, value) { + let found = false; + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + if (found) { + this._list.splice(i, 1); + } else { + found = true; + this._list[i][1] = value; + i++; + } + } else { + i++; + } + } + if (!found) { + this._list.push([name, value]); + } + this._updateSteps(); + } + + sort() { + this._list.sort((a, b) => { + if (a[0] < b[0]) { + return -1; + } + if (a[0] > b[0]) { + return 1; + } + return 0; + }); + + this._updateSteps(); + } + + [Symbol.iterator]() { + return this._list[Symbol.iterator](); + } + + toString() { + return urlencoded.serializeUrlencoded(this._list); + } +}; diff --git a/nodejs/node_modules/whatwg-url/lib/URLSearchParams.js b/nodejs/node_modules/whatwg-url/lib/URLSearchParams.js new file mode 100644 index 00000000..a55587fa --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/URLSearchParams.js @@ -0,0 +1,505 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +const Function = require("./Function.js"); +const newObjectInRealm = utils.newObjectInRealm; +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; + +const interfaceName = "URLSearchParams"; + +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new globalObject.TypeError(`${context} is not of type 'URLSearchParams'.`); +}; + +exports.createDefaultIterator = (globalObject, target, kind) => { + const ctorRegistry = globalObject[ctorRegistrySymbol]; + const iteratorPrototype = ctorRegistry["URLSearchParams Iterator"]; + const iterator = Object.create(iteratorPrototype); + Object.defineProperty(iterator, utils.iterInternalSymbol, { + value: { target, kind, index: 0 }, + configurable: true + }); + return iterator; +}; + +function makeWrapper(globalObject, newTarget) { + let proto; + if (newTarget !== undefined) { + proto = newTarget.prototype; + } + + if (!utils.isObject(proto)) { + proto = globalObject[ctorRegistrySymbol]["URLSearchParams"].prototype; + } + + return Object.create(proto); +} + +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; + +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; + +exports._internalSetup = (wrapper, globalObject) => {}; + +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; + +exports.new = (globalObject, newTarget) => { + const wrapper = makeWrapper(globalObject, newTarget); + + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); + + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; + +const exposed = new Set(["Window", "Worker"]); + +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } + + const ctorRegistry = utils.initCtorRegistry(globalObject); + class URLSearchParams { + constructor() { + const args = []; + { + let curArg = arguments[0]; + if (curArg !== undefined) { + if (utils.isObject(curArg)) { + if (curArg[Symbol.iterator] !== undefined) { + if (!utils.isObject(curArg)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object." + ); + } else { + const V = []; + const tmp = curArg; + for (let nextItem of tmp) { + if (!utils.isObject(nextItem)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + " is not an iterable object." + ); + } else { + const V = []; + const tmp = nextItem; + for (let nextItem of tmp) { + nextItem = conversions["USVString"](nextItem, { + context: + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + "'s element", + globals: globalObject + }); + + V.push(nextItem); + } + nextItem = V; + } + + V.push(nextItem); + } + curArg = V; + } + } else { + if (!utils.isObject(curArg)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object." + ); + } else { + const result = Object.create(null); + for (const key of Reflect.ownKeys(curArg)) { + const desc = Object.getOwnPropertyDescriptor(curArg, key); + if (desc && desc.enumerable) { + let typedKey = key; + + typedKey = conversions["USVString"](typedKey, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key", + globals: globalObject + }); + + let typedValue = curArg[key]; + + typedValue = conversions["USVString"](typedValue, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value", + globals: globalObject + }); + + result[typedKey] = typedValue; + } + } + curArg = result; + } + } + } else { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URLSearchParams': parameter 1", + globals: globalObject + }); + } + } else { + curArg = ""; + } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } + + append(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'append' called on an object that is not a valid instance of URLSearchParams." + ); + } + + if (arguments.length < 2) { + throw new globalObject.TypeError( + `Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].append(...args)); + } + + delete(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'delete' called on an object that is not a valid instance of URLSearchParams." + ); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'delete' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + } + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].delete(...args)); + } + + get(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'get' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return esValue[implSymbol].get(...args); + } + + getAll(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'getAll' called on an object that is not a valid instance of URLSearchParams." + ); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args)); + } + + has(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'has' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'has' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'has' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + } + args.push(curArg); + } + return esValue[implSymbol].has(...args); + } + + set(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set' called on an object that is not a valid instance of URLSearchParams."); + } + + if (arguments.length < 2) { + throw new globalObject.TypeError( + `Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].set(...args)); + } + + sort() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'sort' called on an object that is not a valid instance of URLSearchParams."); + } + + return utils.tryWrapperForImpl(esValue[implSymbol].sort()); + } + + toString() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'toString' called on an object that is not a valid instance of URLSearchParams." + ); + } + + return esValue[implSymbol].toString(); + } + + keys() { + if (!exports.is(this)) { + throw new globalObject.TypeError("'keys' called on an object that is not a valid instance of URLSearchParams."); + } + return exports.createDefaultIterator(globalObject, this, "key"); + } + + values() { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'values' called on an object that is not a valid instance of URLSearchParams." + ); + } + return exports.createDefaultIterator(globalObject, this, "value"); + } + + entries() { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'entries' called on an object that is not a valid instance of URLSearchParams." + ); + } + return exports.createDefaultIterator(globalObject, this, "key+value"); + } + + forEach(callback) { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'forEach' called on an object that is not a valid instance of URLSearchParams." + ); + } + if (arguments.length < 1) { + throw new globalObject.TypeError( + "Failed to execute 'forEach' on 'iterable': 1 argument required, but only 0 present." + ); + } + callback = Function.convert(globalObject, callback, { + context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1" + }); + const thisArg = arguments[1]; + let pairs = Array.from(this[implSymbol]); + let i = 0; + while (i < pairs.length) { + const [key, value] = pairs[i].map(utils.tryWrapperForImpl); + callback.call(thisArg, value, key, this); + pairs = Array.from(this[implSymbol]); + i++; + } + } + + get size() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'get size' called on an object that is not a valid instance of URLSearchParams." + ); + } + + return esValue[implSymbol]["size"]; + } + } + Object.defineProperties(URLSearchParams.prototype, { + append: { enumerable: true }, + delete: { enumerable: true }, + get: { enumerable: true }, + getAll: { enumerable: true }, + has: { enumerable: true }, + set: { enumerable: true }, + sort: { enumerable: true }, + toString: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true }, + forEach: { enumerable: true }, + size: { enumerable: true }, + [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true }, + [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true } + }); + ctorRegistry[interfaceName] = URLSearchParams; + + ctorRegistry["URLSearchParams Iterator"] = Object.create(ctorRegistry["%IteratorPrototype%"], { + [Symbol.toStringTag]: { + configurable: true, + value: "URLSearchParams Iterator" + } + }); + utils.define(ctorRegistry["URLSearchParams Iterator"], { + next() { + const internal = this && this[utils.iterInternalSymbol]; + if (!internal) { + throw new globalObject.TypeError("next() called on a value that is not a URLSearchParams iterator object"); + } + + const { target, kind, index } = internal; + const values = Array.from(target[implSymbol]); + const len = values.length; + if (index >= len) { + return newObjectInRealm(globalObject, { value: undefined, done: true }); + } + + const pair = values[index]; + internal.index = index + 1; + return newObjectInRealm(globalObject, utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind)); + } + }); + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URLSearchParams + }); +}; + +const Impl = require("./URLSearchParams-impl.js"); diff --git a/nodejs/node_modules/whatwg-url/lib/VoidFunction.js b/nodejs/node_modules/whatwg-url/lib/VoidFunction.js new file mode 100644 index 00000000..9a00672a --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/VoidFunction.js @@ -0,0 +1,26 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); + +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new globalObject.TypeError(context + " is not a function"); + } + + function invokeTheCallbackFunction() { + const thisArg = utils.tryWrapperForImpl(this); + let callResult; + + callResult = Reflect.apply(value, thisArg, []); + } + + invokeTheCallbackFunction.construct = () => { + let callResult = Reflect.construct(value, []); + }; + + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; + + return invokeTheCallbackFunction; +}; diff --git a/nodejs/node_modules/whatwg-url/lib/encoding.js b/nodejs/node_modules/whatwg-url/lib/encoding.js new file mode 100644 index 00000000..cb66b8f1 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/encoding.js @@ -0,0 +1,16 @@ +"use strict"; +const utf8Encoder = new TextEncoder(); +const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); + +function utf8Encode(string) { + return utf8Encoder.encode(string); +} + +function utf8DecodeWithoutBOM(bytes) { + return utf8Decoder.decode(bytes); +} + +module.exports = { + utf8Encode, + utf8DecodeWithoutBOM +}; diff --git a/nodejs/node_modules/whatwg-url/lib/infra.js b/nodejs/node_modules/whatwg-url/lib/infra.js new file mode 100644 index 00000000..4a984a3b --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/infra.js @@ -0,0 +1,26 @@ +"use strict"; + +// Note that we take code points as JS numbers, not JS strings. + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +module.exports = { + isASCIIDigit, + isASCIIAlpha, + isASCIIAlphanumeric, + isASCIIHex +}; diff --git a/nodejs/node_modules/whatwg-url/lib/percent-encoding.js b/nodejs/node_modules/whatwg-url/lib/percent-encoding.js new file mode 100644 index 00000000..f8308673 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/percent-encoding.js @@ -0,0 +1,142 @@ +"use strict"; +const { isASCIIHex } = require("./infra"); +const { utf8Encode } = require("./encoding"); + +function p(char) { + return char.codePointAt(0); +} + +// https://url.spec.whatwg.org/#percent-encode +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = `0${hex}`; + } + + return `%${hex}`; +} + +// https://url.spec.whatwg.org/#percent-decode +function percentDecodeBytes(input) { + const output = new Uint8Array(input.byteLength); + let outputIndex = 0; + for (let i = 0; i < input.byteLength; ++i) { + const byte = input[i]; + if (byte !== 0x25) { + output[outputIndex++] = byte; + } else if (byte === 0x25 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) { + output[outputIndex++] = byte; + } else { + const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16); + output[outputIndex++] = bytePoint; + i += 2; + } + } + + return output.slice(0, outputIndex); +} + +// https://url.spec.whatwg.org/#string-percent-decode +function percentDecodeString(input) { + const bytes = utf8Encode(input); + return percentDecodeBytes(bytes); +} + +// https://url.spec.whatwg.org/#c0-control-percent-encode-set +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +// https://url.spec.whatwg.org/#fragment-percent-encode-set +const extraFragmentPercentEncodeSet = new Set([p(" "), p("\""), p("<"), p(">"), p("`")]); +function isFragmentPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#query-percent-encode-set +const extraQueryPercentEncodeSet = new Set([p(" "), p("\""), p("#"), p("<"), p(">")]); +function isQueryPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#special-query-percent-encode-set +function isSpecialQueryPercentEncode(c) { + return isQueryPercentEncode(c) || c === p("'"); +} + +// https://url.spec.whatwg.org/#path-percent-encode-set +const extraPathPercentEncodeSet = new Set([p("?"), p("`"), p("{"), p("}")]); +function isPathPercentEncode(c) { + return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#userinfo-percent-encode-set +const extraUserinfoPercentEncodeSet = + new Set([p("/"), p(":"), p(";"), p("="), p("@"), p("["), p("\\"), p("]"), p("^"), p("|")]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#component-percent-encode-set +const extraComponentPercentEncodeSet = new Set([p("$"), p("%"), p("&"), p("+"), p(",")]); +function isComponentPercentEncode(c) { + return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set +const extraURLEncodedPercentEncodeSet = new Set([p("!"), p("'"), p("("), p(")"), p("~")]); +function isURLEncodedPercentEncode(c) { + return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#code-point-percent-encode-after-encoding +// https://url.spec.whatwg.org/#utf-8-percent-encode +// Assuming encoding is always utf-8 allows us to trim one of the logic branches. TODO: support encoding. +// The "-Internal" variant here has code points as JS strings. The external version used by other files has code points +// as JS numbers, like the rest of the codebase. +function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) { + const bytes = utf8Encode(codePoint); + let output = ""; + for (const byte of bytes) { + // Our percentEncodePredicate operates on bytes, not code points, so this is slightly different from the spec. + if (!percentEncodePredicate(byte)) { + output += String.fromCharCode(byte); + } else { + output += percentEncode(byte); + } + } + + return output; +} + +function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) { + return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate); +} + +// https://url.spec.whatwg.org/#string-percent-encode-after-encoding +// https://url.spec.whatwg.org/#string-utf-8-percent-encode +function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) { + let output = ""; + for (const codePoint of input) { + if (spaceAsPlus && codePoint === " ") { + output += "+"; + } else { + output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate); + } + } + return output; +} + +module.exports = { + isC0ControlPercentEncode, + isFragmentPercentEncode, + isQueryPercentEncode, + isSpecialQueryPercentEncode, + isPathPercentEncode, + isUserinfoPercentEncode, + isURLEncodedPercentEncode, + percentDecodeString, + percentDecodeBytes, + utf8PercentEncodeString, + utf8PercentEncodeCodePoint +}; diff --git a/nodejs/node_modules/whatwg-url/lib/url-state-machine.js b/nodejs/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 00000000..99033921 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1247 @@ +"use strict"; +const tr46 = require("tr46"); + +const infra = require("./infra"); +const { utf8DecodeWithoutBOM } = require("./encoding"); +const { percentDecodeString, utf8PercentEncodeCodePoint, utf8PercentEncodeString, isC0ControlPercentEncode, + isFragmentPercentEncode, isQueryPercentEncode, isSpecialQueryPercentEncode, isPathPercentEncode, + isUserinfoPercentEncode } = require("./percent-encoding"); + +function p(char) { + return char.codePointAt(0); +} + +const specialSchemes = { + ftp: 21, + file: null, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return [...str].length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return infra.isASCIIAlpha(cp1) && (cp2 === p(":") || cp2 === p("|")); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function containsForbiddenDomainCodePoint(string) { + return containsForbiddenHostCodePoint(string) || string.search(/[\u0000-\u001F]|%|\u007F/u) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function isNotSpecial(url) { + return !isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function parseIPv4Number(input) { + if (input === "") { + return failure; + } + + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + let regex = /[^0-7]/u; + if (R === 10) { + regex = /[^0-9]/u; + } + if (R === 16) { + regex = /[^0-9A-Fa-f]/u; + } + + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return failure; + } + + const numbers = []; + for (const part of parts) { + const n = parseIPv4Number(part); + if (n === failure) { + return failure; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * 256 ** (3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = `.${output}`; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = Array.from(input, c => c.codePointAt(0)); + + if (input[pointer] === p(":")) { + if (input[pointer + 1] !== p(":")) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === p(":")) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && infra.isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === p(".")) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === p(".") && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!infra.isASCIIDigit(input[pointer])) { + return failure; + } + + while (infra.isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === p(":")) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const compress = findLongestZeroSequence(address); + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isNotSpecialArg = false) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (isNotSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8DecodeWithoutBOM(percentDecodeString(input)); + const asciiDomain = domainToASCII(domain); + if (asciiDomain === failure) { + return failure; + } + + if (containsForbiddenDomainCodePoint(asciiDomain)) { + return failure; + } + + if (endsInANumber(asciiDomain)) { + return parseIPv4(asciiDomain); + } + + return asciiDomain; +} + +function endsInANumber(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length === 1) { + return false; + } + parts.pop(); + } + + const last = parts[parts.length - 1]; + if (parseIPv4Number(last) !== failure) { + return true; + } + + if (/^[0-9]+$/u.test(last)) { + return true; + } + + return false; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePoint(input)) { + return failure; + } + + return utf8PercentEncodeString(input, isC0ControlPercentEncode); +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + return currStart; + } + + return maxIdx; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return `[${serializeIPv6(host)}]`; + } + + return host; +} + +function domainToASCII(domain, beStrict = false) { + const result = tr46.toASCII(domain, { + checkBidi: true, + checkHyphens: false, + checkJoiners: true, + useSTD3ASCIIRules: beStrict, + verifyDNSLength: beStrict + }); + if (result === null || result === "") { + return failure; + } + return result; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/ug, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/ug, ""); +} + +function shortenPath(url) { + const { path } = url; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.scheme === "file"; +} + +function hasAnOpaquePath(url) { + return typeof url.path === "string"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/u.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = Array.from(this.input, c => c.codePointAt(0)); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this[`parse ${this.state}`](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (infra.isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (infra.isASCIIAlphanumeric(c) || c === p("+") || c === p("-") || c === p(".")) { + this.buffer += cStr.toLowerCase(); + } else if (c === p(":")) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && this.url.host === "") { + return false; + } + } + this.url.scheme = this.buffer; + if (this.stateOverride) { + if (this.url.port === defaultPort(this.url.scheme)) { + this.url.port = null; + } + return false; + } + this.buffer = ""; + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== p("/") || this.input[this.pointer + 2] !== p("/")) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === p("/")) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.path = ""; + this.state = "opaque path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (hasAnOpaquePath(this.base) && c !== p("#"))) { + return failure; + } else if (hasAnOpaquePath(this.base) && c === p("#")) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path; + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === p("/") && this.input[this.pointer + 1] === p("/")) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === p("/")) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (c === p("/")) { + this.state = "relative slash"; + } else if (isSpecial(this.url) && c === p("\\")) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + this.url.path.pop(); + this.state = "path"; + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === p("/") || c === p("\\"))) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === p("/")) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === p("/") && this.input[this.pointer + 1] === p("/")) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== p("/") && c !== p("\\")) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === p("@")) { + this.parseError = true; + if (this.atFlag) { + this.buffer = `%40${this.buffer}`; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === p(":") && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\"))) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === p(":") && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + if (this.stateOverride === "hostname") { + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\"))) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === p("[")) { + this.arrFlag = true; + } else if (c === p("]")) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (infra.isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\")) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > 2 ** 16 - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([p("/"), p("\\"), p("?"), p("#")]); + +function startsWithWindowsDriveLetter(input, pointer) { + const length = input.length - pointer; + return length >= 2 && + isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && + (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); +} + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + this.url.host = ""; + + if (c === p("/") || c === p("\\")) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { + shortenPath(this.url); + } else { + this.parseError = true; + this.url.path = []; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === p("/") || c === p("\\")) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (!startsWithWindowsDriveLetter(this.input, this.pointer) && + isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } + this.url.host = this.base.host; + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === p("/") || c === p("\\") || c === p("?") || c === p("#")) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "path"; + + if (c !== p("/") && c !== p("\\")) { + --this.pointer; + } + } else if (!this.stateOverride && c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== p("/")) { + --this.pointer; + } + } else if (this.stateOverride && this.url.host === null) { + this.url.path.push(""); + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === p("/") || (isSpecial(this.url) && c === p("\\")) || + (!this.stateOverride && (c === p("?") || c === p("#")))) { + if (isSpecial(this.url) && c === p("\\")) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== p("/") && + !(isSpecial(this.url) && c === p("\\"))) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + this.buffer = `${this.buffer[0]}:`; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } + if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse opaque path"] = function parseOpaquePath(c) { + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== p("%")) { + this.parseError = true; + } + + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + if ((!this.stateOverride && c === p("#")) || isNaN(c)) { + const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode; + this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate); + + this.buffer = ""; + + if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = `${url.scheme}:`; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += `:${url.password}`; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += `:${url.port}`; + } + } + + if (url.host === null && !hasAnOpaquePath(url) && url.path.length > 1 && url.path[0] === "") { + output += "/."; + } + output += serializePath(url); + + if (url.query !== null) { + output += `?${url.query}`; + } + + if (!excludeFragment && url.fragment !== null) { + output += `#${url.fragment}`; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = `${tuple.scheme}://`; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += `:${tuple.port}`; + } + + return result; +} + +function serializePath(url) { + if (hasAnOpaquePath(url)) { + return url.path; + } + + let output = ""; + for (const segment of url.path) { + output += `/${segment}`; + } + return output; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializePath = serializePath; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": { + const pathURL = module.exports.parseURL(serializePath(url)); + if (pathURL === null) { + return "null"; + } + if (pathURL.scheme !== "http" && pathURL.scheme !== "https") { + return "null"; + } + return module.exports.serializeURLOrigin(pathURL); + } + case "ftp": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // The spec says: + // > Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin. + // Browsers tested so far: + // - Chrome says "file://", but treats file: URLs as cross-origin for most (all?) purposes; see e.g. + // https://bugs.chromium.org/p/chromium/issues/detail?id=37586 + // - Firefox says "null", but treats file: URLs as same-origin sometimes based on directory stuff; see + // https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs + return "null"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return null; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode); +}; + +module.exports.setThePassword = function (url, password) { + url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode); +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.hasAnOpaquePath = hasAnOpaquePath; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/nodejs/node_modules/whatwg-url/lib/urlencoded.js b/nodejs/node_modules/whatwg-url/lib/urlencoded.js new file mode 100644 index 00000000..e7230637 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/urlencoded.js @@ -0,0 +1,106 @@ +"use strict"; +const { utf8Encode, utf8DecodeWithoutBOM } = require("./encoding"); +const { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = require("./percent-encoding"); + +function p(char) { + return char.codePointAt(0); +} + +// https://url.spec.whatwg.org/#concept-urlencoded-parser +function parseUrlencoded(input) { + const sequences = strictlySplitByteSequence(input, p("&")); + const output = []; + for (const bytes of sequences) { + if (bytes.length === 0) { + continue; + } + + let name, value; + const indexOfEqual = bytes.indexOf(p("=")); + + if (indexOfEqual >= 0) { + name = bytes.slice(0, indexOfEqual); + value = bytes.slice(indexOfEqual + 1); + } else { + name = bytes; + value = new Uint8Array(0); + } + + name = replaceByteInByteSequence(name, 0x2B, 0x20); + value = replaceByteInByteSequence(value, 0x2B, 0x20); + + const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name)); + const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value)); + + output.push([nameString, valueString]); + } + return output; +} + +// https://url.spec.whatwg.org/#concept-urlencoded-string-parser +function parseUrlencodedString(input) { + return parseUrlencoded(utf8Encode(input)); +} + +// https://url.spec.whatwg.org/#concept-urlencoded-serializer +function serializeUrlencoded(tuples, encodingOverride = undefined) { + let encoding = "utf-8"; + if (encodingOverride !== undefined) { + // TODO "get the output encoding", i.e. handle encoding labels vs. names. + encoding = encodingOverride; + } + + let output = ""; + for (const [i, tuple] of tuples.entries()) { + // TODO: handle encoding override + + const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true); + + let value = tuple[1]; + if (tuple.length > 2 && tuple[2] !== undefined) { + if (tuple[2] === "hidden" && name === "_charset_") { + value = encoding; + } else if (tuple[2] === "file") { + // value is a File object + value = value.name; + } + } + + value = utf8PercentEncodeString(value, isURLEncodedPercentEncode, true); + + if (i !== 0) { + output += "&"; + } + output += `${name}=${value}`; + } + return output; +} + +function strictlySplitByteSequence(buf, cp) { + const list = []; + let last = 0; + let i = buf.indexOf(cp); + while (i >= 0) { + list.push(buf.slice(last, i)); + last = i + 1; + i = buf.indexOf(cp, last); + } + if (last !== buf.length) { + list.push(buf.slice(last)); + } + return list; +} + +function replaceByteInByteSequence(buf, from, to) { + let i = buf.indexOf(from); + while (i >= 0) { + buf[i] = to; + i = buf.indexOf(from, i + 1); + } + return buf; +} + +module.exports = { + parseUrlencodedString, + serializeUrlencoded +}; diff --git a/nodejs/node_modules/whatwg-url/lib/utils.js b/nodejs/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 00000000..3af17706 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,190 @@ +"use strict"; + +// Returns "Type(value) is Object" in ES terminology. +function isObject(value) { + return (typeof value === "object" && value !== null) || typeof value === "function"; +} + +const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); + +// Like `Object.assign`, but using `[[GetOwnProperty]]` and `[[DefineOwnProperty]]` +// instead of `[[Get]]` and `[[Set]]` and only allowing objects +function define(target, source) { + for (const key of Reflect.ownKeys(source)) { + const descriptor = Reflect.getOwnPropertyDescriptor(source, key); + if (descriptor && !Reflect.defineProperty(target, key, descriptor)) { + throw new TypeError(`Cannot redefine property: ${String(key)}`); + } + } +} + +function newObjectInRealm(globalObject, object) { + const ctorRegistry = initCtorRegistry(globalObject); + return Object.defineProperties( + Object.create(ctorRegistry["%Object.prototype%"]), + Object.getOwnPropertyDescriptors(object) + ); +} + +const wrapperSymbol = Symbol("wrapper"); +const implSymbol = Symbol("impl"); +const sameObjectCaches = Symbol("SameObject caches"); +const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); + +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + +function initCtorRegistry(globalObject) { + if (hasOwn(globalObject, ctorRegistrySymbol)) { + return globalObject[ctorRegistrySymbol]; + } + + const ctorRegistry = Object.create(null); + + // In addition to registering all the WebIDL2JS-generated types in the constructor registry, + // we also register a few intrinsics that we make use of in generated code, since they are not + // easy to grab from the globalObject variable. + ctorRegistry["%Object.prototype%"] = globalObject.Object.prototype; + ctorRegistry["%IteratorPrototype%"] = Object.getPrototypeOf( + Object.getPrototypeOf(new globalObject.Array()[Symbol.iterator]()) + ); + + try { + ctorRegistry["%AsyncIteratorPrototype%"] = Object.getPrototypeOf( + Object.getPrototypeOf( + globalObject.eval("(async function* () {})").prototype + ) + ); + } catch { + ctorRegistry["%AsyncIteratorPrototype%"] = AsyncIteratorPrototype; + } + + globalObject[ctorRegistrySymbol] = ctorRegistry; + return ctorRegistry; +} + +function getSameObject(wrapper, prop, creator) { + if (!wrapper[sameObjectCaches]) { + wrapper[sameObjectCaches] = Object.create(null); + } + + if (prop in wrapper[sameObjectCaches]) { + return wrapper[sameObjectCaches][prop]; + } + + wrapper[sameObjectCaches][prop] = creator(); + return wrapper[sameObjectCaches][prop]; +} + +function wrapperForImpl(impl) { + return impl ? impl[wrapperSymbol] : null; +} + +function implForWrapper(wrapper) { + return wrapper ? wrapper[implSymbol] : null; +} + +function tryWrapperForImpl(impl) { + const wrapper = wrapperForImpl(impl); + return wrapper ? wrapper : impl; +} + +function tryImplForWrapper(wrapper) { + const impl = implForWrapper(wrapper); + return impl ? impl : wrapper; +} + +const iterInternalSymbol = Symbol("internal"); + +function isArrayIndexPropName(P) { + if (typeof P !== "string") { + return false; + } + const i = P >>> 0; + if (i === 2 ** 32 - 1) { + return false; + } + const s = `${i}`; + if (P !== s) { + return false; + } + return true; +} + +const byteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +function isArrayBuffer(value) { + try { + byteLengthGetter.call(value); + return true; + } catch (e) { + return false; + } +} + +function iteratorResult([key, value], kind) { + let result; + switch (kind) { + case "key": + result = key; + break; + case "value": + result = value; + break; + case "key+value": + result = [key, value]; + break; + } + return { value: result, done: false }; +} + +const supportsPropertyIndex = Symbol("supports property index"); +const supportedPropertyIndices = Symbol("supported property indices"); +const supportsPropertyName = Symbol("supports property name"); +const supportedPropertyNames = Symbol("supported property names"); +const indexedGet = Symbol("indexed property get"); +const indexedSetNew = Symbol("indexed property set new"); +const indexedSetExisting = Symbol("indexed property set existing"); +const namedGet = Symbol("named property get"); +const namedSetNew = Symbol("named property set new"); +const namedSetExisting = Symbol("named property set existing"); +const namedDelete = Symbol("named property delete"); + +const asyncIteratorNext = Symbol("async iterator get the next iteration result"); +const asyncIteratorReturn = Symbol("async iterator return steps"); +const asyncIteratorInit = Symbol("async iterator initialization steps"); +const asyncIteratorEOI = Symbol("async iterator end of iteration"); + +module.exports = exports = { + isObject, + hasOwn, + define, + newObjectInRealm, + wrapperSymbol, + implSymbol, + getSameObject, + ctorRegistrySymbol, + initCtorRegistry, + wrapperForImpl, + implForWrapper, + tryWrapperForImpl, + tryImplForWrapper, + iterInternalSymbol, + isArrayBuffer, + isArrayIndexPropName, + supportsPropertyIndex, + supportedPropertyIndices, + supportsPropertyName, + supportedPropertyNames, + indexedGet, + indexedSetNew, + indexedSetExisting, + namedGet, + namedSetNew, + namedSetExisting, + namedDelete, + asyncIteratorNext, + asyncIteratorReturn, + asyncIteratorInit, + asyncIteratorEOI, + iteratorResult +}; diff --git a/nodejs/node_modules/whatwg-url/package.json b/nodejs/node_modules/whatwg-url/package.json new file mode 100644 index 00000000..eb02627e --- /dev/null +++ b/nodejs/node_modules/whatwg-url/package.json @@ -0,0 +1,58 @@ +{ + "name": "whatwg-url", + "version": "13.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "index.js", + "files": [ + "index.js", + "webidl2js-wrapper.js", + "lib/*.js" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "devDependencies": { + "@domenic/eslint-config": "^3.0.0", + "benchmark": "^2.1.4", + "domexception": "^4.0.0", + "esbuild": "^0.17.19", + "eslint": "^8.41.0", + "jest": "^29.5.0", + "minipass-fetch": "^3.0.3", + "webidl2js": "^17.1.0" + }, + "engines": { + "node": ">=16" + }, + "scripts": { + "coverage": "jest --coverage", + "lint": "eslint .", + "prepare": "node scripts/transform.js", + "pretest": "node scripts/get-latest-platform-tests.js && node scripts/transform.js", + "build-live-viewer": "esbuild --bundle --format=esm --sourcemap --outfile=live-viewer/whatwg-url.mjs index.js", + "test": "jest" + }, + "jest": { + "collectCoverageFrom": [ + "lib/**/*.js", + "!lib/utils.js" + ], + "coverageDirectory": "coverage", + "coverageReporters": [ + "lcov", + "text-summary" + ], + "testEnvironment": "node", + "testMatch": [ + "/test/**/*.js" + ], + "testPathIgnorePatterns": [ + "^/test/testharness.js$", + "^/test/web-platform-tests/" + ] + } +} diff --git a/nodejs/node_modules/whatwg-url/webidl2js-wrapper.js b/nodejs/node_modules/whatwg-url/webidl2js-wrapper.js new file mode 100644 index 00000000..b731ace5 --- /dev/null +++ b/nodejs/node_modules/whatwg-url/webidl2js-wrapper.js @@ -0,0 +1,7 @@ +"use strict"; + +const URL = require("./lib/URL"); +const URLSearchParams = require("./lib/URLSearchParams"); + +exports.URL = URL; +exports.URLSearchParams = URLSearchParams; diff --git a/nodejs/node_modules/winston-transport/.babelrc b/nodejs/node_modules/winston-transport/.babelrc new file mode 100644 index 00000000..002b4aa0 --- /dev/null +++ b/nodejs/node_modules/winston-transport/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["env"] +} diff --git a/nodejs/node_modules/winston-transport/.eslintrc b/nodejs/node_modules/winston-transport/.eslintrc new file mode 100644 index 00000000..a73255e2 --- /dev/null +++ b/nodejs/node_modules/winston-transport/.eslintrc @@ -0,0 +1,7 @@ +{ + "extends": "@dabh/eslint-config-populist", + "rules": { + "one-var": ["error", { var: "never", let: "never", const: "never" }], + "strict": 0 + } +} diff --git a/nodejs/node_modules/winston-transport/.gitattributes b/nodejs/node_modules/winston-transport/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/nodejs/node_modules/winston-transport/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/nodejs/node_modules/winston-transport/.nyc_output/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json b/nodejs/node_modules/winston-transport/.nyc_output/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json new file mode 100644 index 00000000..5a4936db --- /dev/null +++ b/nodejs/node_modules/winston-transport/.nyc_output/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json @@ -0,0 +1 @@ +{"/Users/dabh/winston-transport/index.js":{"path":"/Users/dabh/winston-transport/index.js","statementMap":{"0":{"start":{"line":4,"column":0},"end":{"line":4,"column":37}},"1":{"start":{"line":7,"column":0},"end":{"line":7,"column":59}}},"fnMap":{},"branchMap":{},"s":{"0":1,"1":1},"f":{},"b":{},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"8b988309d802712672b7bff507361099a67bc431","contentHash":"976bb7c8b475d18ea5eb9e44ee5e145c5939228b9c6d978e7aba13c296d67d13"},"/Users/dabh/winston-transport/modern.js":{"path":"/Users/dabh/winston-transport/modern.js","statementMap":{"0":{"start":{"line":3,"column":13},"end":{"line":3,"column":28}},"1":{"start":{"line":4,"column":17},"end":{"line":4,"column":67}},"2":{"start":{"line":5,"column":18},"end":{"line":5,"column":40}},"3":{"start":{"line":18,"column":24},"end":{"line":54,"column":1}},"4":{"start":{"line":19,"column":2},"end":{"line":19,"column":82}},"5":{"start":{"line":21,"column":2},"end":{"line":21,"column":31}},"6":{"start":{"line":22,"column":2},"end":{"line":22,"column":29}},"7":{"start":{"line":23,"column":2},"end":{"line":23,"column":51}},"8":{"start":{"line":24,"column":2},"end":{"line":24,"column":51}},"9":{"start":{"line":25,"column":2},"end":{"line":25,"column":31}},"10":{"start":{"line":27,"column":2},"end":{"line":27,"column":42}},"11":{"start":{"line":27,"column":19},"end":{"line":27,"column":42}},"12":{"start":{"line":28,"column":2},"end":{"line":28,"column":45}},"13":{"start":{"line":28,"column":20},"end":{"line":28,"column":45}},"14":{"start":{"line":29,"column":2},"end":{"line":29,"column":48}},"15":{"start":{"line":29,"column":21},"end":{"line":29,"column":48}},"16":{"start":{"line":32,"column":2},"end":{"line":39,"column":5}},"17":{"start":{"line":37,"column":4},"end":{"line":37,"column":32}},"18":{"start":{"line":38,"column":4},"end":{"line":38,"column":25}},"19":{"start":{"line":42,"column":2},"end":{"line":53,"column":5}},"20":{"start":{"line":47,"column":4},"end":{"line":52,"column":5}},"21":{"start":{"line":48,"column":6},"end":{"line":48,"column":25}},"22":{"start":{"line":49,"column":6},"end":{"line":51,"column":7}},"23":{"start":{"line":50,"column":8},"end":{"line":50,"column":21}},"24":{"start":{"line":59,"column":0},"end":{"line":59,"column":41}},"25":{"start":{"line":69,"column":0},"end":{"line":107,"column":2}},"26":{"start":{"line":70,"column":2},"end":{"line":72,"column":3}},"27":{"start":{"line":71,"column":4},"end":{"line":71,"column":26}},"28":{"start":{"line":78,"column":16},"end":{"line":78,"column":64}},"29":{"start":{"line":80,"column":2},"end":{"line":104,"column":3}},"30":{"start":{"line":81,"column":4},"end":{"line":83,"column":5}},"31":{"start":{"line":82,"column":6},"end":{"line":82,"column":38}},"32":{"start":{"line":90,"column":4},"end":{"line":94,"column":5}},"33":{"start":{"line":91,"column":6},"end":{"line":91,"column":88}},"34":{"start":{"line":93,"column":6},"end":{"line":93,"column":21}},"35":{"start":{"line":96,"column":4},"end":{"line":101,"column":5}},"36":{"start":{"line":98,"column":6},"end":{"line":98,"column":17}},"37":{"start":{"line":99,"column":6},"end":{"line":99,"column":35}},"38":{"start":{"line":99,"column":20},"end":{"line":99,"column":35}},"39":{"start":{"line":100,"column":6},"end":{"line":100,"column":13}},"40":{"start":{"line":103,"column":4},"end":{"line":103,"column":43}},"41":{"start":{"line":105,"column":2},"end":{"line":105,"column":35}},"42":{"start":{"line":106,"column":2},"end":{"line":106,"column":24}},"43":{"start":{"line":117,"column":0},"end":{"line":166,"column":2}},"44":{"start":{"line":118,"column":2},"end":{"line":128,"column":3}},"45":{"start":{"line":119,"column":18},"end":{"line":119,"column":51}},"46":{"start":{"line":120,"column":4},"end":{"line":122,"column":5}},"47":{"start":{"line":121,"column":6},"end":{"line":121,"column":28}},"48":{"start":{"line":127,"column":4},"end":{"line":127,"column":38}},"49":{"start":{"line":130,"column":2},"end":{"line":163,"column":3}},"50":{"start":{"line":130,"column":15},"end":{"line":130,"column":16}},"51":{"start":{"line":131,"column":4},"end":{"line":131,"column":43}},"52":{"start":{"line":131,"column":34},"end":{"line":131,"column":43}},"53":{"start":{"line":133,"column":4},"end":{"line":136,"column":5}},"54":{"start":{"line":134,"column":6},"end":{"line":134,"column":52}},"55":{"start":{"line":135,"column":6},"end":{"line":135,"column":15}},"56":{"start":{"line":143,"column":4},"end":{"line":150,"column":5}},"57":{"start":{"line":144,"column":6},"end":{"line":147,"column":8}},"58":{"start":{"line":149,"column":6},"end":{"line":149,"column":21}},"59":{"start":{"line":152,"column":4},"end":{"line":162,"column":5}},"60":{"start":{"line":154,"column":6},"end":{"line":154,"column":27}},"61":{"start":{"line":155,"column":6},"end":{"line":159,"column":7}},"62":{"start":{"line":157,"column":8},"end":{"line":157,"column":23}},"63":{"start":{"line":158,"column":8},"end":{"line":158,"column":23}},"64":{"start":{"line":161,"column":6},"end":{"line":161,"column":48}},"65":{"start":{"line":165,"column":2},"end":{"line":165,"column":24}},"66":{"start":{"line":177,"column":0},"end":{"line":202,"column":2}},"67":{"start":{"line":178,"column":15},"end":{"line":178,"column":26}},"68":{"start":{"line":179,"column":2},"end":{"line":181,"column":3}},"69":{"start":{"line":180,"column":4},"end":{"line":180,"column":17}},"70":{"start":{"line":185,"column":16},"end":{"line":185,"column":64}},"71":{"start":{"line":188,"column":2},"end":{"line":199,"column":3}},"72":{"start":{"line":196,"column":4},"end":{"line":198,"column":5}},"73":{"start":{"line":197,"column":6},"end":{"line":197,"column":18}},"74":{"start":{"line":201,"column":2},"end":{"line":201,"column":15}},"75":{"start":{"line":208,"column":0},"end":{"line":211,"column":2}},"76":{"start":{"line":210,"column":2},"end":{"line":210,"column":24}}},"fnMap":{"0":{"name":"TransportStream","decl":{"start":{"line":18,"column":50},"end":{"line":18,"column":65}},"loc":{"start":{"line":18,"column":80},"end":{"line":54,"column":1}},"line":18},"1":{"name":"(anonymous_1)","decl":{"start":{"line":32,"column":20},"end":{"line":32,"column":21}},"loc":{"start":{"line":32,"column":30},"end":{"line":39,"column":3}},"line":32},"2":{"name":"(anonymous_2)","decl":{"start":{"line":42,"column":22},"end":{"line":42,"column":23}},"loc":{"start":{"line":42,"column":29},"end":{"line":53,"column":3}},"line":42},"3":{"name":"_write","decl":{"start":{"line":69,"column":44},"end":{"line":69,"column":50}},"loc":{"start":{"line":69,"column":72},"end":{"line":107,"column":1}},"line":69},"4":{"name":"_writev","decl":{"start":{"line":117,"column":45},"end":{"line":117,"column":52}},"loc":{"start":{"line":117,"column":71},"end":{"line":166,"column":1}},"line":117},"5":{"name":"_accept","decl":{"start":{"line":177,"column":45},"end":{"line":177,"column":52}},"loc":{"start":{"line":177,"column":60},"end":{"line":202,"column":1}},"line":177},"6":{"name":"_nop","decl":{"start":{"line":208,"column":42},"end":{"line":208,"column":46}},"loc":{"start":{"line":208,"column":49},"end":{"line":211,"column":1}},"line":208}},"branchMap":{"0":{"loc":{"start":{"line":18,"column":66},"end":{"line":18,"column":78}},"type":"default-arg","locations":[{"start":{"line":18,"column":76},"end":{"line":18,"column":78}}],"line":18},"1":{"loc":{"start":{"line":27,"column":2},"end":{"line":27,"column":42}},"type":"if","locations":[{"start":{"line":27,"column":2},"end":{"line":27,"column":42}},{"start":{"line":27,"column":2},"end":{"line":27,"column":42}}],"line":27},"2":{"loc":{"start":{"line":28,"column":2},"end":{"line":28,"column":45}},"type":"if","locations":[{"start":{"line":28,"column":2},"end":{"line":28,"column":45}},{"start":{"line":28,"column":2},"end":{"line":28,"column":45}}],"line":28},"3":{"loc":{"start":{"line":29,"column":2},"end":{"line":29,"column":48}},"type":"if","locations":[{"start":{"line":29,"column":2},"end":{"line":29,"column":48}},{"start":{"line":29,"column":2},"end":{"line":29,"column":48}}],"line":29},"4":{"loc":{"start":{"line":47,"column":4},"end":{"line":52,"column":5}},"type":"if","locations":[{"start":{"line":47,"column":4},"end":{"line":52,"column":5}},{"start":{"line":47,"column":4},"end":{"line":52,"column":5}}],"line":47},"5":{"loc":{"start":{"line":49,"column":6},"end":{"line":51,"column":7}},"type":"if","locations":[{"start":{"line":49,"column":6},"end":{"line":51,"column":7}},{"start":{"line":49,"column":6},"end":{"line":51,"column":7}}],"line":49},"6":{"loc":{"start":{"line":70,"column":2},"end":{"line":72,"column":3}},"type":"if","locations":[{"start":{"line":70,"column":2},"end":{"line":72,"column":3}},{"start":{"line":70,"column":2},"end":{"line":72,"column":3}}],"line":70},"7":{"loc":{"start":{"line":70,"column":6},"end":{"line":70,"column":72}},"type":"binary-expr","locations":[{"start":{"line":70,"column":6},"end":{"line":70,"column":17}},{"start":{"line":70,"column":22},"end":{"line":70,"column":45}},{"start":{"line":70,"column":49},"end":{"line":70,"column":71}}],"line":70},"8":{"loc":{"start":{"line":78,"column":16},"end":{"line":78,"column":64}},"type":"binary-expr","locations":[{"start":{"line":78,"column":16},"end":{"line":78,"column":26}},{"start":{"line":78,"column":31},"end":{"line":78,"column":42}},{"start":{"line":78,"column":46},"end":{"line":78,"column":63}}],"line":78},"9":{"loc":{"start":{"line":80,"column":2},"end":{"line":104,"column":3}},"type":"if","locations":[{"start":{"line":80,"column":2},"end":{"line":104,"column":3}},{"start":{"line":80,"column":2},"end":{"line":104,"column":3}}],"line":80},"10":{"loc":{"start":{"line":80,"column":6},"end":{"line":80,"column":62}},"type":"binary-expr","locations":[{"start":{"line":80,"column":6},"end":{"line":80,"column":12}},{"start":{"line":80,"column":16},"end":{"line":80,"column":62}}],"line":80},"11":{"loc":{"start":{"line":81,"column":4},"end":{"line":83,"column":5}},"type":"if","locations":[{"start":{"line":81,"column":4},"end":{"line":83,"column":5}},{"start":{"line":81,"column":4},"end":{"line":83,"column":5}}],"line":81},"12":{"loc":{"start":{"line":81,"column":8},"end":{"line":81,"column":28}},"type":"binary-expr","locations":[{"start":{"line":81,"column":8},"end":{"line":81,"column":12}},{"start":{"line":81,"column":16},"end":{"line":81,"column":28}}],"line":81},"13":{"loc":{"start":{"line":96,"column":4},"end":{"line":101,"column":5}},"type":"if","locations":[{"start":{"line":96,"column":4},"end":{"line":101,"column":5}},{"start":{"line":96,"column":4},"end":{"line":101,"column":5}}],"line":96},"14":{"loc":{"start":{"line":96,"column":8},"end":{"line":96,"column":32}},"type":"binary-expr","locations":[{"start":{"line":96,"column":8},"end":{"line":96,"column":16}},{"start":{"line":96,"column":20},"end":{"line":96,"column":32}}],"line":96},"15":{"loc":{"start":{"line":99,"column":6},"end":{"line":99,"column":35}},"type":"if","locations":[{"start":{"line":99,"column":6},"end":{"line":99,"column":35}},{"start":{"line":99,"column":6},"end":{"line":99,"column":35}}],"line":99},"16":{"loc":{"start":{"line":118,"column":2},"end":{"line":128,"column":3}},"type":"if","locations":[{"start":{"line":118,"column":2},"end":{"line":128,"column":3}},{"start":{"line":118,"column":2},"end":{"line":128,"column":3}}],"line":118},"17":{"loc":{"start":{"line":120,"column":4},"end":{"line":122,"column":5}},"type":"if","locations":[{"start":{"line":120,"column":4},"end":{"line":122,"column":5}},{"start":{"line":120,"column":4},"end":{"line":122,"column":5}}],"line":120},"18":{"loc":{"start":{"line":131,"column":4},"end":{"line":131,"column":43}},"type":"if","locations":[{"start":{"line":131,"column":4},"end":{"line":131,"column":43}},{"start":{"line":131,"column":4},"end":{"line":131,"column":43}}],"line":131},"19":{"loc":{"start":{"line":133,"column":4},"end":{"line":136,"column":5}},"type":"if","locations":[{"start":{"line":133,"column":4},"end":{"line":136,"column":5}},{"start":{"line":133,"column":4},"end":{"line":136,"column":5}}],"line":133},"20":{"loc":{"start":{"line":133,"column":8},"end":{"line":133,"column":39}},"type":"binary-expr","locations":[{"start":{"line":133,"column":8},"end":{"line":133,"column":23}},{"start":{"line":133,"column":27},"end":{"line":133,"column":39}}],"line":133},"21":{"loc":{"start":{"line":152,"column":4},"end":{"line":162,"column":5}},"type":"if","locations":[{"start":{"line":152,"column":4},"end":{"line":162,"column":5}},{"start":{"line":152,"column":4},"end":{"line":162,"column":5}}],"line":152},"22":{"loc":{"start":{"line":152,"column":8},"end":{"line":152,"column":32}},"type":"binary-expr","locations":[{"start":{"line":152,"column":8},"end":{"line":152,"column":16}},{"start":{"line":152,"column":20},"end":{"line":152,"column":32}}],"line":152},"23":{"loc":{"start":{"line":155,"column":6},"end":{"line":159,"column":7}},"type":"if","locations":[{"start":{"line":155,"column":6},"end":{"line":159,"column":7}},{"start":{"line":155,"column":6},"end":{"line":159,"column":7}}],"line":155},"24":{"loc":{"start":{"line":179,"column":2},"end":{"line":181,"column":3}},"type":"if","locations":[{"start":{"line":179,"column":2},"end":{"line":181,"column":3}},{"start":{"line":179,"column":2},"end":{"line":181,"column":3}}],"line":179},"25":{"loc":{"start":{"line":185,"column":16},"end":{"line":185,"column":64}},"type":"binary-expr","locations":[{"start":{"line":185,"column":16},"end":{"line":185,"column":26}},{"start":{"line":185,"column":31},"end":{"line":185,"column":42}},{"start":{"line":185,"column":46},"end":{"line":185,"column":63}}],"line":185},"26":{"loc":{"start":{"line":188,"column":2},"end":{"line":199,"column":3}},"type":"if","locations":[{"start":{"line":188,"column":2},"end":{"line":199,"column":3}},{"start":{"line":188,"column":2},"end":{"line":199,"column":3}}],"line":188},"27":{"loc":{"start":{"line":189,"column":4},"end":{"line":191,"column":50}},"type":"binary-expr","locations":[{"start":{"line":189,"column":4},"end":{"line":189,"column":27}},{"start":{"line":190,"column":4},"end":{"line":190,"column":10}},{"start":{"line":191,"column":4},"end":{"line":191,"column":50}}],"line":189},"28":{"loc":{"start":{"line":196,"column":4},"end":{"line":198,"column":5}},"type":"if","locations":[{"start":{"line":196,"column":4},"end":{"line":198,"column":5}},{"start":{"line":196,"column":4},"end":{"line":198,"column":5}}],"line":196},"29":{"loc":{"start":{"line":196,"column":8},"end":{"line":196,"column":56}},"type":"binary-expr","locations":[{"start":{"line":196,"column":8},"end":{"line":196,"column":29}},{"start":{"line":196,"column":33},"end":{"line":196,"column":56}}],"line":196}},"s":{"0":1,"1":1,"2":1,"3":1,"4":51,"5":51,"6":51,"7":51,"8":51,"9":51,"10":51,"11":22,"12":51,"13":1,"14":51,"15":0,"16":51,"17":5,"18":5,"19":51,"20":2,"21":2,"22":2,"23":1,"24":1,"25":1,"26":49,"27":10,"28":39,"29":39,"30":33,"31":20,"32":13,"33":13,"34":1,"35":13,"36":8,"37":8,"38":1,"39":7,"40":5,"41":6,"42":6,"43":1,"44":6,"45":1,"46":1,"47":0,"48":1,"49":5,"50":5,"51":584,"52":15,"53":569,"54":400,"55":400,"56":169,"57":169,"58":1,"59":169,"60":8,"61":8,"62":1,"63":1,"64":161,"65":4,"66":1,"67":1425,"68":1425,"69":32,"70":1393,"71":1393,"72":1240,"73":1232,"74":161,"75":1,"76":416},"f":{"0":51,"1":5,"2":2,"3":49,"4":6,"5":1425,"6":416},"b":{"0":[1],"1":[22,29],"2":[1,50],"3":[0,51],"4":[2,0],"5":[1,1],"6":[10,39],"7":[49,48,10],"8":[39,29,4],"9":[33,6],"10":[39,14],"11":[20,13],"12":[33,33],"13":[8,5],"14":[13,12],"15":[1,7],"16":[1,5],"17":[0,1],"18":[15,569],"19":[400,169],"20":[569,569],"21":[8,161],"22":[169,168],"23":[1,7],"24":[32,1393],"25":[1393,969,0],"26":[1240,153],"27":[1393,1377,408],"28":[1232,8],"29":[1240,1232]},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"f5e3e8b3514b164235fdbd3f0560bcdeb13bef08","contentHash":"19b69eb47411179768db4b56b7bc2ead2365fbea98c876b78b48d49317aa1c5c"},"/Users/dabh/winston-transport/legacy.js":{"path":"/Users/dabh/winston-transport/legacy.js","statementMap":{"0":{"start":{"line":3,"column":13},"end":{"line":3,"column":28}},"1":{"start":{"line":4,"column":18},"end":{"line":4,"column":40}},"2":{"start":{"line":5,"column":24},"end":{"line":5,"column":43}},"3":{"start":{"line":15,"column":30},"end":{"line":39,"column":1}},"4":{"start":{"line":16,"column":2},"end":{"line":16,"column":38}},"5":{"start":{"line":17,"column":2},"end":{"line":19,"column":3}},"6":{"start":{"line":18,"column":4},"end":{"line":18,"column":79}},"7":{"start":{"line":21,"column":2},"end":{"line":21,"column":37}},"8":{"start":{"line":22,"column":2},"end":{"line":22,"column":53}},"9":{"start":{"line":23,"column":2},"end":{"line":23,"column":86}},"10":{"start":{"line":26,"column":2},"end":{"line":26,"column":21}},"11":{"start":{"line":32,"column":4},"end":{"line":32,"column":44}},"12":{"start":{"line":35,"column":2},"end":{"line":38,"column":3}},"13":{"start":{"line":36,"column":4},"end":{"line":36,"column":62}},"14":{"start":{"line":37,"column":4},"end":{"line":37,"column":62}},"15":{"start":{"line":44,"column":0},"end":{"line":44,"column":54}},"16":{"start":{"line":54,"column":0},"end":{"line":66,"column":2}},"17":{"start":{"line":55,"column":2},"end":{"line":57,"column":3}},"18":{"start":{"line":56,"column":4},"end":{"line":56,"column":26}},"19":{"start":{"line":61,"column":2},"end":{"line":63,"column":3}},"20":{"start":{"line":62,"column":4},"end":{"line":62,"column":67}},"21":{"start":{"line":65,"column":2},"end":{"line":65,"column":17}},"22":{"start":{"line":76,"column":0},"end":{"line":90,"column":2}},"23":{"start":{"line":77,"column":2},"end":{"line":87,"column":3}},"24":{"start":{"line":77,"column":15},"end":{"line":77,"column":16}},"25":{"start":{"line":78,"column":4},"end":{"line":86,"column":5}},"26":{"start":{"line":79,"column":6},"end":{"line":84,"column":8}},"27":{"start":{"line":85,"column":6},"end":{"line":85,"column":27}},"28":{"start":{"line":89,"column":2},"end":{"line":89,"column":24}},"29":{"start":{"line":97,"column":0},"end":{"line":103,"column":2}},"30":{"start":{"line":99,"column":2},"end":{"line":102,"column":16}},"31":{"start":{"line":110,"column":0},"end":{"line":119,"column":2}},"32":{"start":{"line":111,"column":2},"end":{"line":113,"column":3}},"33":{"start":{"line":112,"column":4},"end":{"line":112,"column":27}},"34":{"start":{"line":115,"column":2},"end":{"line":118,"column":3}},"35":{"start":{"line":116,"column":4},"end":{"line":116,"column":74}},"36":{"start":{"line":117,"column":4},"end":{"line":117,"column":41}}},"fnMap":{"0":{"name":"LegacyTransportStream","decl":{"start":{"line":15,"column":56},"end":{"line":15,"column":77}},"loc":{"start":{"line":15,"column":92},"end":{"line":39,"column":1}},"line":15},"1":{"name":"transportError","decl":{"start":{"line":31,"column":11},"end":{"line":31,"column":25}},"loc":{"start":{"line":31,"column":31},"end":{"line":33,"column":3}},"line":31},"2":{"name":"_write","decl":{"start":{"line":54,"column":50},"end":{"line":54,"column":56}},"loc":{"start":{"line":54,"column":78},"end":{"line":66,"column":1}},"line":54},"3":{"name":"_writev","decl":{"start":{"line":76,"column":51},"end":{"line":76,"column":58}},"loc":{"start":{"line":76,"column":77},"end":{"line":90,"column":1}},"line":76},"4":{"name":"_deprecated","decl":{"start":{"line":97,"column":55},"end":{"line":97,"column":66}},"loc":{"start":{"line":97,"column":69},"end":{"line":103,"column":1}},"line":97},"5":{"name":"close","decl":{"start":{"line":110,"column":49},"end":{"line":110,"column":54}},"loc":{"start":{"line":110,"column":57},"end":{"line":119,"column":1}},"line":110}},"branchMap":{"0":{"loc":{"start":{"line":15,"column":78},"end":{"line":15,"column":90}},"type":"default-arg","locations":[{"start":{"line":15,"column":88},"end":{"line":15,"column":90}}],"line":15},"1":{"loc":{"start":{"line":17,"column":2},"end":{"line":19,"column":3}},"type":"if","locations":[{"start":{"line":17,"column":2},"end":{"line":19,"column":3}},{"start":{"line":17,"column":2},"end":{"line":19,"column":3}}],"line":17},"2":{"loc":{"start":{"line":17,"column":6},"end":{"line":17,"column":71}},"type":"binary-expr","locations":[{"start":{"line":17,"column":6},"end":{"line":17,"column":24}},{"start":{"line":17,"column":28},"end":{"line":17,"column":71}}],"line":17},"3":{"loc":{"start":{"line":22,"column":15},"end":{"line":22,"column":52}},"type":"binary-expr","locations":[{"start":{"line":22,"column":15},"end":{"line":22,"column":25}},{"start":{"line":22,"column":29},"end":{"line":22,"column":52}}],"line":22},"4":{"loc":{"start":{"line":23,"column":26},"end":{"line":23,"column":85}},"type":"binary-expr","locations":[{"start":{"line":23,"column":26},"end":{"line":23,"column":47}},{"start":{"line":23,"column":51},"end":{"line":23,"column":85}}],"line":23},"5":{"loc":{"start":{"line":35,"column":2},"end":{"line":38,"column":3}},"type":"if","locations":[{"start":{"line":35,"column":2},"end":{"line":38,"column":3}},{"start":{"line":35,"column":2},"end":{"line":38,"column":3}}],"line":35},"6":{"loc":{"start":{"line":55,"column":2},"end":{"line":57,"column":3}},"type":"if","locations":[{"start":{"line":55,"column":2},"end":{"line":57,"column":3}},{"start":{"line":55,"column":2},"end":{"line":57,"column":3}}],"line":55},"7":{"loc":{"start":{"line":55,"column":6},"end":{"line":55,"column":72}},"type":"binary-expr","locations":[{"start":{"line":55,"column":6},"end":{"line":55,"column":17}},{"start":{"line":55,"column":22},"end":{"line":55,"column":45}},{"start":{"line":55,"column":49},"end":{"line":55,"column":71}}],"line":55},"8":{"loc":{"start":{"line":61,"column":2},"end":{"line":63,"column":3}},"type":"if","locations":[{"start":{"line":61,"column":2},"end":{"line":63,"column":3}},{"start":{"line":61,"column":2},"end":{"line":63,"column":3}}],"line":61},"9":{"loc":{"start":{"line":61,"column":6},"end":{"line":61,"column":72}},"type":"binary-expr","locations":[{"start":{"line":61,"column":6},"end":{"line":61,"column":17}},{"start":{"line":61,"column":21},"end":{"line":61,"column":72}}],"line":61},"10":{"loc":{"start":{"line":78,"column":4},"end":{"line":86,"column":5}},"type":"if","locations":[{"start":{"line":78,"column":4},"end":{"line":86,"column":5}},{"start":{"line":78,"column":4},"end":{"line":86,"column":5}}],"line":78},"11":{"loc":{"start":{"line":111,"column":2},"end":{"line":113,"column":3}},"type":"if","locations":[{"start":{"line":111,"column":2},"end":{"line":113,"column":3}},{"start":{"line":111,"column":2},"end":{"line":113,"column":3}}],"line":111},"12":{"loc":{"start":{"line":115,"column":2},"end":{"line":118,"column":3}},"type":"if","locations":[{"start":{"line":115,"column":2},"end":{"line":118,"column":3}},{"start":{"line":115,"column":2},"end":{"line":118,"column":3}}],"line":115}},"s":{"0":1,"1":1,"2":1,"3":1,"4":23,"5":23,"6":2,"7":21,"8":21,"9":21,"10":21,"11":1,"12":21,"13":18,"14":18,"15":1,"16":1,"17":29,"18":10,"19":19,"20":16,"21":19,"22":1,"23":2,"24":2,"25":415,"26":400,"27":400,"28":2,"29":1,"30":1,"31":1,"32":2,"33":2,"34":2,"35":2,"36":2},"f":{"0":23,"1":1,"2":29,"3":2,"4":1,"5":2},"b":{"0":[2],"1":[2,21],"2":[23,21],"3":[21,19],"4":[21,20],"5":[18,3],"6":[10,19],"7":[29,28,10],"8":[16,3],"9":[19,8],"10":[400,15],"11":[2,0],"12":[2,0]},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"11fd32e1fbda4c1483874e6fce21fe2f1a98d345","contentHash":"d0c7a092ffa5592b06f001a5f97a6a886b4f00d92a166f51193b4e6c1d7dd493"}} \ No newline at end of file diff --git a/nodejs/node_modules/winston-transport/.nyc_output/processinfo/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json b/nodejs/node_modules/winston-transport/.nyc_output/processinfo/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json new file mode 100644 index 00000000..14c1fb1d --- /dev/null +++ b/nodejs/node_modules/winston-transport/.nyc_output/processinfo/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json @@ -0,0 +1 @@ +{"parent":null,"pid":98505,"argv":["/Users/dabh/.nvm/versions/node/v16.18.0/bin/node","/Users/dabh/winston-transport/node_modules/.bin/mocha","test/index.test.js","test/inheritance.test.js","test/legacy.test.js"],"execArgv":[],"cwd":"/Users/dabh/winston-transport","time":1707030331549,"ppid":98504,"coverageFilename":"/Users/dabh/winston-transport/.nyc_output/c1bd7935-644d-4c7a-89c1-24531a04e4cc.json","externalId":"","uuid":"c1bd7935-644d-4c7a-89c1-24531a04e4cc","files":["/Users/dabh/winston-transport/index.js","/Users/dabh/winston-transport/modern.js","/Users/dabh/winston-transport/legacy.js"]} \ No newline at end of file diff --git a/nodejs/node_modules/winston-transport/.nyc_output/processinfo/index.json b/nodejs/node_modules/winston-transport/.nyc_output/processinfo/index.json new file mode 100644 index 00000000..0a503d95 --- /dev/null +++ b/nodejs/node_modules/winston-transport/.nyc_output/processinfo/index.json @@ -0,0 +1 @@ +{"processes":{"c1bd7935-644d-4c7a-89c1-24531a04e4cc":{"parent":null,"children":[]}},"files":{"/Users/dabh/winston-transport/index.js":["c1bd7935-644d-4c7a-89c1-24531a04e4cc"],"/Users/dabh/winston-transport/modern.js":["c1bd7935-644d-4c7a-89c1-24531a04e4cc"],"/Users/dabh/winston-transport/legacy.js":["c1bd7935-644d-4c7a-89c1-24531a04e4cc"]},"externalIds":{}} \ No newline at end of file diff --git a/nodejs/node_modules/winston-transport/CHANGELOG.md b/nodejs/node_modules/winston-transport/CHANGELOG.md new file mode 100644 index 00000000..a6ef4de2 --- /dev/null +++ b/nodejs/node_modules/winston-transport/CHANGELOG.md @@ -0,0 +1,126 @@ +# CHANGELOG + +### 4.5.0 (2022/02/05) + +- [#81] Memory leak fix: do not wait for `process.nextTick` to clear callbacks +- [#87, #82, #67] Update dependencies, CI config, and linter config + +### 4.4.1 (2021/12/14) + +- [#44] Add handleRejections to types. +- [#60] Exclude unnecessary files from npm package +- [#45] [#58] Update dependencies. + +### 4.4.0 (2018/12/23) + +- [#41] Support handleRejections option. +- [#42] Expose LegacyTransportStream from the base module. +- Update dependencies. + +### 4.3.0 (2018/12/23) + +- [#30] Precompile before publishing to `npm`. +- [#32] Add new option to increase default `highWaterMark` value. + +### 4.2.0 (2018/06/11) + +- [#26] Do not use copy-by-value for `this.level`. +- [#25] Wrap calls to `format.transform` with try / catch. +- [#24] Use `readable-stream` package to get the _final semantics across all versions of Node. + +### 4.1.0 (2018/05/31) + +- [#23] Revert to prototypal-based syntax for backwards compatibility. + +### 4.0.0 (2018/05/24) + +- **BREAKING** Update transports to use ES6 classes. Creation of +`TransportStream` and `LegacyTransportStream` now requires the `new` keyword. + +**No longer works** +``` js +const Transport = require('winston-transport'); +const transport = Transport({ + log: (info, callback) => { /* log something */ } +}); +``` + +**Do this instead** +``` js +const Transport = require('winston-transport'); +const transport = new Transport({ + log: (info, callback) => { /* log something */ } +}); +``` + +### 3.3.0 (2018/05/24) +**Unpublished:** overlooked that 26f816e introduced a breaking change. + +- [#21] Do not log when there is no info object. +- [#20] Add silent options to typings. +- [#19] Refactor test fixtures to use es6-classes. +- [#18] Use triple-beam for info object constants. +- [#17] Add linting and Node v10 to the travis build of the project. + +### 3.2.1 (2018/04/25) + +- [#16] Reorder in TS defs: namespace must come after class in order for delcaration merging to work as expected. + +### 3.2.0 (2018/04/22) + +- [#13] Add silent support to LegacyTransportStream. Fixes [#8]. +- [#14] Ensure that if a Transport-specific format is provided it is invoked on each chunk before passing it to `.log`. Fixes [#12]. +- [#11] Revice `d.ts` +- Add `.travis.yml`. +- Documentation updates: + - [#5] Update deprecated link. + - [#7] Correct `this` reference in `README.md` by using an arrow function. + +### 3.1.0 (2018/04/06) + +- [#10] Add `silent` option to `TransportStream`. Still needs to be implemented + for `LegacyTransportStream`. +- Bump `mocha` to `^5.0.5`. +- Bump `nyc` to `^11.6.0`. + +### 3.0.1 (2017/10/01) + +- [#4] Use ES6-class for defining Transport in `README.md`. +- [#4] Do not overwrite prototypal methods unless they are provided in the options. + +### 3.0.0 (2017/09/29) + +- Use `Symbol.for('level')` to lookup immutable `level` on `info` objects. + +### 2.1.1 (2017/09/29) + +- Properly interact with the `{ format }`, if provided. + +### 2.1.0 (2017/09/27) + +- If a format is defined use it to mutate the info. + +### 2.0.0 (2017/04/11) + +- [#2] Final semantics for `winston-transport` base implementations: + - `TransportStream`: the new `objectMode` Writable stream which should be the base for all future Transports after `winston >= 3`. + - `LegacyTransportStream`: the backwards compatible wrap to Transports written for `winston < 3`. There isn't all that much different for those implementors except that `log(level, message, meta, callback)` is now `log(info, callback)` where `info` is the object being plumbed along the objectMode pipe-chain. This was absolutely critical to not "break the ecosystem" and give [the over 500 Transport package authors](https://www.npmjs.com/search?q=winston) an upgrade path. + - Along with all the code coverage & `WritableStream` goodies: + - 100% code coverage for `TransportStream` + - 100% code coverage for `LegacyTransportStream` + - Implementation of `_writev` for `TransportStream` + - Implementation of `_writev` for `LegacyTransportStream` + +### 1.0.2 (2015/11/30) + +- Pass the write stream callback so that we can communicate backpressure up the chain of streams. + +### 1.0.1 (2015/11/22) + +- First `require`-able version. + +### 1.0.0 (2015/11/22) + +- Initial version. + +[#2]: https://github.com/winstonjs/winston-transport/pull/2 diff --git a/nodejs/node_modules/winston-transport/LICENSE b/nodejs/node_modules/winston-transport/LICENSE new file mode 100644 index 00000000..64e5d87d --- /dev/null +++ b/nodejs/node_modules/winston-transport/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Charlie Robbins & the contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/nodejs/node_modules/winston-transport/README.md b/nodejs/node_modules/winston-transport/README.md new file mode 100644 index 00000000..1b7591eb --- /dev/null +++ b/nodejs/node_modules/winston-transport/README.md @@ -0,0 +1,50 @@ +# winston-transport + +The base `TransportStream` implementation for `winston >= 3`. Use these to +write ecosystem Transports for `winston`. + +## Usage + +``` js +const Transport = require('winston-transport'); +const util = require('util'); + +// +// Inherit from `winston-transport` so you can take advantage +// of the base functionality and `.exceptions.handle()`. +// +module.exports = class CustomTransport extends Transport { + constructor(opts) { + super(opts); + + // + // Consume any custom options here. e.g.: + // - Connection information for databases + // - Authentication information for APIs (e.g. loggly, papertrail, + // logentries, etc.). + // + } + + log(info, callback) { + setImmediate(() => { + this.emit('logged', info); + }); + + // Perform the writing to the remote service + + callback(); + } +}; +``` + +## Tests + +Tests are written with `mocha`, `nyc`, `assume`, and +`abstract-winston-transport`. They can be run with `npm`: + +``` bash +npm test +``` + +##### Author: [Charlie Robbins](https://github.com/indexzero) +##### LICENSE: MIT diff --git a/nodejs/node_modules/winston-transport/dist/index.js b/nodejs/node_modules/winston-transport/dist/index.js new file mode 100644 index 00000000..ba57f116 --- /dev/null +++ b/nodejs/node_modules/winston-transport/dist/index.js @@ -0,0 +1,8 @@ +'use strict'; + +// Expose modern transport directly as the export + +module.exports = require('./modern'); + +// Expose legacy stream +module.exports.LegacyTransportStream = require('./legacy'); \ No newline at end of file diff --git a/nodejs/node_modules/winston-transport/dist/legacy.js b/nodejs/node_modules/winston-transport/dist/legacy.js new file mode 100644 index 00000000..0a29d1b9 --- /dev/null +++ b/nodejs/node_modules/winston-transport/dist/legacy.js @@ -0,0 +1,116 @@ +'use strict'; + +var util = require('util'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL; + +var TransportStream = require('./modern'); + +/** + * Constructor function for the LegacyTransportStream. This is an internal + * wrapper `winston >= 3` uses to wrap older transports implementing + * log(level, message, meta). + * @param {Object} options - Options for this TransportStream instance. + * @param {Transpot} options.transport - winston@2 or older Transport to wrap. + */ + +var LegacyTransportStream = module.exports = function LegacyTransportStream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + TransportStream.call(this, options); + if (!options.transport || typeof options.transport.log !== 'function') { + throw new Error('Invalid transport, must be an object with a log method.'); + } + + this.transport = options.transport; + this.level = this.level || options.transport.level; + this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; + + // Display our deprecation notice. + this._deprecated(); + + // Properly bubble up errors from the transport to the + // LegacyTransportStream instance, but only once no matter how many times + // this transport is shared. + function transportError(err) { + this.emit('error', err, this.transport); + } + + if (!this.transport.__winstonError) { + this.transport.__winstonError = transportError.bind(this); + this.transport.on('error', this.transport.__winstonError); + } +}; + +/* + * Inherit from TransportStream using Node.js built-ins + */ +util.inherits(LegacyTransportStream, TransportStream); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +LegacyTransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. + if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { + this.transport.log(info[LEVEL], info.message, info, this._nop); + } + + callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { + for (var i = 0; i < chunks.length; i++) { + if (this._accept(chunks[i])) { + this.transport.log(chunks[i].chunk[LEVEL], chunks[i].chunk.message, chunks[i].chunk, this._nop); + chunks[i].callback(); + } + } + + return callback(null); +}; + +/** + * Displays a deprecation notice. Defined as a function so it can be + * overriden in tests. + * @returns {undefined} + */ +LegacyTransportStream.prototype._deprecated = function _deprecated() { + // eslint-disable-next-line no-console + console.error([this.transport.name + ' is a legacy winston transport. Consider upgrading: ', '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'].join('\n')); +}; + +/** + * Clean up error handling state on the legacy transport associated + * with this instance. + * @returns {undefined} + */ +LegacyTransportStream.prototype.close = function close() { + if (this.transport.close) { + this.transport.close(); + } + + if (this.transport.__winstonError) { + this.transport.removeListener('error', this.transport.__winstonError); + this.transport.__winstonError = null; + } +}; \ No newline at end of file diff --git a/nodejs/node_modules/winston-transport/dist/modern.js b/nodejs/node_modules/winston-transport/dist/modern.js new file mode 100644 index 00000000..4759ab8c --- /dev/null +++ b/nodejs/node_modules/winston-transport/dist/modern.js @@ -0,0 +1,212 @@ +'use strict'; + +var util = require('util'); +var Writable = require('readable-stream/lib/_stream_writable.js'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL; + +/** + * Constructor function for the TransportStream. This is the base prototype + * that all `winston >= 3` transports should inherit from. + * @param {Object} options - Options for this TransportStream instance + * @param {String} options.level - Highest level according to RFC5424. + * @param {Boolean} options.handleExceptions - If true, info with + * { exception: true } will be written. + * @param {Function} options.log - Custom log function for simple Transport + * creation + * @param {Function} options.close - Called on "unpipe" from parent. + */ + + +var TransportStream = module.exports = function TransportStream() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + + this.format = options.format; + this.level = options.level; + this.handleExceptions = options.handleExceptions; + this.handleRejections = options.handleRejections; + this.silent = options.silent; + + if (options.log) this.log = options.log; + if (options.logv) this.logv = options.logv; + if (options.close) this.close = options.close; + + // Get the levels from the source we are piped from. + this.once('pipe', function (logger) { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + _this.levels = logger.levels; + _this.parent = logger; + }); + + // If and/or when the transport is removed from this instance + this.once('unpipe', function (src) { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + if (src === _this.parent) { + _this.parent = null; + if (_this.close) { + _this.close(); + } + } + }); +}; + +/* + * Inherit from Writeable using Node.js built-ins + */ +util.inherits(TransportStream, Writable); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +TransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. We always + // prefer any explicit level set on the Transport itself falling back to + // any level set on the parent. + var level = this.level || this.parent && this.parent.level; + + if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (info && !this.format) { + return this.log(info, callback); + } + + var errState = void 0; + var transformed = void 0; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform(Object.assign({}, info), this.format.options); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + callback(); + if (errState) throw errState; + return; + } + + return this.log(transformed, callback); + } + this._writableState.sync = false; + return callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +TransportStream.prototype._writev = function _writev(chunks, callback) { + if (this.logv) { + var infos = chunks.filter(this._accept, this); + if (!infos.length) { + return callback(null); + } + + // Remark (indexzero): from a performance perspective if Transport + // implementers do choose to implement logv should we make it their + // responsibility to invoke their format? + return this.logv(infos, callback); + } + + for (var i = 0; i < chunks.length; i++) { + if (!this._accept(chunks[i])) continue; + + if (chunks[i].chunk && !this.format) { + this.log(chunks[i].chunk, chunks[i].callback); + continue; + } + + var errState = void 0; + var transformed = void 0; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform(Object.assign({}, chunks[i].chunk), this.format.options); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + chunks[i].callback(); + if (errState) { + // eslint-disable-next-line callback-return + callback(null); + throw errState; + } + } else { + this.log(transformed, chunks[i].callback); + } + } + + return callback(null); +}; + +/** + * Predicate function that returns true if the specfied `info` on the + * WriteReq, `write`, should be passed down into the derived + * TransportStream's I/O via `.log(info, callback)`. + * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object + * representing the log message. + * @returns {Boolean} - Value indicating if the `write` should be accepted & + * logged. + */ +TransportStream.prototype._accept = function _accept(write) { + var info = write.chunk; + if (this.silent) { + return false; + } + + // We always prefer any explicit level set on the Transport itself + // falling back to any level set on the parent. + var level = this.level || this.parent && this.parent.level; + + // Immediately check the average case: log level filtering. + if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) { + // Ensure the info object is valid based on `{ exception }`: + // 1. { handleExceptions: true }: all `info` objects are valid + // 2. { exception: false }: accepted by all transports. + if (this.handleExceptions || info.exception !== true) { + return true; + } + } + + return false; +}; + +/** + * _nop is short for "No operation" + * @returns {Boolean} Intentionally false. + */ +TransportStream.prototype._nop = function _nop() { + // eslint-disable-next-line no-undefined + return void undefined; +}; \ No newline at end of file diff --git a/nodejs/node_modules/winston-transport/index.d.ts b/nodejs/node_modules/winston-transport/index.d.ts new file mode 100644 index 00000000..2d844682 --- /dev/null +++ b/nodejs/node_modules/winston-transport/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for winston-transport 3.0 +// Project: https://github.com/winstonjs/winston-transport +// Definitions by: DABH +// Definitions: https://github.com/winstonjs/winston-transport + +/// + +import * as stream from 'stream'; +import * as logform from 'logform'; + +declare class TransportStream extends stream.Writable { + public format?: logform.Format; + public level?: string; + public silent?: boolean; + public handleExceptions?: boolean; + public handleRejections?: boolean; + + constructor(opts?: TransportStream.TransportStreamOptions); + + public log?(info: any, next: () => void): any; + public logv?(info: any, next: () => void): any; + public close?(): void; +} + +declare namespace TransportStream { + interface TransportStreamOptions { + format?: logform.Format; + level?: string; + silent?: boolean; + handleExceptions?: boolean; + handleRejections?: boolean; + + log?(info: any, next: () => void): any; + logv?(info: any, next: () => void): any; + close?(): void; + } +} + +export = TransportStream; diff --git a/nodejs/node_modules/winston-transport/index.js b/nodejs/node_modules/winston-transport/index.js new file mode 100644 index 00000000..6a62012a --- /dev/null +++ b/nodejs/node_modules/winston-transport/index.js @@ -0,0 +1,7 @@ +'use strict'; + +// Expose modern transport directly as the export +module.exports = require('./modern'); + +// Expose legacy stream +module.exports.LegacyTransportStream = require('./legacy'); diff --git a/nodejs/node_modules/winston-transport/legacy.js b/nodejs/node_modules/winston-transport/legacy.js new file mode 100644 index 00000000..6cc9522d --- /dev/null +++ b/nodejs/node_modules/winston-transport/legacy.js @@ -0,0 +1,119 @@ +'use strict'; + +const util = require('util'); +const { LEVEL } = require('triple-beam'); +const TransportStream = require('./modern'); + +/** + * Constructor function for the LegacyTransportStream. This is an internal + * wrapper `winston >= 3` uses to wrap older transports implementing + * log(level, message, meta). + * @param {Object} options - Options for this TransportStream instance. + * @param {Transpot} options.transport - winston@2 or older Transport to wrap. + */ + +const LegacyTransportStream = module.exports = function LegacyTransportStream(options = {}) { + TransportStream.call(this, options); + if (!options.transport || typeof options.transport.log !== 'function') { + throw new Error('Invalid transport, must be an object with a log method.'); + } + + this.transport = options.transport; + this.level = this.level || options.transport.level; + this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; + + // Display our deprecation notice. + this._deprecated(); + + // Properly bubble up errors from the transport to the + // LegacyTransportStream instance, but only once no matter how many times + // this transport is shared. + function transportError(err) { + this.emit('error', err, this.transport); + } + + if (!this.transport.__winstonError) { + this.transport.__winstonError = transportError.bind(this); + this.transport.on('error', this.transport.__winstonError); + } +}; + +/* + * Inherit from TransportStream using Node.js built-ins + */ +util.inherits(LegacyTransportStream, TransportStream); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +LegacyTransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || (info.exception === true && !this.handleExceptions)) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. + if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { + this.transport.log(info[LEVEL], info.message, info, this._nop); + } + + callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { + for (let i = 0; i < chunks.length; i++) { + if (this._accept(chunks[i])) { + this.transport.log( + chunks[i].chunk[LEVEL], + chunks[i].chunk.message, + chunks[i].chunk, + this._nop + ); + chunks[i].callback(); + } + } + + return callback(null); +}; + +/** + * Displays a deprecation notice. Defined as a function so it can be + * overriden in tests. + * @returns {undefined} + */ +LegacyTransportStream.prototype._deprecated = function _deprecated() { + // eslint-disable-next-line no-console + console.error([ + `${this.transport.name} is a legacy winston transport. Consider upgrading: `, + '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md' + ].join('\n')); +}; + +/** + * Clean up error handling state on the legacy transport associated + * with this instance. + * @returns {undefined} + */ +LegacyTransportStream.prototype.close = function close() { + if (this.transport.close) { + this.transport.close(); + } + + if (this.transport.__winstonError) { + this.transport.removeListener('error', this.transport.__winstonError); + this.transport.__winstonError = null; + } +}; diff --git a/nodejs/node_modules/winston-transport/modern.js b/nodejs/node_modules/winston-transport/modern.js new file mode 100644 index 00000000..37eeb3d8 --- /dev/null +++ b/nodejs/node_modules/winston-transport/modern.js @@ -0,0 +1,211 @@ +'use strict'; + +const util = require('util'); +const Writable = require('readable-stream/lib/_stream_writable.js'); +const { LEVEL } = require('triple-beam'); + +/** + * Constructor function for the TransportStream. This is the base prototype + * that all `winston >= 3` transports should inherit from. + * @param {Object} options - Options for this TransportStream instance + * @param {String} options.level - Highest level according to RFC5424. + * @param {Boolean} options.handleExceptions - If true, info with + * { exception: true } will be written. + * @param {Function} options.log - Custom log function for simple Transport + * creation + * @param {Function} options.close - Called on "unpipe" from parent. + */ +const TransportStream = module.exports = function TransportStream(options = {}) { + Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + + this.format = options.format; + this.level = options.level; + this.handleExceptions = options.handleExceptions; + this.handleRejections = options.handleRejections; + this.silent = options.silent; + + if (options.log) this.log = options.log; + if (options.logv) this.logv = options.logv; + if (options.close) this.close = options.close; + + // Get the levels from the source we are piped from. + this.once('pipe', logger => { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + this.levels = logger.levels; + this.parent = logger; + }); + + // If and/or when the transport is removed from this instance + this.once('unpipe', src => { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + if (src === this.parent) { + this.parent = null; + if (this.close) { + this.close(); + } + } + }); +}; + +/* + * Inherit from Writeable using Node.js built-ins + */ +util.inherits(TransportStream, Writable); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +TransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || (info.exception === true && !this.handleExceptions)) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. We always + // prefer any explicit level set on the Transport itself falling back to + // any level set on the parent. + const level = this.level || (this.parent && this.parent.level); + + if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (info && !this.format) { + return this.log(info, callback); + } + + let errState; + let transformed; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform(Object.assign({}, info), this.format.options); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + callback(); + if (errState) throw errState; + return; + } + + return this.log(transformed, callback); + } + this._writableState.sync = false; + return callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +TransportStream.prototype._writev = function _writev(chunks, callback) { + if (this.logv) { + const infos = chunks.filter(this._accept, this); + if (!infos.length) { + return callback(null); + } + + // Remark (indexzero): from a performance perspective if Transport + // implementers do choose to implement logv should we make it their + // responsibility to invoke their format? + return this.logv(infos, callback); + } + + for (let i = 0; i < chunks.length; i++) { + if (!this._accept(chunks[i])) continue; + + if (chunks[i].chunk && !this.format) { + this.log(chunks[i].chunk, chunks[i].callback); + continue; + } + + let errState; + let transformed; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform( + Object.assign({}, chunks[i].chunk), + this.format.options + ); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + chunks[i].callback(); + if (errState) { + // eslint-disable-next-line callback-return + callback(null); + throw errState; + } + } else { + this.log(transformed, chunks[i].callback); + } + } + + return callback(null); +}; + +/** + * Predicate function that returns true if the specfied `info` on the + * WriteReq, `write`, should be passed down into the derived + * TransportStream's I/O via `.log(info, callback)`. + * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object + * representing the log message. + * @returns {Boolean} - Value indicating if the `write` should be accepted & + * logged. + */ +TransportStream.prototype._accept = function _accept(write) { + const info = write.chunk; + if (this.silent) { + return false; + } + + // We always prefer any explicit level set on the Transport itself + // falling back to any level set on the parent. + const level = this.level || (this.parent && this.parent.level); + + // Immediately check the average case: log level filtering. + if ( + info.exception === true || + !level || + this.levels[level] >= this.levels[info[LEVEL]] + ) { + // Ensure the info object is valid based on `{ exception }`: + // 1. { handleExceptions: true }: all `info` objects are valid + // 2. { exception: false }: accepted by all transports. + if (this.handleExceptions || info.exception !== true) { + return true; + } + } + + return false; +}; + +/** + * _nop is short for "No operation" + * @returns {Boolean} Intentionally false. + */ +TransportStream.prototype._nop = function _nop() { + // eslint-disable-next-line no-undefined + return void undefined; +}; diff --git a/nodejs/node_modules/winston-transport/package.json b/nodejs/node_modules/winston-transport/package.json new file mode 100644 index 00000000..94a86b25 --- /dev/null +++ b/nodejs/node_modules/winston-transport/package.json @@ -0,0 +1,52 @@ +{ + "name": "winston-transport", + "description": "Base stream implementations for winston@3 and up.", + "version": "4.7.0", + "main": "index.js", + "browser": "dist/index.js", + "scripts": { + "lint": "eslint test/*.js index.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", + "pretest": "npm run lint && npm run build", + "test": "nyc mocha test/*.test.js", + "report": "nyc report --reporter=lcov", + "build": "rimraf dist && babel *.js -d ./dist", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git@github.com:winstonjs/winston-transport.git" + }, + "keywords": [ + "winston", + "transport", + "winston3" + ], + "author": "Charlie Robbins ", + "license": "MIT", + "bugs": { + "url": "https://github.com/winstonjs/winston-transport/issues" + }, + "homepage": "https://github.com/winstonjs/winston-transport#readme", + "dependencies": { + "logform": "^2.3.2", + "readable-stream": "^3.6.0", + "triple-beam": "^1.3.0" + }, + "devDependencies": { + "@types/node": "^20.8.6", + "abstract-winston-transport": ">=0.5.1", + "assume": "^2.3.0", + "babel-cli": "^6.26.0", + "babel-preset-env": "^1.7.0", + "deep-equal": "^2.0.5", + "eslint": "^8.8.0", + "@dabh/eslint-config-populist": "^5.0.0", + "mocha": "^10.0.0", + "nyc": "^15.1.0", + "rimraf": "^5.0.5", + "winston-compat": "^0.1.5" + }, + "engines": { + "node": ">= 12.0.0" + } +} diff --git a/nodejs/node_modules/winston/LICENSE b/nodejs/node_modules/winston/LICENSE new file mode 100644 index 00000000..948d80dd --- /dev/null +++ b/nodejs/node_modules/winston/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Charlie Robbins + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/nodejs/node_modules/winston/README.md b/nodejs/node_modules/winston/README.md new file mode 100644 index 00000000..7ee941fd --- /dev/null +++ b/nodejs/node_modules/winston/README.md @@ -0,0 +1,1247 @@ +# winston + +A logger for just about everything. + +[![Version npm](https://img.shields.io/npm/v/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston) +[![npm Downloads](https://img.shields.io/npm/dm/winston.svg?style=flat-square)](https://npmcharts.com/compare/winston?minimal=true) +[![build status](https://github.com/winstonjs/winston/actions/workflows/ci.yml/badge.svg)](https://github.com/winstonjs/winston/actions/workflows/ci.yml) +[![coverage status](https://coveralls.io/repos/github/winstonjs/winston/badge.svg?branch=master)](https://coveralls.io/github/winstonjs/winston?branch=master) + +[![NPM](https://nodei.co/npm/winston.png?downloads=true&downloadRank=true)](https://nodei.co/npm/winston/) + +## winston@3 + +See the [Upgrade Guide](UPGRADE-3.0.md) for more information. Bug reports and +PRs welcome! + +## Looking for `winston@2.x` documentation? + +Please note that the documentation below is for `winston@3`. +[Read the `winston@2.x` documentation]. + +## Motivation + +`winston` is designed to be a simple and universal logging library with +support for multiple transports. A transport is essentially a storage device +for your logs. Each `winston` logger can have multiple transports (see: +[Transports]) configured at different levels (see: [Logging levels]). For +example, one may want error logs to be stored in a persistent remote location +(like a database), but all logs output to the console or a local file. + +`winston` aims to decouple parts of the logging process to make it more +flexible and extensible. Attention is given to supporting flexibility in log +formatting (see: [Formats]) & levels (see: [Using custom logging levels]), and +ensuring those APIs decoupled from the implementation of transport logging +(i.e. how the logs are stored / indexed, see: [Adding Custom Transports]) to +the API that they exposed to the programmer. + +## Quick Start + +TL;DR? Check out the [quick start example][quick-example] in `./examples/`. +There are a number of other examples in [`./examples/*.js`][examples]. +Don't see an example you think should be there? Submit a pull request +to add it! + +## Usage + +The recommended way to use `winston` is to create your own logger. The +simplest way to do this is using `winston.createLogger`: + +``` js +const winston = require('winston'); + +const logger = winston.createLogger({ + level: 'info', + format: winston.format.json(), + defaultMeta: { service: 'user-service' }, + transports: [ + // + // - Write all logs with importance level of `error` or less to `error.log` + // - Write all logs with importance level of `info` or less to `combined.log` + // + new winston.transports.File({ filename: 'error.log', level: 'error' }), + new winston.transports.File({ filename: 'combined.log' }), + ], +}); + +// +// If we're not in production then log to the `console` with the format: +// `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` +// +if (process.env.NODE_ENV !== 'production') { + logger.add(new winston.transports.Console({ + format: winston.format.simple(), + })); +} +``` + +You may also log directly via the default logger exposed by +`require('winston')`, but this merely intended to be a convenient shared +logger to use throughout your application if you so choose. +Note that the default logger doesn't have any transports by default. +You need add transports by yourself, and leaving the default logger without any +transports may produce a high memory usage issue. + +## Table of contents + +* [Motivation](#motivation) +* [Quick Start](#quick-start) +* [Usage](#usage) +* [Table of Contents](#table-of-contents) +* [Logging](#logging) + * [Creating your logger](#creating-your-own-logger) + * [Streams, `objectMode`, and `info` objects](#streams-objectmode-and-info-objects) +* [Formats] + * [Combining formats](#combining-formats) + * [String interpolation](#string-interpolation) + * [Filtering `info` Objects](#filtering-info-objects) + * [Creating custom formats](#creating-custom-formats) +* [Logging levels] + * [Using logging levels](#using-logging-levels) + * [Using custom logging levels](#using-custom-logging-levels) +* [Transports] + * [Multiple transports of the same type](#multiple-transports-of-the-same-type) + * [Adding Custom Transports](#adding-custom-transports) + * [Common Transport options](#common-transport-options) +* [Exceptions](#exceptions) + * [Handling Uncaught Exceptions with winston](#handling-uncaught-exceptions-with-winston) + * [To Exit or Not to Exit](#to-exit-or-not-to-exit) +* [Rejections](#rejections) + * [Handling Uncaught Promise Rejections with winston](#handling-uncaught-promise-rejections-with-winston) +* [Profiling](#profiling) +* [Streaming Logs](#streaming-logs) +* [Querying Logs](#querying-logs) +* [Further Reading](#further-reading) + * [Using the default logger](#using-the-default-logger) + * [Awaiting logs to be written in `winston`](#awaiting-logs-to-be-written-in-winston) + * [Working with multiple Loggers in `winston`](#working-with-multiple-loggers-in-winston) +* [Installation](#installation) +* [Run Tests](#run-tests) + +## Logging + +Logging levels in `winston` conform to the severity ordering specified by +[RFC5424]: _severity of all levels is assumed to be numerically **ascending** +from most important to least important._ + +``` js +const levels = { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 +}; +``` + +### Creating your own Logger +You get started by creating a logger using `winston.createLogger`: + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.Console(), + new winston.transports.File({ filename: 'combined.log' }) + ] +}); +``` + +A logger accepts the following parameters: + +| Name | Default | Description | +| ------------- | --------------------------- | --------------- | +| `level` | `'info'` | Log only if [`info.level`](#streams-objectmode-and-info-objects) is less than or equal to this level | +| `levels` | `winston.config.npm.levels` | Levels (and colors) representing log priorities | +| `format` | `winston.format.json` | Formatting for `info` messages (see: [Formats]) | +| `transports` | `[]` _(No transports)_ | Set of logging targets for `info` messages | +| `exitOnError` | `true` | If false, handled exceptions will not cause `process.exit` | +| `silent` | `false` | If true, all logs are suppressed | + +The levels provided to `createLogger` will be defined as convenience methods +on the `logger` returned. + +``` js +// +// Logging +// +logger.log({ + level: 'info', + message: 'Hello distributed log files!' +}); + +logger.info('Hello again distributed logs'); +``` + +You can add or remove transports from the `logger` once it has been provided +to you from `winston.createLogger`: + +``` js +const files = new winston.transports.File({ filename: 'combined.log' }); +const console = new winston.transports.Console(); + +logger + .clear() // Remove all transports + .add(console) // Add console transport + .add(files) // Add file transport + .remove(console); // Remove console transport +``` + +You can also wholesale reconfigure a `winston.Logger` instance using the +`configure` method: + +``` js +const logger = winston.createLogger({ + level: 'info', + transports: [ + new winston.transports.Console(), + new winston.transports.File({ filename: 'combined.log' }) + ] +}); + +// +// Replaces the previous transports with those in the +// new configuration wholesale. +// +const DailyRotateFile = require('winston-daily-rotate-file'); +logger.configure({ + level: 'verbose', + transports: [ + new DailyRotateFile(opts) + ] +}); +``` + +### Creating child loggers + +You can create child loggers from existing loggers to pass metadata overrides: + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.Console(), + ] +}); + +const childLogger = logger.child({ requestId: '451' }); +``` +> `.child` is likely to be bugged if you're also extending the `Logger` class, due to some implementation details that make `this` keyword to point to unexpected things. Use with caution. + +### Streams, `objectMode`, and `info` objects + +In `winston`, both `Logger` and `Transport` instances are treated as +[`objectMode`](https://nodejs.org/api/stream.html#stream_object_mode) +streams that accept an `info` object. + +The `info` parameter provided to a given format represents a single log +message. The object itself is mutable. Every `info` must have at least the +`level` and `message` properties: + +``` js +const info = { + level: 'info', // Level of the logging message + message: 'Hey! Log something?' // Descriptive message being logged. +}; +``` + +Properties **besides level and message** are considered as "`meta`". i.e.: + +``` js +const { level, message, ...meta } = info; +``` + +Several of the formats in `logform` itself add additional properties: + +| Property | Format added by | Description | +| ----------- | --------------- | ----------- | +| `splat` | `splat()` | String interpolation splat for `%d %s`-style messages. | +| `timestamp` | `timestamp()` | timestamp the message was received. | +| `label` | `label()` | Custom label associated with each message. | +| `ms` | `ms()` | Number of milliseconds since the previous log message. | + +As a consumer you may add whatever properties you wish – _internal state is +maintained by `Symbol` properties:_ + +- `Symbol.for('level')` _**(READ-ONLY)**:_ equal to `level` property. + **Is treated as immutable by all code.** +- `Symbol.for('message'):` complete string message set by "finalizing formats": + - `json` + - `logstash` + - `printf` + - `prettyPrint` + - `simple` +- `Symbol.for('splat')`: additional string interpolation arguments. _Used + exclusively by `splat()` format._ + +These Symbols are stored in another package: `triple-beam` so that all +consumers of `logform` can have the same Symbol reference. i.e.: + +``` js +const { LEVEL, MESSAGE, SPLAT } = require('triple-beam'); + +console.log(LEVEL === Symbol.for('level')); +// true + +console.log(MESSAGE === Symbol.for('message')); +// true + +console.log(SPLAT === Symbol.for('splat')); +// true +``` + +> **NOTE:** any `{ message }` property in a `meta` object provided will +> automatically be concatenated to any `msg` already provided: For +> example the below will concatenate 'world' onto 'hello': +> +> ``` js +> logger.log('error', 'hello', { message: 'world' }); +> logger.info('hello', { message: 'world' }); +> ``` + +## Formats + +Formats in `winston` can be accessed from `winston.format`. They are +implemented in [`logform`](https://github.com/winstonjs/logform), a separate +module from `winston`. This allows flexibility when writing your own transports +in case you wish to include a default format with your transport. + +In modern versions of `node` template strings are very performant and are the +recommended way for doing most end-user formatting. If you want to bespoke +format your logs, `winston.format.printf` is for you: + +``` js +const { createLogger, format, transports } = require('winston'); +const { combine, timestamp, label, printf } = format; + +const myFormat = printf(({ level, message, label, timestamp }) => { + return `${timestamp} [${label}] ${level}: ${message}`; +}); + +const logger = createLogger({ + format: combine( + label({ label: 'right meow!' }), + timestamp(), + myFormat + ), + transports: [new transports.Console()] +}); +``` + +To see what built-in formats are available and learn more about creating your +own custom logging formats, see [`logform`][logform]. + +### Combining formats + +Any number of formats may be combined into a single format using +`format.combine`. Since `format.combine` takes no `opts`, as a convenience it +returns pre-created instance of the combined format. + +``` js +const { createLogger, format, transports } = require('winston'); +const { combine, timestamp, label, prettyPrint } = format; + +const logger = createLogger({ + format: combine( + label({ label: 'right meow!' }), + timestamp(), + prettyPrint() + ), + transports: [new transports.Console()] +}) + +logger.log({ + level: 'info', + message: 'What time is the testing at?' +}); +// Outputs: +// { level: 'info', +// message: 'What time is the testing at?', +// label: 'right meow!', +// timestamp: '2017-09-30T03:57:26.875Z' } +``` + +### String interpolation + +The `log` method provides the string interpolation using [util.format]. **It +must be enabled using `format.splat()`.** + +Below is an example that defines a format with string interpolation of +messages using `format.splat` and then serializes the entire `info` message +using `format.simple`. + +``` js +const { createLogger, format, transports } = require('winston'); +const logger = createLogger({ + format: format.combine( + format.splat(), + format.simple() + ), + transports: [new transports.Console()] +}); + +// info: test message my string {} +logger.log('info', 'test message %s', 'my string'); + +// info: test message 123 {} +logger.log('info', 'test message %d', 123); + +// info: test message first second {number: 123} +logger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 }); +``` + +### Filtering `info` Objects + +If you wish to filter out a given `info` Object completely when logging then +simply return a falsey value. + +``` js +const { createLogger, format, transports } = require('winston'); + +// Ignore log messages if they have { private: true } +const ignorePrivate = format((info, opts) => { + if (info.private) { return false; } + return info; +}); + +const logger = createLogger({ + format: format.combine( + ignorePrivate(), + format.json() + ), + transports: [new transports.Console()] +}); + +// Outputs: {"level":"error","message":"Public error to share"} +logger.log({ + level: 'error', + message: 'Public error to share' +}); + +// Messages with { private: true } will not be written when logged. +logger.log({ + private: true, + level: 'error', + message: 'This is super secret - hide it.' +}); +``` + +Use of `format.combine` will respect any falsey values return and stop +evaluation of later formats in the series. For example: + +``` js +const { format } = require('winston'); +const { combine, timestamp, label } = format; + +const willNeverThrow = format.combine( + format(info => { return false })(), // Ignores everything + format(info => { throw new Error('Never reached') })() +); +``` + +### Creating custom formats + +Formats are prototypal objects (i.e. class instances) that define a single +method: `transform(info, opts)` and return the mutated `info`: + +- `info`: an object representing the log message. +- `opts`: setting specific to the current instance of the format. + +They are expected to return one of two things: + +- **An `info` Object** representing the modified `info` argument. Object +references need not be preserved if immutability is preferred. All current +built-in formats consider `info` mutable, but [immutablejs] is being +considered for future releases. +- **A falsey value** indicating that the `info` argument should be ignored by the +caller. (See: [Filtering `info` Objects](#filtering-info-objects)) below. + +`winston.format` is designed to be as simple as possible. To define a new +format, simply pass it a `transform(info, opts)` function to get a new +`Format`. + +The named `Format` returned can be used to create as many copies of the given +`Format` as desired: + +``` js +const { format } = require('winston'); + +const volume = format((info, opts) => { + if (opts.yell) { + info.message = info.message.toUpperCase(); + } else if (opts.whisper) { + info.message = info.message.toLowerCase(); + } + + return info; +}); + +// `volume` is now a function that returns instances of the format. +const scream = volume({ yell: true }); +console.dir(scream.transform({ + level: 'info', + message: `sorry for making you YELL in your head!` +}, scream.options)); +// { +// level: 'info' +// message: 'SORRY FOR MAKING YOU YELL IN YOUR HEAD!' +// } + +// `volume` can be used multiple times to create different formats. +const whisper = volume({ whisper: true }); +console.dir(whisper.transform({ + level: 'info', + message: `WHY ARE THEY MAKING US YELL SO MUCH!` +}, whisper.options)); +// { +// level: 'info' +// message: 'why are they making us yell so much!' +// } +``` + +## Logging Levels + +Logging levels in `winston` conform to the severity ordering specified by +[RFC5424]: _severity of all levels is assumed to be numerically **ascending** +from most important to least important._ + +Each `level` is given a specific integer priority. The higher the priority the +more important the message is considered to be, and the lower the +corresponding integer priority. For example, as specified exactly in RFC5424 +the `syslog` levels are prioritized from 0 to 7 (highest to lowest). + +```js +{ + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 +} +``` + +Similarly, `npm` logging levels are prioritized from 0 to 6 (highest to +lowest): + +``` js +{ + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 +} +``` + +If you do not explicitly define the levels that `winston` should use, the +`npm` levels above will be used. + +### Using Logging Levels + +Setting the level for your logging message can be accomplished in one of two +ways. You can pass a string representing the logging level to the log() method +or use the level specified methods defined on every winston Logger. + +``` js +// +// Any logger instance +// +logger.log('silly', "127.0.0.1 - there's no place like home"); +logger.log('debug', "127.0.0.1 - there's no place like home"); +logger.log('verbose', "127.0.0.1 - there's no place like home"); +logger.log('info', "127.0.0.1 - there's no place like home"); +logger.log('warn', "127.0.0.1 - there's no place like home"); +logger.log('error', "127.0.0.1 - there's no place like home"); +logger.info("127.0.0.1 - there's no place like home"); +logger.warn("127.0.0.1 - there's no place like home"); +logger.error("127.0.0.1 - there's no place like home"); + +// +// Default logger +// +winston.log('info', "127.0.0.1 - there's no place like home"); +winston.info("127.0.0.1 - there's no place like home"); +``` + +`winston` allows you to define a `level` property on each transport which +specifies the **maximum** level of messages that a transport should log. For +example, using the `syslog` levels you could log only `error` messages to the +console and everything `info` and below to a file (which includes `error` +messages): + +``` js +const logger = winston.createLogger({ + levels: winston.config.syslog.levels, + transports: [ + new winston.transports.Console({ level: 'error' }), + new winston.transports.File({ + filename: 'combined.log', + level: 'info' + }) + ] +}); +``` + +You may also dynamically change the log level of a transport: + +``` js +const transports = { + console: new winston.transports.Console({ level: 'warn' }), + file: new winston.transports.File({ filename: 'combined.log', level: 'error' }) +}; + +const logger = winston.createLogger({ + transports: [ + transports.console, + transports.file + ] +}); + +logger.info('Will not be logged in either transport!'); +transports.console.level = 'info'; +transports.file.level = 'info'; +logger.info('Will be logged in both transports!'); +``` + +`winston` supports customizable logging levels, defaulting to npm style +logging levels. Levels must be specified at the time of creating your logger. + +### Using Custom Logging Levels + +In addition to the predefined `npm`, `syslog`, and `cli` levels available in +`winston`, you can also choose to define your own: + +``` js +const myCustomLevels = { + levels: { + foo: 0, + bar: 1, + baz: 2, + foobar: 3 + }, + colors: { + foo: 'blue', + bar: 'green', + baz: 'yellow', + foobar: 'red' + } +}; + +const customLevelLogger = winston.createLogger({ + levels: myCustomLevels.levels +}); + +customLevelLogger.foobar('some foobar level-ed message'); +``` + +Although there is slight repetition in this data structure, it enables simple +encapsulation if you do not want to have colors. If you do wish to have +colors, in addition to passing the levels to the Logger itself, you must make +winston aware of them: + +``` js +winston.addColors(myCustomLevels.colors); +``` + +This enables loggers using the `colorize` formatter to appropriately color and style +the output of custom levels. + +Additionally, you can also change background color and font style. +For example, +``` js +baz: 'italic yellow', +foobar: 'bold red cyanBG' +``` + +Possible options are below. + +* Font styles: `bold`, `dim`, `italic`, `underline`, `inverse`, `hidden`, + `strikethrough`. + +* Font foreground colors: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, + `cyan`, `white`, `gray`, `grey`. + +* Background colors: `blackBG`, `redBG`, `greenBG`, `yellowBG`, `blueBG` + `magentaBG`, `cyanBG`, `whiteBG` + +### Colorizing Standard logging levels + +To colorize the standard logging level add +```js +winston.format.combine( + winston.format.colorize(), + winston.format.simple() +); +``` +where `winston.format.simple()` is whatever other formatter you want to use. The `colorize` formatter must come before any formatters adding text you wish to color. + +### Colorizing full log line when json formatting logs + +To colorize the full log line with the json formatter you can apply the following + +```js +winston.format.combine( + winston.format.json(), + winston.format.colorize({ all }) +); +``` + +## Transports + +There are several [core transports] included in `winston`, which leverage the +built-in networking and file I/O offered by Node.js core. In addition, there +are [additional transports] written by members of the community. + +## Multiple transports of the same type + +It is possible to use multiple transports of the same type e.g. +`winston.transports.File` when you construct the transport. + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.File({ + filename: 'combined.log', + level: 'info' + }), + new winston.transports.File({ + filename: 'errors.log', + level: 'error' + }) + ] +}); +``` + +If you later want to remove one of these transports you can do so by using the +transport itself. e.g.: + +``` js +const combinedLogs = logger.transports.find(transport => { + return transport.filename === 'combined.log' +}); + +logger.remove(combinedLogs); +``` + +## Adding Custom Transports + +Adding a custom transport is easy. All you need to do is accept any options +you need, implement a log() method, and consume it with `winston`. + +``` js +const Transport = require('winston-transport'); +const util = require('util'); + +// +// Inherit from `winston-transport` so you can take advantage +// of the base functionality and `.exceptions.handle()`. +// +module.exports = class YourCustomTransport extends Transport { + constructor(opts) { + super(opts); + // + // Consume any custom options here. e.g.: + // - Connection information for databases + // - Authentication information for APIs (e.g. loggly, papertrail, + // logentries, etc.). + // + } + + log(info, callback) { + setImmediate(() => { + this.emit('logged', info); + }); + + // Perform the writing to the remote service + callback(); + } +}; +``` + +## Common Transport options + +As every transport inherits from [winston-transport], it's possible to set +a custom format and a custom log level on each transport separately: + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.File({ + filename: 'error.log', + level: 'error', + format: winston.format.json() + }), + new winston.transports.Http({ + level: 'warn', + format: winston.format.json() + }), + new winston.transports.Console({ + level: 'info', + format: winston.format.combine( + winston.format.colorize(), + winston.format.simple() + ) + }) + ] +}); +``` + +## Exceptions + +### Handling Uncaught Exceptions with winston + +With `winston`, it is possible to catch and log `uncaughtException` events +from your process. With your own logger instance you can enable this behavior +when it's created or later on in your applications lifecycle: + +``` js +const { createLogger, transports } = require('winston'); + +// Enable exception handling when you create your logger. +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ], + exceptionHandlers: [ + new transports.File({ filename: 'exceptions.log' }) + ] +}); + +// Or enable it later on by adding a transport or using `.exceptions.handle` +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ] +}); + +// Call exceptions.handle with a transport to handle exceptions +logger.exceptions.handle( + new transports.File({ filename: 'exceptions.log' }) +); +``` + +If you want to use this feature with the default logger, simply call +`.exceptions.handle()` with a transport instance. + +``` js +// +// You can add a separate exception logger by passing it to `.exceptions.handle` +// +winston.exceptions.handle( + new winston.transports.File({ filename: 'path/to/exceptions.log' }) +); + +// +// Alternatively you can set `handleExceptions` to true when adding transports +// to winston. +// +winston.add(new winston.transports.File({ + filename: 'path/to/combined.log', + handleExceptions: true +})); +``` + +### To Exit or Not to Exit + +By default, winston will exit after logging an uncaughtException. If this is +not the behavior you want, set `exitOnError = false` + +``` js +const logger = winston.createLogger({ exitOnError: false }); + +// +// or, like this: +// +logger.exitOnError = false; +``` + +When working with custom logger instances, you can pass in separate transports +to the `exceptionHandlers` property or set `handleExceptions` on any +transport. + +##### Example 1 + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.File({ filename: 'path/to/combined.log' }) + ], + exceptionHandlers: [ + new winston.transports.File({ filename: 'path/to/exceptions.log' }) + ] +}); +``` + +##### Example 2 + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.Console({ + handleExceptions: true + }) + ], + exitOnError: false +}); +``` + +The `exitOnError` option can also be a function to prevent exit on only +certain types of errors: + +``` js +function ignoreEpipe(err) { + return err.code !== 'EPIPE'; +} + +const logger = winston.createLogger({ exitOnError: ignoreEpipe }); + +// +// or, like this: +// +logger.exitOnError = ignoreEpipe; +``` + +## Rejections + +### Handling Uncaught Promise Rejections with winston + +With `winston`, it is possible to catch and log `unhandledRejection` events +from your process. With your own logger instance you can enable this behavior +when it's created or later on in your applications lifecycle: + +``` js +const { createLogger, transports } = require('winston'); + +// Enable rejection handling when you create your logger. +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ], + rejectionHandlers: [ + new transports.File({ filename: 'rejections.log' }) + ] +}); + +// Or enable it later on by adding a transport or using `.rejections.handle` +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ] +}); + +// Call rejections.handle with a transport to handle rejections +logger.rejections.handle( + new transports.File({ filename: 'rejections.log' }) +); +``` + +If you want to use this feature with the default logger, simply call +`.rejections.handle()` with a transport instance. + +``` js +// +// You can add a separate rejection logger by passing it to `.rejections.handle` +// +winston.rejections.handle( + new winston.transports.File({ filename: 'path/to/rejections.log' }) +); + +// +// Alternatively you can set `handleRejections` to true when adding transports +// to winston. +// +winston.add(new winston.transports.File({ + filename: 'path/to/combined.log', + handleRejections: true +})); +``` + +## Profiling + +In addition to logging messages and metadata, `winston` also has a simple +profiling mechanism implemented for any logger: + +``` js +// +// Start profile of 'test' +// +logger.profile('test'); + +setTimeout(function () { + // + // Stop profile of 'test'. Logging will now take place: + // '17 Jan 21:00:00 - info: test duration=1000ms' + // + logger.profile('test'); +}, 1000); +``` + +Also you can start a timer and keep a reference that you can call `.done()` +on: + +``` js + // Returns an object corresponding to a specific timing. When done + // is called the timer will finish and log the duration. e.g.: + // + const profiler = logger.startTimer(); + setTimeout(function () { + profiler.done({ message: 'Logging message' }); + }, 1000); +``` + +All profile messages are set to 'info' level by default, and both message and +metadata are optional. For individual profile messages, you can override the default log level by supplying a metadata object with a `level` property: + +```js +logger.profile('test', { level: 'debug' }); +``` + +## Querying Logs + +`winston` supports querying of logs with Loggly-like options. [See Loggly +Search API](https://www.loggly.com/docs/api-retrieving-data/). Specifically: +`File`, `Couchdb`, `Redis`, `Loggly`, `Nssocket`, and `Http`. + +``` js +const options = { + from: new Date() - (24 * 60 * 60 * 1000), + until: new Date(), + limit: 10, + start: 0, + order: 'desc', + fields: ['message'] +}; + +// +// Find items logged between today and yesterday. +// +logger.query(options, function (err, results) { + if (err) { + /* TODO: handle me */ + throw err; + } + + console.log(results); +}); +``` + +## Streaming Logs +Streaming allows you to stream your logs back from your chosen transport. + +``` js +// +// Start at the end. +// +winston.stream({ start: -1 }).on('log', function(log) { + console.log(log); +}); +``` + +## Further Reading + +### Using the Default Logger + +The default logger is accessible through the `winston` module directly. Any +method that you could call on an instance of a logger is available on the +default logger: + +``` js +const winston = require('winston'); + +winston.log('info', 'Hello distributed log files!'); +winston.info('Hello again distributed logs'); + +winston.level = 'debug'; +winston.log('debug', 'Now my debug messages are written to console!'); +``` + +By default, no transports are set on the default logger. You must +add or remove transports via the `add()` and `remove()` methods: + +``` js +const files = new winston.transports.File({ filename: 'combined.log' }); +const console = new winston.transports.Console(); + +winston.add(console); +winston.add(files); +winston.remove(console); +``` + +Or do it with one call to configure(): + +``` js +winston.configure({ + transports: [ + new winston.transports.File({ filename: 'somefile.log' }) + ] +}); +``` + +For more documentation about working with each individual transport supported +by `winston` see the [`winston` Transports](docs/transports.md) document. + +### Awaiting logs to be written in `winston` + +Often it is useful to wait for your logs to be written before exiting the +process. Each instance of `winston.Logger` is also a [Node.js stream]. A +`finish` event will be raised when all logs have flushed to all transports +after the stream has been ended. + +``` js +const transport = new winston.transports.Console(); +const logger = winston.createLogger({ + transports: [transport] +}); + +logger.on('finish', function (info) { + // All `info` log messages has now been logged +}); + +logger.info('CHILL WINSTON!', { seriously: true }); +logger.end(); +``` + +It is also worth mentioning that the logger also emits an 'error' event +if an error occurs within the logger itself which +you should handle or suppress if you don't want unhandled exceptions: + +``` js +// +// Handle errors originating in the logger itself +// +logger.on('error', function (err) { /* Do Something */ }); +``` + +### Working with multiple Loggers in winston + +Often in larger, more complex, applications it is necessary to have multiple +logger instances with different settings. Each logger is responsible for a +different feature area (or category). This is exposed in `winston` in two +ways: through `winston.loggers` and instances of `winston.Container`. In fact, +`winston.loggers` is just a predefined instance of `winston.Container`: + +``` js +const winston = require('winston'); +const { format } = winston; +const { combine, label, json } = format; + +// +// Configure the logger for `category1` +// +winston.loggers.add('category1', { + format: combine( + label({ label: 'category one' }), + json() + ), + transports: [ + new winston.transports.Console({ level: 'silly' }), + new winston.transports.File({ filename: 'somefile.log' }) + ] +}); + +// +// Configure the logger for `category2` +// +winston.loggers.add('category2', { + format: combine( + label({ label: 'category two' }), + json() + ), + transports: [ + new winston.transports.Http({ host: 'localhost', port:8080 }) + ] +}); +``` + +Now that your loggers are setup, you can require winston _in any file in your +application_ and access these pre-configured loggers: + +``` js +const winston = require('winston'); + +// +// Grab your preconfigured loggers +// +const category1 = winston.loggers.get('category1'); +const category2 = winston.loggers.get('category2'); + +category1.info('logging to file and console transports'); +category2.info('logging to http transport'); +``` + +If you prefer to manage the `Container` yourself, you can simply instantiate one: + +``` js +const winston = require('winston'); +const { format } = winston; +const { combine, label, json } = format; + +const container = new winston.Container(); + +container.add('category1', { + format: combine( + label({ label: 'category one' }), + json() + ), + transports: [ + new winston.transports.Console({ level: 'silly' }), + new winston.transports.File({ filename: 'somefile.log' }) + ] +}); + +const category1 = container.get('category1'); +category1.info('logging to file and console transports'); +``` + +## Installation + +``` bash +npm install winston +``` + +``` bash +yarn add winston +``` + +## Run Tests + +All of the winston tests are written with [`mocha`][mocha], [`nyc`][nyc], and +[`assume`][assume]. They can be run with `npm`. + +``` bash +npm test +``` + +#### Author: [Charlie Robbins] +#### Contributors: [Jarrett Cruger], [David Hyde], [Chris Alderson] + +[Transports]: #transports +[Logging levels]: #logging-levels +[Formats]: #formats +[Using custom logging levels]: #using-custom-logging-levels +[Adding Custom Transports]: #adding-custom-transports +[core transports]: docs/transports.md#winston-core +[additional transports]: docs/transports.md#additional-transports + +[RFC5424]: https://tools.ietf.org/html/rfc5424 +[util.format]: https://nodejs.org/dist/latest/docs/api/util.html#util_util_format_format_args +[mocha]: https://mochajs.org +[nyc]: https://github.com/istanbuljs/nyc +[assume]: https://github.com/bigpipe/assume +[logform]: https://github.com/winstonjs/logform#readme +[winston-transport]: https://github.com/winstonjs/winston-transport + +[Read the `winston@2.x` documentation]: https://github.com/winstonjs/winston/tree/2.x + +[quick-example]: https://github.com/winstonjs/winston/blob/master/examples/quick-start.js +[examples]: https://github.com/winstonjs/winston/tree/master/examples + +[Charlie Robbins]: http://github.com/indexzero +[Jarrett Cruger]: https://github.com/jcrugzz +[David Hyde]: https://github.com/dabh +[Chris Alderson]: https://github.com/chrisalderson diff --git a/nodejs/node_modules/winston/dist/winston.js b/nodejs/node_modules/winston/dist/winston.js new file mode 100644 index 00000000..45ed8693 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston.js @@ -0,0 +1,171 @@ +/** + * winston.js: Top-level include defining Winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +var logform = require('logform'); +var _require = require('./winston/common'), + warn = _require.warn; + +/** + * Expose version. Use `require` method for `webpack` support. + * @type {string} + */ +exports.version = require('../package.json').version; +/** + * Include transports defined by default by winston + * @type {Array} + */ +exports.transports = require('./winston/transports'); +/** + * Expose utility methods + * @type {Object} + */ +exports.config = require('./winston/config'); +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ +exports.addColors = logform.levels; +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ +exports.format = logform.format; +/** + * Expose core Logging-related prototypes. + * @type {function} + */ +exports.createLogger = require('./winston/create-logger'); +/** + * Expose core Logging-related prototypes. + * @type {function} + */ +exports.Logger = require('./winston/logger'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +exports.ExceptionHandler = require('./winston/exception-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +exports.RejectionHandler = require('./winston/rejection-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Container} + */ +exports.Container = require('./winston/container'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +exports.Transport = require('winston-transport'); +/** + * We create and expose a default `Container` to `winston.loggers` so that the + * programmer may manage multiple `winston.Logger` instances without any + * additional overhead. + * @example + * // some-file1.js + * const logger = require('winston').loggers.get('something'); + * + * // some-file2.js + * const logger = require('winston').loggers.get('something'); + */ +exports.loggers = new exports.Container(); + +/** + * We create and expose a 'defaultLogger' so that the programmer may do the + * following without the need to create an instance of winston.Logger directly: + * @example + * const winston = require('winston'); + * winston.log('info', 'some message'); + * winston.error('some error'); + */ +var defaultLogger = exports.createLogger(); + +// Pass through the target methods onto `winston. +Object.keys(exports.config.npm.levels).concat(['log', 'query', 'stream', 'add', 'remove', 'clear', 'profile', 'startTimer', 'handleExceptions', 'unhandleExceptions', 'handleRejections', 'unhandleRejections', 'configure', 'child']).forEach(function (method) { + return exports[method] = function () { + return defaultLogger[method].apply(defaultLogger, arguments); + }; +}); + +/** + * Define getter / setter for the default logger level which need to be exposed + * by winston. + * @type {string} + */ +Object.defineProperty(exports, 'level', { + get: function get() { + return defaultLogger.level; + }, + set: function set(val) { + defaultLogger.level = val; + } +}); + +/** + * Define getter for `exceptions` which replaces `handleExceptions` and + * `unhandleExceptions`. + * @type {Object} + */ +Object.defineProperty(exports, 'exceptions', { + get: function get() { + return defaultLogger.exceptions; + } +}); + +/** + * Define getter for `rejections` which replaces `handleRejections` and + * `unhandleRejections`. + * @type {Object} + */ +Object.defineProperty(exports, 'rejections', { + get: function get() { + return defaultLogger.rejections; + } +}); + +/** + * Define getters / setters for appropriate properties of the default logger + * which need to be exposed by winston. + * @type {Logger} + */ +['exitOnError'].forEach(function (prop) { + Object.defineProperty(exports, prop, { + get: function get() { + return defaultLogger[prop]; + }, + set: function set(val) { + defaultLogger[prop] = val; + } + }); +}); + +/** + * The default transports and exceptionHandlers for the default winston logger. + * @type {Object} + */ +Object.defineProperty(exports, 'default', { + get: function get() { + return { + exceptionHandlers: defaultLogger.exceptionHandlers, + rejectionHandlers: defaultLogger.rejectionHandlers, + transports: defaultLogger.transports + }; + } +}); + +// Have friendlier breakage notices for properties that were exposed by default +// on winston < 3.0. +warn.deprecated(exports, 'setLevels'); +warn.forFunctions(exports, 'useFormat', ['cli']); +warn.forProperties(exports, 'useFormat', ['padLevels', 'stripColors']); +warn.forFunctions(exports, 'deprecated', ['addRewriter', 'addFilter', 'clone', 'extend']); +warn.forProperties(exports, 'deprecated', ['emitErrs', 'levelLength']); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/common.js b/nodejs/node_modules/winston/dist/winston/common.js new file mode 100644 index 00000000..38d76882 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/common.js @@ -0,0 +1,44 @@ +/** + * common.js: Internal helper and utility functions for winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +var _require = require('util'), + format = _require.format; + +/** + * Set of simple deprecation notices and a way to expose them for a set of + * properties. + * @type {Object} + * @private + */ +exports.warn = { + deprecated: function deprecated(prop) { + return function () { + throw new Error(format('{ %s } was removed in winston@3.0.0.', prop)); + }; + }, + useFormat: function useFormat(prop) { + return function () { + throw new Error([format('{ %s } was removed in winston@3.0.0.', prop), 'Use a custom winston.format = winston.format(function) instead.'].join('\n')); + }; + }, + forFunctions: function forFunctions(obj, type, props) { + props.forEach(function (prop) { + obj[prop] = exports.warn[type](prop); + }); + }, + forProperties: function forProperties(obj, type, props) { + props.forEach(function (prop) { + var notice = exports.warn[type](prop); + Object.defineProperty(obj, prop, { + get: notice, + set: notice + }); + }); + } +}; \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/config/index.js b/nodejs/node_modules/winston/dist/winston/config/index.js new file mode 100644 index 00000000..17bd7181 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/config/index.js @@ -0,0 +1,36 @@ +/** + * index.js: Default settings for all levels that winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +var logform = require('logform'); +var _require = require('triple-beam'), + configs = _require.configs; + +/** + * Export config set for the CLI. + * @type {Object} + */ +exports.cli = logform.levels(configs.cli); + +/** + * Export config set for npm. + * @type {Object} + */ +exports.npm = logform.levels(configs.npm); + +/** + * Export config set for the syslog. + * @type {Object} + */ +exports.syslog = logform.levels(configs.syslog); + +/** + * Hoist addColors from logform where it was refactored into in winston@3. + * @type {Object} + */ +exports.addColors = logform.levels; \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/container.js b/nodejs/node_modules/winston/dist/winston/container.js new file mode 100644 index 00000000..e2602233 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/container.js @@ -0,0 +1,142 @@ +/** + * container.js: Inversion of control container for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var createLogger = require('./create-logger'); + +/** + * Inversion of control container for winston logger instances. + * @type {Container} + */ +module.exports = /*#__PURE__*/function () { + /** + * Constructor function for the Container object responsible for managing a + * set of `winston.Logger` instances based on string ids. + * @param {!Object} [options={}] - Default pass-thru options for Loggers. + */ + function Container() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, Container); + this.loggers = new Map(); + this.options = options; + } + + /** + * Retrieves a `winston.Logger` instance for the specified `id`. If an + * instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + _createClass(Container, [{ + key: "add", + value: function add(id, options) { + var _this = this; + if (!this.loggers.has(id)) { + // Remark: Simple shallow clone for configuration options in case we pass + // in instantiated protoypal objects + options = Object.assign({}, options || this.options); + var existing = options.transports || this.options.transports; + + // Remark: Make sure if we have an array of transports we slice it to + // make copies of those references. + if (existing) { + options.transports = Array.isArray(existing) ? existing.slice() : [existing]; + } else { + options.transports = []; + } + var logger = createLogger(options); + logger.on('close', function () { + return _this._delete(id); + }); + this.loggers.set(id, logger); + } + return this.loggers.get(id); + } + + /** + * Retreives a `winston.Logger` instance for the specified `id`. If + * an instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + }, { + key: "get", + value: function get(id, options) { + return this.add(id, options); + } + + /** + * Check if the container has a logger with the id. + * @param {?string} id - The id of the Logger instance to find. + * @returns {boolean} - Boolean value indicating if this instance has a + * logger with the specified `id`. + */ + }, { + key: "has", + value: function has(id) { + return !!this.loggers.has(id); + } + + /** + * Closes a `Logger` instance with the specified `id` if it exists. + * If no `id` is supplied then all Loggers are closed. + * @param {?string} id - The id of the Logger instance to close. + * @returns {undefined} + */ + }, { + key: "close", + value: function close(id) { + var _this2 = this; + if (id) { + return this._removeLogger(id); + } + this.loggers.forEach(function (val, key) { + return _this2._removeLogger(key); + }); + } + + /** + * Remove a logger based on the id. + * @param {!string} id - The id of the logger to remove. + * @returns {undefined} + * @private + */ + }, { + key: "_removeLogger", + value: function _removeLogger(id) { + if (!this.loggers.has(id)) { + return; + } + var logger = this.loggers.get(id); + logger.close(); + this._delete(id); + } + + /** + * Deletes a `Logger` instance with the specified `id`. + * @param {!string} id - The id of the Logger instance to delete from + * container. + * @returns {undefined} + * @private + */ + }, { + key: "_delete", + value: function _delete(id) { + this.loggers["delete"](id); + } + }]); + return Container; +}(); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/create-logger.js b/nodejs/node_modules/winston/dist/winston/create-logger.js new file mode 100644 index 00000000..e1d184b5 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/create-logger.js @@ -0,0 +1,123 @@ +/** + * create-logger.js: Logger factory for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var _require = require('triple-beam'), + LEVEL = _require.LEVEL; +var config = require('./config'); +var Logger = require('./logger'); +var debug = require('@dabh/diagnostics')('winston:create-logger'); +function isLevelEnabledFunctionName(level) { + return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled'; +} + +/** + * Create a new instance of a winston Logger. Creates a new + * prototype for each instance. + * @param {!Object} opts - Options for the created logger. + * @returns {Logger} - A newly created logger instance. + */ +module.exports = function () { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + // + // Default levels: npm + // + opts.levels = opts.levels || config.npm.levels; + + /** + * DerivedLogger to attach the logs level methods. + * @type {DerivedLogger} + * @extends {Logger} + */ + var DerivedLogger = /*#__PURE__*/function (_Logger) { + _inherits(DerivedLogger, _Logger); + /** + * Create a new class derived logger for which the levels can be attached to + * the prototype of. This is a V8 optimization that is well know to increase + * performance of prototype functions. + * @param {!Object} options - Options for the created logger. + */ + function DerivedLogger(options) { + _classCallCheck(this, DerivedLogger); + return _callSuper(this, DerivedLogger, [options]); + } + return _createClass(DerivedLogger); + }(Logger); + var logger = new DerivedLogger(opts); + + // + // Create the log level methods for the derived logger. + // + Object.keys(opts.levels).forEach(function (level) { + debug('Define prototype method for "%s"', level); + if (level === 'log') { + // eslint-disable-next-line no-console + console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + return; + } + + // + // Define prototype methods for each log level e.g.: + // logger.log('info', msg) implies these methods are defined: + // - logger.info(msg) + // - logger.isInfoEnabled() + // + // Remark: to support logger.child this **MUST** be a function + // so it'll always be called on the instance instead of a fixed + // place in the prototype chain. + // + DerivedLogger.prototype[level] = function () { + // Prefer any instance scope, but default to "root" logger + var self = this || logger; + + // Optimize the hot-path which is the single object. + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (args.length === 1) { + var msg = args[0]; + var info = msg && msg.message && msg || { + message: msg + }; + info.level = info[LEVEL] = level; + self._addDefaultMeta(info); + self.write(info); + return this || logger; + } + + // When provided nothing assume the empty string + if (args.length === 0) { + self.log(level, ''); + return self; + } + + // Otherwise build argument list which could potentially conform to + // either: + // . v3 API: log(obj) + // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback]) + return self.log.apply(self, [level].concat(args)); + }; + DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () { + return (this || logger).isLevelEnabled(level); + }; + }); + return logger; +}; \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/exception-handler.js b/nodejs/node_modules/winston/dist/winston/exception-handler.js new file mode 100644 index 00000000..78df68f1 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/exception-handler.js @@ -0,0 +1,266 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var os = require('os'); +var asyncForEach = require('async/forEach'); +var debug = require('@dabh/diagnostics')('winston:exception'); +var once = require('one-time'); +var stackTrace = require('stack-trace'); +var ExceptionStream = require('./exception-stream'); + +/** + * Object for handling uncaughtException events. + * @type {ExceptionHandler} + */ +module.exports = /*#__PURE__*/function () { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + function ExceptionHandler(logger) { + _classCallCheck(this, ExceptionHandler); + if (!logger) { + throw new Error('Logger is required to handle exceptions'); + } + this.logger = logger; + this.handlers = new Map(); + } + + /** + * Handles `uncaughtException` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + _createClass(ExceptionHandler, [{ + key: "handle", + value: function handle() { + var _this = this; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + args.forEach(function (arg) { + if (Array.isArray(arg)) { + return arg.forEach(function (handler) { + return _this._addHandler(handler); + }); + } + _this._addHandler(arg); + }); + if (!this.catcher) { + this.catcher = this._uncaughtException.bind(this); + process.on('uncaughtException', this.catcher); + } + } + + /** + * Removes any handlers to `uncaughtException` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + }, { + key: "unhandle", + value: function unhandle() { + var _this2 = this; + if (this.catcher) { + process.removeListener('uncaughtException', this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach(function (wrapper) { + return _this2.logger.unpipe(wrapper); + }); + } + } + + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getAllInfo", + value: function getAllInfo(err) { + var message = null; + if (err) { + message = typeof err === 'string' ? err : err.message; + } + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: ["uncaughtException: ".concat(message || '(no error message)'), err && err.stack || ' No stack trace'].join('\n'), + stack: err && err.stack, + exception: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getProcessInfo", + value: function getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getOsInfo", + value: function getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getTrace", + value: function getTrace(err) { + var trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(function (site) { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + "function": site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + "native": site.isNative() + }; + }); + } + + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + }, { + key: "_addHandler", + value: function _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleExceptions = true; + var wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + }, { + key: "_uncaughtException", + value: function _uncaughtException(err) { + var info = this.getAllInfo(err); + var handlers = this._getExceptionHandlers(); + // Calculate if we should exit on this error + var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError; + var timeout; + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no exception handlers.'); + // eslint-disable-next-line no-console + console.warn('winston: not exiting process.'); + doExit = false; + } + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + if (doExit && !process._exiting) { + // Remark: Currently ignoring any exceptions from transports when + // catching uncaught exceptions. + if (timeout) { + clearTimeout(timeout); + } + // eslint-disable-next-line no-process-exit + process.exit(1); + } + } + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + + // Log to all transports attempting to listen for when they are completed. + asyncForEach(handlers, function (handler, next) { + var done = once(next); + var transport = handler.transport || handler; + + // Debug wrapping so that we can inspect what's going on under the covers. + function onDone(event) { + return function () { + debug(event); + done(); + }; + } + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, function () { + return doExit && gracefulExit(); + }); + this.logger.log(info); + + // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + }, { + key: "_getExceptionHandlers", + value: function _getExceptionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleExceptions: true` + return this.logger.transports.filter(function (wrap) { + var transport = wrap.transport || wrap; + return transport.handleExceptions; + }); + } + }]); + return ExceptionHandler; +}(); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/exception-stream.js b/nodejs/node_modules/winston/dist/winston/exception-stream.js new file mode 100644 index 00000000..d0c62124 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/exception-stream.js @@ -0,0 +1,76 @@ +/** + * exception-stream.js: TODO: add file header handler. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var _require = require('readable-stream'), + Writable = _require.Writable; + +/** + * TODO: add class description. + * @type {ExceptionStream} + * @extends {Writable} + */ +module.exports = /*#__PURE__*/function (_Writable) { + _inherits(ExceptionStream, _Writable); + /** + * Constructor function for the ExceptionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.exception` set to true. + * @param {!TransportStream} transport - Stream to filter to exceptions + */ + function ExceptionStream(transport) { + var _this; + _classCallCheck(this, ExceptionStream); + _this = _callSuper(this, ExceptionStream, [{ + objectMode: true + }]); + if (!transport) { + throw new Error('ExceptionStream requires a TransportStream instance.'); + } + + // Remark (indexzero): we set `handleExceptions` here because it's the + // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers + _this.handleExceptions = true; + _this.transport = transport; + return _this; + } + + /** + * Writes the info object to our transport instance if (and only if) the + * `exception` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _createClass(ExceptionStream, [{ + key: "_write", + value: function _write(info, enc, callback) { + if (info.exception) { + return this.transport.log(info, callback); + } + callback(); + return true; + } + }]); + return ExceptionStream; +}(Writable); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/logger.js b/nodejs/node_modules/winston/dist/winston/logger.js new file mode 100644 index 00000000..ee112c36 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/logger.js @@ -0,0 +1,672 @@ +/** + * logger.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var _require = require('readable-stream'), + Stream = _require.Stream, + Transform = _require.Transform; +var asyncForEach = require('async/forEach'); +var _require2 = require('triple-beam'), + LEVEL = _require2.LEVEL, + SPLAT = _require2.SPLAT; +var isStream = require('is-stream'); +var ExceptionHandler = require('./exception-handler'); +var RejectionHandler = require('./rejection-handler'); +var LegacyTransportStream = require('winston-transport/legacy'); +var Profiler = require('./profiler'); +var _require3 = require('./common'), + warn = _require3.warn; +var config = require('./config'); + +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ +var formatRegExp = /%[scdjifoO%]/g; + +/** + * TODO: add class description. + * @type {Logger} + * @extends {Transform} + */ +var Logger = /*#__PURE__*/function (_Transform) { + _inherits(Logger, _Transform); + /** + * Constructor function for the Logger object responsible for persisting log + * messages and metadata to one or more transports. + * @param {!Object} options - foo + */ + function Logger(options) { + var _this; + _classCallCheck(this, Logger); + _this = _callSuper(this, Logger, [{ + objectMode: true + }]); + _this.configure(options); + return _this; + } + _createClass(Logger, [{ + key: "child", + value: function child(defaultRequestMetadata) { + var logger = this; + return Object.create(logger, { + write: { + value: function value(info) { + var infoClone = Object.assign({}, defaultRequestMetadata, info); + + // Object.assign doesn't copy inherited Error + // properties so we have to do that explicitly + // + // Remark (indexzero): we should remove this + // since the errors format will handle this case. + // + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + } + logger.write(infoClone); + } + } + }); + } + + /** + * This will wholesale reconfigure this instance by: + * 1. Resetting all transports. Older transports will be removed implicitly. + * 2. Set all other options including levels, colors, rewriters, filters, + * exceptionHandlers, etc. + * @param {!Object} options - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "configure", + value: function configure() { + var _this2 = this; + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + silent = _ref.silent, + format = _ref.format, + defaultMeta = _ref.defaultMeta, + levels = _ref.levels, + _ref$level = _ref.level, + level = _ref$level === void 0 ? 'info' : _ref$level, + _ref$exitOnError = _ref.exitOnError, + exitOnError = _ref$exitOnError === void 0 ? true : _ref$exitOnError, + transports = _ref.transports, + colors = _ref.colors, + emitErrs = _ref.emitErrs, + formatters = _ref.formatters, + padLevels = _ref.padLevels, + rewriters = _ref.rewriters, + stripColors = _ref.stripColors, + exceptionHandlers = _ref.exceptionHandlers, + rejectionHandlers = _ref.rejectionHandlers; + // Reset transports if we already have them + if (this.transports.length) { + this.clear(); + } + this.silent = silent; + this.format = format || this.format || require('logform/json')(); + this.defaultMeta = defaultMeta || null; + // Hoist other options onto this instance. + this.levels = levels || this.levels || config.npm.levels; + this.level = level; + if (this.exceptions) { + this.exceptions.unhandle(); + } + if (this.rejections) { + this.rejections.unhandle(); + } + this.exceptions = new ExceptionHandler(this); + this.rejections = new RejectionHandler(this); + this.profilers = {}; + this.exitOnError = exitOnError; + + // Add all transports we have been provided. + if (transports) { + transports = Array.isArray(transports) ? transports : [transports]; + transports.forEach(function (transport) { + return _this2.add(transport); + }); + } + if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) { + throw new Error(['{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', 'Use a custom winston.format(function) instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n')); + } + if (exceptionHandlers) { + this.exceptions.handle(exceptionHandlers); + } + if (rejectionHandlers) { + this.rejections.handle(rejectionHandlers); + } + } + }, { + key: "isLevelEnabled", + value: function isLevelEnabled(level) { + var _this3 = this; + var givenLevelValue = getLevelValue(this.levels, level); + if (givenLevelValue === null) { + return false; + } + var configuredLevelValue = getLevelValue(this.levels, this.level); + if (configuredLevelValue === null) { + return false; + } + if (!this.transports || this.transports.length === 0) { + return configuredLevelValue >= givenLevelValue; + } + var index = this.transports.findIndex(function (transport) { + var transportLevelValue = getLevelValue(_this3.levels, transport.level); + if (transportLevelValue === null) { + transportLevelValue = configuredLevelValue; + } + return transportLevelValue >= givenLevelValue; + }); + return index !== -1; + } + + /* eslint-disable valid-jsdoc */ + /** + * Ensure backwards compatibility with a `log` method + * @param {mixed} level - Level the log message is written at. + * @param {mixed} msg - TODO: add param description. + * @param {mixed} meta - TODO: add param description. + * @returns {Logger} - TODO: add return description. + * + * @example + * // Supports the existing API: + * logger.log('info', 'Hello world', { custom: true }); + * logger.log('info', new Error('Yo, it\'s on fire')); + * + * // Requires winston.format.splat() + * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); + * + * // And the new API with a single JSON literal: + * logger.log({ level: 'info', message: 'Hello world', custom: true }); + * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); + * + * // Also requires winston.format.splat() + * logger.log({ + * level: 'info', + * message: '%s %d%%', + * [SPLAT]: ['A string', 50], + * meta: { thisIsMeta: true } + * }); + * + */ + /* eslint-enable valid-jsdoc */ + }, { + key: "log", + value: function log(level, msg) { + for (var _len = arguments.length, splat = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + splat[_key - 2] = arguments[_key]; + } + // eslint-disable-line max-params + // Optimize for the hotpath of logging JSON literals + if (arguments.length === 1) { + // Yo dawg, I heard you like levels ... seriously ... + // In this context the LHS `level` here is actually the `info` so read + // this as: info[LEVEL] = info.level; + level[LEVEL] = level.level; + this._addDefaultMeta(level); + this.write(level); + return this; + } + + // Slightly less hotpath, but worth optimizing for. + if (arguments.length === 2) { + if (msg && _typeof(msg) === 'object') { + msg[LEVEL] = msg.level = level; + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + msg = _defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), "level", level), "message", msg); + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + var meta = splat[0]; + if (_typeof(meta) === 'object' && meta !== null) { + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + var tokens = msg && msg.match && msg.match(formatRegExp); + if (!tokens) { + var info = Object.assign({}, this.defaultMeta, meta, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), SPLAT, splat), "level", level), "message", msg)); + if (meta.message) info.message = "".concat(info.message, " ").concat(meta.message); + if (meta.stack) info.stack = meta.stack; + this.write(info); + return this; + } + } + this.write(Object.assign({}, this.defaultMeta, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), SPLAT, splat), "level", level), "message", msg))); + return this; + } + + /** + * Pushes data so that it can be picked up by all of our pipe targets. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - Continues stream processing. + * @returns {undefined} + * @private + */ + }, { + key: "_transform", + value: function _transform(info, enc, callback) { + if (this.silent) { + return callback(); + } + + // [LEVEL] is only soft guaranteed to be set here since we are a proper + // stream. It is likely that `info` came in through `.log(info)` or + // `.info(info)`. If it is not defined, however, define it. + // This LEVEL symbol is provided by `triple-beam` and also used in: + // - logform + // - winston-transport + // - abstract-winston-transport + if (!info[LEVEL]) { + info[LEVEL] = info.level; + } + + // Remark: really not sure what to do here, but this has been reported as + // very confusing by pre winston@2.0.0 users as quite confusing when using + // custom levels. + if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { + // eslint-disable-next-line no-console + console.error('[winston] Unknown logger level: %s', info[LEVEL]); + } + + // Remark: not sure if we should simply error here. + if (!this._readableState.pipes) { + // eslint-disable-next-line no-console + console.error('[winston] Attempt to write logs with no transports, which can increase memory usage: %j', info); + } + + // Here we write to the `format` pipe-chain, which on `readable` above will + // push the formatted `info` Object onto the buffer for this instance. We trap + // (and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + this.push(this.format.transform(info, this.format.options)); + } finally { + this._writableState.sync = false; + // eslint-disable-next-line callback-return + callback(); + } + } + + /** + * Delays the 'finish' event until all transport pipe targets have + * also emitted 'finish' or are already finished. + * @param {mixed} callback - Continues stream processing. + */ + }, { + key: "_final", + value: function _final(callback) { + var transports = this.transports.slice(); + asyncForEach(transports, function (transport, next) { + if (!transport || transport.finished) return setImmediate(next); + transport.once('finish', next); + transport.end(); + }, callback); + } + + /** + * Adds the transport to this logger instance by piping to it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + }, { + key: "add", + value: function add(transport) { + // Support backwards compatibility with all existing `winston < 3.x.x` + // transports which meet one of two criteria: + // 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream. + // 2. They expose a log method which has a length greater than 2 (i.e. more then + // just `log(info, callback)`. + var target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({ + transport: transport + }) : transport; + if (!target._writableState || !target._writableState.objectMode) { + throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.'); + } + + // Listen for the `error` event and the `warn` event on the new Transport. + this._onEvent('error', target); + this._onEvent('warn', target); + this.pipe(target); + if (transport.handleExceptions) { + this.exceptions.handle(); + } + if (transport.handleRejections) { + this.rejections.handle(); + } + return this; + } + + /** + * Removes the transport from this logger instance by unpiping from it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + }, { + key: "remove", + value: function remove(transport) { + if (!transport) return this; + var target = transport; + if (!isStream(transport) || transport.log.length > 2) { + target = this.transports.filter(function (match) { + return match.transport === transport; + })[0]; + } + if (target) { + this.unpipe(target); + } + return this; + } + + /** + * Removes all transports from this logger instance. + * @returns {Logger} - TODO: add return description. + */ + }, { + key: "clear", + value: function clear() { + this.unpipe(); + return this; + } + + /** + * Cleans up resources (streams, event listeners) for all transports + * associated with this instance (if necessary). + * @returns {Logger} - TODO: add return description. + */ + }, { + key: "close", + value: function close() { + this.exceptions.unhandle(); + this.rejections.unhandle(); + this.clear(); + this.emit('close'); + return this; + } + + /** + * Sets the `target` levels specified on this instance. + * @param {Object} Target levels to use on this instance. + */ + }, { + key: "setLevels", + value: function setLevels() { + warn.deprecated('setLevels'); + } + + /** + * Queries the all transports for this instance with the specified `options`. + * This will aggregate each transport's results into one object containing + * a property per transport. + * @param {Object} options - Query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + */ + }, { + key: "query", + value: function query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + var results = {}; + var queryObject = Object.assign({}, options.query || {}); + + // Helper function to query a single transport + function queryTransport(transport, next) { + if (options.query && typeof transport.formatQuery === 'function') { + options.query = transport.formatQuery(queryObject); + } + transport.query(options, function (err, res) { + if (err) { + return next(err); + } + if (typeof transport.formatResults === 'function') { + res = transport.formatResults(res, options.format); + } + next(null, res); + }); + } + + // Helper function to accumulate the results from `queryTransport` into + // the `results`. + function addResults(transport, next) { + queryTransport(transport, function (err, result) { + // queryTransport could potentially invoke the callback multiple times + // since Transport code can be unpredictable. + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + + // eslint-disable-next-line callback-return + next(); + } + next = null; + }); + } + + // Iterate over the transports in parallel setting the appropriate key in + // the `results`. + asyncForEach(this.transports.filter(function (transport) { + return !!transport.query; + }), addResults, function () { + return callback(null, results); + }); + } + + /** + * Returns a log stream for all transports. Options object is optional. + * @param{Object} options={} - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + */ + }, { + key: "stream", + value: function stream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var out = new Stream(); + var streams = []; + out._streams = streams; + out.destroy = function () { + var i = streams.length; + while (i--) { + streams[i].destroy(); + } + }; + + // Create a list of all transports for this instance. + this.transports.filter(function (transport) { + return !!transport.stream; + }).forEach(function (transport) { + var str = transport.stream(options); + if (!str) { + return; + } + streams.push(str); + str.on('log', function (log) { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit('log', log); + }); + str.on('error', function (err) { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit('error', err); + }); + }); + return out; + } + + /** + * Returns an object corresponding to a specific timing. When done is called + * the timer will finish and log the duration. e.g.: + * @returns {Profile} - TODO: add return description. + * @example + * const timer = winston.startTimer() + * setTimeout(() => { + * timer.done({ + * message: 'Logging message' + * }); + * }, 1000); + */ + }, { + key: "startTimer", + value: function startTimer() { + return new Profiler(this); + } + + /** + * Tracks the time inbetween subsequent calls to this method with the same + * `id` parameter. The second call to this method will log the difference in + * milliseconds along with the message. + * @param {string} id Unique id of the profiler + * @returns {Logger} - TODO: add return description. + */ + }, { + key: "profile", + value: function profile(id) { + var time = Date.now(); + if (this.profilers[id]) { + var timeEnd = this.profilers[id]; + delete this.profilers[id]; + + // Attempt to be kind to users if they are still using older APIs. + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + if (typeof args[args.length - 2] === 'function') { + // eslint-disable-next-line no-console + console.warn('Callback function no longer supported as of winston@3.0.0'); + args.pop(); + } + + // Set the duration property of the metadata + var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = time - timeEnd; + info.message = info.message || id; + return this.write(info); + } + this.profilers[id] = time; + return this; + } + + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + }, { + key: "handleExceptions", + value: function handleExceptions() { + var _this$exceptions; + // eslint-disable-next-line no-console + console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()'); + (_this$exceptions = this.exceptions).handle.apply(_this$exceptions, arguments); + } + + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + }, { + key: "unhandleExceptions", + value: function unhandleExceptions() { + var _this$exceptions2; + // eslint-disable-next-line no-console + console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()'); + (_this$exceptions2 = this.exceptions).unhandle.apply(_this$exceptions2, arguments); + } + + /** + * Throw a more meaningful deprecation notice + * @throws {Error} - TODO: add throws description. + */ + }, { + key: "cli", + value: function cli() { + throw new Error(['Logger.cli() was removed in winston@3.0.0', 'Use a custom winston.formats.cli() instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n')); + } + + /** + * Bubbles the `event` that occured on the specified `transport` up + * from this instance. + * @param {string} event - The event that occured + * @param {Object} transport - Transport on which the event occured + * @private + */ + }, { + key: "_onEvent", + value: function _onEvent(event, transport) { + function transportEvent(err) { + // https://github.com/winstonjs/winston/issues/1364 + if (event === 'error' && !this.transports.includes(transport)) { + this.add(transport); + } + this.emit(event, err, transport); + } + if (!transport['__winston' + event]) { + transport['__winston' + event] = transportEvent.bind(this); + transport.on(event, transport['__winston' + event]); + } + } + }, { + key: "_addDefaultMeta", + value: function _addDefaultMeta(msg) { + if (this.defaultMeta) { + Object.assign(msg, this.defaultMeta); + } + } + }]); + return Logger; +}(Transform); +function getLevelValue(levels, level) { + var value = levels[level]; + if (!value && value !== 0) { + return null; + } + return value; +} + +/** + * Represents the current readableState pipe targets for this Logger instance. + * @type {Array|Object} + */ +Object.defineProperty(Logger.prototype, 'transports', { + configurable: false, + enumerable: true, + get: function get() { + var pipes = this._readableState.pipes; + return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + } +}); +module.exports = Logger; \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/profiler.js b/nodejs/node_modules/winston/dist/winston/profiler.js new file mode 100644 index 00000000..795c16b1 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/profiler.js @@ -0,0 +1,66 @@ +/** + * profiler.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * TODO: add class description. + * @type {Profiler} + * @private + */ +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Profiler = /*#__PURE__*/function () { + /** + * Constructor function for the Profiler instance used by + * `Logger.prototype.startTimer`. When done is called the timer will finish + * and log the duration. + * @param {!Logger} logger - TODO: add param description. + * @private + */ + function Profiler(logger) { + _classCallCheck(this, Profiler); + var Logger = require('./logger'); + if (_typeof(logger) !== 'object' || Array.isArray(logger) || !(logger instanceof Logger)) { + throw new Error('Logger is required for profiling'); + } else { + this.logger = logger; + this.start = Date.now(); + } + } + + /** + * Ends the current timer (i.e. Profiler) instance and logs the `msg` along + * with the duration since creation. + * @returns {mixed} - TODO: add return description. + * @private + */ + _createClass(Profiler, [{ + key: "done", + value: function done() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (typeof args[args.length - 1] === 'function') { + // eslint-disable-next-line no-console + console.warn('Callback function no longer supported as of winston@3.0.0'); + args.pop(); + } + var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = Date.now() - this.start; + return this.logger.write(info); + } + }]); + return Profiler; +}(); +; +module.exports = Profiler; \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/rejection-handler.js b/nodejs/node_modules/winston/dist/winston/rejection-handler.js new file mode 100644 index 00000000..51999c84 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/rejection-handler.js @@ -0,0 +1,266 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var os = require('os'); +var asyncForEach = require('async/forEach'); +var debug = require('@dabh/diagnostics')('winston:rejection'); +var once = require('one-time'); +var stackTrace = require('stack-trace'); +var RejectionStream = require('./rejection-stream'); + +/** + * Object for handling unhandledRejection events. + * @type {RejectionHandler} + */ +module.exports = /*#__PURE__*/function () { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + function RejectionHandler(logger) { + _classCallCheck(this, RejectionHandler); + if (!logger) { + throw new Error('Logger is required to handle rejections'); + } + this.logger = logger; + this.handlers = new Map(); + } + + /** + * Handles `unhandledRejection` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + _createClass(RejectionHandler, [{ + key: "handle", + value: function handle() { + var _this = this; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + args.forEach(function (arg) { + if (Array.isArray(arg)) { + return arg.forEach(function (handler) { + return _this._addHandler(handler); + }); + } + _this._addHandler(arg); + }); + if (!this.catcher) { + this.catcher = this._unhandledRejection.bind(this); + process.on('unhandledRejection', this.catcher); + } + } + + /** + * Removes any handlers to `unhandledRejection` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + }, { + key: "unhandle", + value: function unhandle() { + var _this2 = this; + if (this.catcher) { + process.removeListener('unhandledRejection', this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach(function (wrapper) { + return _this2.logger.unpipe(wrapper); + }); + } + } + + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getAllInfo", + value: function getAllInfo(err) { + var message = null; + if (err) { + message = typeof err === 'string' ? err : err.message; + } + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: ["unhandledRejection: ".concat(message || '(no error message)'), err && err.stack || ' No stack trace'].join('\n'), + stack: err && err.stack, + rejection: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getProcessInfo", + value: function getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getOsInfo", + value: function getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "getTrace", + value: function getTrace(err) { + var trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(function (site) { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + "function": site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + "native": site.isNative() + }; + }); + } + + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + }, { + key: "_addHandler", + value: function _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleRejections = true; + var wrapper = new RejectionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + }, { + key: "_unhandledRejection", + value: function _unhandledRejection(err) { + var info = this.getAllInfo(err); + var handlers = this._getRejectionHandlers(); + // Calculate if we should exit on this error + var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError; + var timeout; + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no rejection handlers.'); + // eslint-disable-next-line no-console + console.warn('winston: not exiting process.'); + doExit = false; + } + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + if (doExit && !process._exiting) { + // Remark: Currently ignoring any rejections from transports when + // catching unhandled rejections. + if (timeout) { + clearTimeout(timeout); + } + // eslint-disable-next-line no-process-exit + process.exit(1); + } + } + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + + // Log to all transports attempting to listen for when they are completed. + asyncForEach(handlers, function (handler, next) { + var done = once(next); + var transport = handler.transport || handler; + + // Debug wrapping so that we can inspect what's going on under the covers. + function onDone(event) { + return function () { + debug(event); + done(); + }; + } + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, function () { + return doExit && gracefulExit(); + }); + this.logger.log(info); + + // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + }, { + key: "_getRejectionHandlers", + value: function _getRejectionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleRejections: true` + return this.logger.transports.filter(function (wrap) { + var transport = wrap.transport || wrap; + return transport.handleRejections; + }); + } + }]); + return RejectionHandler; +}(); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/rejection-stream.js b/nodejs/node_modules/winston/dist/winston/rejection-stream.js new file mode 100644 index 00000000..8ebc9776 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/rejection-stream.js @@ -0,0 +1,73 @@ +/** + * rejection-stream.js: TODO: add file header handler. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var _require = require('readable-stream'), + Writable = _require.Writable; + +/** + * TODO: add class description. + * @type {RejectionStream} + * @extends {Writable} + */ +module.exports = /*#__PURE__*/function (_Writable) { + _inherits(RejectionStream, _Writable); + /** + * Constructor function for the RejectionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.rejection` set to true. + * @param {!TransportStream} transport - Stream to filter to rejections + */ + function RejectionStream(transport) { + var _this; + _classCallCheck(this, RejectionStream); + _this = _callSuper(this, RejectionStream, [{ + objectMode: true + }]); + if (!transport) { + throw new Error('RejectionStream requires a TransportStream instance.'); + } + _this.handleRejections = true; + _this.transport = transport; + return _this; + } + + /** + * Writes the info object to our transport instance if (and only if) the + * `rejection` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _createClass(RejectionStream, [{ + key: "_write", + value: function _write(info, enc, callback) { + if (info.rejection) { + return this.transport.log(info, callback); + } + callback(); + return true; + } + }]); + return RejectionStream; +}(Writable); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/tail-file.js b/nodejs/node_modules/winston/dist/winston/tail-file.js new file mode 100644 index 00000000..b47b0ba4 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/tail-file.js @@ -0,0 +1,113 @@ +/** + * tail-file.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +var fs = require('fs'); +var _require = require('string_decoder'), + StringDecoder = _require.StringDecoder; +var _require2 = require('readable-stream'), + Stream = _require2.Stream; + +/** + * Simple no-op function. + * @returns {undefined} + */ +function noop() {} + +/** + * TODO: add function description. + * @param {Object} options - Options for tail. + * @param {function} iter - Iterator function to execute on every line. +* `tail -f` a file. Options must include file. + * @returns {mixed} - TODO: add return description. + */ +module.exports = function (options, iter) { + var buffer = Buffer.alloc(64 * 1024); + var decode = new StringDecoder('utf8'); + var stream = new Stream(); + var buff = ''; + var pos = 0; + var row = 0; + if (options.start === -1) { + delete options.start; + } + stream.readable = true; + stream.destroy = function () { + stream.destroyed = true; + stream.emit('end'); + stream.emit('close'); + }; + fs.open(options.file, 'a+', '0644', function (err, fd) { + if (err) { + if (!iter) { + stream.emit('error', err); + } else { + iter(err); + } + stream.destroy(); + return; + } + (function read() { + if (stream.destroyed) { + fs.close(fd, noop); + return; + } + return fs.read(fd, buffer, 0, buffer.length, pos, function (error, bytes) { + if (error) { + if (!iter) { + stream.emit('error', error); + } else { + iter(error); + } + stream.destroy(); + return; + } + if (!bytes) { + if (buff) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', buff); + } else { + iter(null, buff); + } + } + row++; + buff = ''; + } + return setTimeout(read, 1000); + } + var data = decode.write(buffer.slice(0, bytes)); + if (!iter) { + stream.emit('data', data); + } + data = (buff + data).split(/\n+/); + var l = data.length - 1; + var i = 0; + for (; i < l; i++) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', data[i]); + } else { + iter(null, data[i]); + } + } + row++; + } + buff = data[l]; + pos += bytes; + return read(); + }); + })(); + }); + if (!iter) { + return stream; + } + return stream.destroy; +}; \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/transports/console.js b/nodejs/node_modules/winston/dist/winston/transports/console.js new file mode 100644 index 00000000..b7c7a8f7 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/transports/console.js @@ -0,0 +1,136 @@ +/* eslint-disable no-console */ +/* + * console.js: Transport for outputting to the console. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var os = require('os'); +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; +var TransportStream = require('winston-transport'); + +/** + * Transport for outputting to the console. + * @type {Console} + * @extends {TransportStream} + */ +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(Console, _TransportStream); + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + function Console() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, Console); + _this = _callSuper(this, Console, [options]); + + // Expose the name of this Transport on the prototype + _this.name = options.name || 'console'; + _this.stderrLevels = _this._stringArrayToSet(options.stderrLevels); + _this.consoleWarnLevels = _this._stringArrayToSet(options.consoleWarnLevels); + _this.eol = typeof options.eol === 'string' ? options.eol : os.EOL; + _this.setMaxListeners(30); + return _this; + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + _createClass(Console, [{ + key: "log", + value: function log(info, callback) { + var _this2 = this; + setImmediate(function () { + return _this2.emit('logged', info); + }); + + // Remark: what if there is no raw...? + if (this.stderrLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + console._stderr.write("".concat(info[MESSAGE]).concat(this.eol)); + } else { + // console.error adds a newline + console.error(info[MESSAGE]); + } + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } else if (this.consoleWarnLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + // in Node.js console.warn is an alias for console.error + console._stderr.write("".concat(info[MESSAGE]).concat(this.eol)); + } else { + // console.warn adds a newline + console.warn(info[MESSAGE]); + } + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + if (console._stdout) { + // Node.js maps `process.stdout` to `console._stdout`. + console._stdout.write("".concat(info[MESSAGE]).concat(this.eol)); + } else { + // console.log adds a newline. + console.log(info[MESSAGE]); + } + if (callback) { + callback(); // eslint-disable-line callback-return + } + } + + /** + * Returns a Set-like object with strArray's elements as keys (each with the + * value true). + * @param {Array} strArray - Array of Set-elements as strings. + * @param {?string} [errMsg] - Custom error message thrown on invalid input. + * @returns {Object} - TODO: add return description. + * @private + */ + }, { + key: "_stringArrayToSet", + value: function _stringArrayToSet(strArray, errMsg) { + if (!strArray) return {}; + errMsg = errMsg || 'Cannot make set from type other than Array of string elements'; + if (!Array.isArray(strArray)) { + throw new Error(errMsg); + } + return strArray.reduce(function (set, el) { + if (typeof el !== 'string') { + throw new Error(errMsg); + } + set[el] = true; + return set; + }, {}); + } + }]); + return Console; +}(TransportStream); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/transports/file.js b/nodejs/node_modules/winston/dist/winston/transports/file.js new file mode 100644 index 00000000..2fb6425c --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/transports/file.js @@ -0,0 +1,790 @@ +/* eslint-disable complexity,max-statements */ +/** + * file.js: Transport for outputting to a local log file. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var fs = require('fs'); +var path = require('path'); +var asyncSeries = require('async/series'); +var zlib = require('zlib'); +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +var _require2 = require('readable-stream'), + Stream = _require2.Stream, + PassThrough = _require2.PassThrough; +var TransportStream = require('winston-transport'); +var debug = require('@dabh/diagnostics')('winston:file'); +var os = require('os'); +var tailFile = require('../tail-file'); + +/** + * Transport for outputting to a local log file. + * @type {File} + * @extends {TransportStream} + */ +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(File, _TransportStream); + /** + * Constructor function for the File transport object responsible for + * persisting log messages and metadata to one or more files. + * @param {Object} options - Options for this instance. + */ + function File() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, File); + _this = _callSuper(this, File, [options]); + + // Expose the name of this Transport on the prototype. + _this.name = options.name || 'file'; + + // Helper function which throws an `Error` in the event that any of the + // rest of the arguments is present in `options`. + function throwIf(target) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + args.slice(1).forEach(function (name) { + if (options[name]) { + throw new Error("Cannot set ".concat(name, " and ").concat(target, " together")); + } + }); + } + + // Setup the base stream that always gets piped to to handle buffering. + _this._stream = new PassThrough(); + _this._stream.setMaxListeners(30); + + // Bind this context for listener methods. + _this._onError = _this._onError.bind(_assertThisInitialized(_this)); + if (options.filename || options.dirname) { + throwIf('filename or dirname', 'stream'); + _this._basename = _this.filename = options.filename ? path.basename(options.filename) : 'winston.log'; + _this.dirname = options.dirname || path.dirname(options.filename); + _this.options = options.options || { + flags: 'a' + }; + } else if (options.stream) { + // eslint-disable-next-line no-console + console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream'); + throwIf('stream', 'filename', 'maxsize'); + _this._dest = _this._stream.pipe(_this._setupStream(options.stream)); + _this.dirname = path.dirname(_this._dest.path); + // We need to listen for drain events when write() returns false. This + // can make node mad at times. + } else { + throw new Error('Cannot log to file without filename or stream.'); + } + _this.maxsize = options.maxsize || null; + _this.rotationFormat = options.rotationFormat || false; + _this.zippedArchive = options.zippedArchive || false; + _this.maxFiles = options.maxFiles || null; + _this.eol = typeof options.eol === 'string' ? options.eol : os.EOL; + _this.tailable = options.tailable || false; + _this.lazy = options.lazy || false; + + // Internal state variables representing the number of files this instance + // has created and the current size (in bytes) of the current logfile. + _this._size = 0; + _this._pendingSize = 0; + _this._created = 0; + _this._drain = false; + _this._opening = false; + _this._ending = false; + _this._fileExist = false; + if (_this.dirname) _this._createLogDirIfNotExist(_this.dirname); + if (!_this.lazy) _this.open(); + return _this; + } + _createClass(File, [{ + key: "finishIfEnding", + value: function finishIfEnding() { + var _this2 = this; + if (this._ending) { + if (this._opening) { + this.once('open', function () { + _this2._stream.once('finish', function () { + return _this2.emit('finish'); + }); + setImmediate(function () { + return _this2._stream.end(); + }); + }); + } else { + this._stream.once('finish', function () { + return _this2.emit('finish'); + }); + setImmediate(function () { + return _this2._stream.end(); + }); + } + } + } + + /** + * Core logging method exposed to Winston. Metadata is optional. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "log", + value: function log(info) { + var _this3 = this; + var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; + // Remark: (jcrugzz) What is necessary about this callback(null, true) now + // when thinking about 3.x? Should silent be handled in the base + // TransportStream _write method? + if (this.silent) { + callback(); + return true; + } + + // Output stream buffer is full and has asked us to wait for the drain event + if (this._drain) { + this._stream.once('drain', function () { + _this3._drain = false; + _this3.log(info, callback); + }); + return; + } + if (this._rotate) { + this._stream.once('rotate', function () { + _this3._rotate = false; + _this3.log(info, callback); + }); + return; + } + if (this.lazy) { + if (!this._fileExist) { + if (!this._opening) { + this.open(); + } + this.once('open', function () { + _this3._fileExist = true; + _this3.log(info, callback); + return; + }); + return; + } + if (this._needsNewFile(this._pendingSize)) { + this._dest.once('close', function () { + if (!_this3._opening) { + _this3.open(); + } + _this3.once('open', function () { + _this3.log(info, callback); + return; + }); + return; + }); + return; + } + } + + // Grab the raw string and append the expected EOL. + var output = "".concat(info[MESSAGE]).concat(this.eol); + var bytes = Buffer.byteLength(output); + + // After we have written to the PassThrough check to see if we need + // to rotate to the next file. + // + // Remark: This gets called too early and does not depict when data + // has been actually flushed to disk. + function logged() { + var _this4 = this; + this._size += bytes; + this._pendingSize -= bytes; + debug('logged %s %s', this._size, output); + this.emit('logged', info); + + // Do not attempt to rotate files while rotating + if (this._rotate) { + return; + } + + // Do not attempt to rotate files while opening + if (this._opening) { + return; + } + + // Check to see if we need to end the stream and create a new one. + if (!this._needsNewFile()) { + return; + } + if (this.lazy) { + this._endStream(function () { + _this4.emit('fileclosed'); + }); + return; + } + + // End the current stream, ensure it flushes and create a new one. + // This could potentially be optimized to not run a stat call but its + // the safest way since we are supporting `maxFiles`. + this._rotate = true; + this._endStream(function () { + return _this4._rotateFile(); + }); + } + + // Keep track of the pending bytes being written while files are opening + // in order to properly rotate the PassThrough this._stream when the file + // eventually does open. + this._pendingSize += bytes; + if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) { + this.rotatedWhileOpening = true; + } + var written = this._stream.write(output, logged.bind(this)); + if (!written) { + this._drain = true; + this._stream.once('drain', function () { + _this3._drain = false; + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + debug('written', written, this._drain); + this.finishIfEnding(); + return written; + } + + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * TODO: Refactor me. + */ + }, { + key: "query", + value: function query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = normalizeQuery(options); + var file = path.join(this.dirname, this.filename); + var buff = ''; + var results = []; + var row = 0; + var stream = fs.createReadStream(file, { + encoding: 'utf8' + }); + stream.on('error', function (err) { + if (stream.readable) { + stream.destroy(); + } + if (!callback) { + return; + } + return err.code !== 'ENOENT' ? callback(err) : callback(null, results); + }); + stream.on('data', function (data) { + data = (buff + data).split(/\n+/); + var l = data.length - 1; + var i = 0; + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; + } + buff = data[l]; + }); + stream.on('close', function () { + if (buff) { + add(buff, true); + } + if (options.order === 'desc') { + results = results.reverse(); + } + + // eslint-disable-next-line callback-return + if (callback) callback(null, results); + }); + function add(buff, attempt) { + try { + var log = JSON.parse(buff); + if (check(log)) { + push(log); + } + } catch (e) { + if (!attempt) { + stream.emit('error', e); + } + } + } + function push(log) { + if (options.rows && results.length >= options.rows && options.order !== 'desc') { + if (stream.readable) { + stream.destroy(); + } + return; + } + if (options.fields) { + log = options.fields.reduce(function (obj, key) { + obj[key] = log[key]; + return obj; + }, {}); + } + if (options.order === 'desc') { + if (results.length >= options.rows) { + results.shift(); + } + } + results.push(log); + } + function check(log) { + if (!log) { + return; + } + if (_typeof(log) !== 'object') { + return; + } + var time = new Date(log.timestamp); + if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { + return; + } + return true; + } + function normalizeQuery(options) { + options = options || {}; + + // limit + options.rows = options.rows || options.limit || 10; + + // starting row offset + options.start = options.start || 0; + + // now + options.until = options.until || new Date(); + if (_typeof(options.until) !== 'object') { + options.until = new Date(options.until); + } + + // now - 24 + options.from = options.from || options.until - 24 * 60 * 60 * 1000; + if (_typeof(options.from) !== 'object') { + options.from = new Date(options.from); + } + + // 'asc' or 'desc' + options.order = options.order || 'desc'; + return options; + } + } + + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + * TODO: Refactor me. + */ + }, { + key: "stream", + value: function stream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var file = path.join(this.dirname, this.filename); + var stream = new Stream(); + var tail = { + file: file, + start: options.start + }; + stream.destroy = tailFile(tail, function (err, line) { + if (err) { + return stream.emit('error', err); + } + try { + stream.emit('data', line); + line = JSON.parse(line); + stream.emit('log', line); + } catch (e) { + stream.emit('error', e); + } + }); + return stream; + } + + /** + * Checks to see the filesize of. + * @returns {undefined} + */ + }, { + key: "open", + value: function open() { + var _this5 = this; + // If we do not have a filename then we were passed a stream and + // don't need to keep track of size. + if (!this.filename) return; + if (this._opening) return; + this._opening = true; + + // Stat the target file to get the size and create the stream. + this.stat(function (err, size) { + if (err) { + return _this5.emit('error', err); + } + debug('stat done: %s { size: %s }', _this5.filename, size); + _this5._size = size; + _this5._dest = _this5._createStream(_this5._stream); + _this5._opening = false; + _this5.once('open', function () { + if (_this5._stream.eventNames().includes('rotate')) { + _this5._stream.emit('rotate'); + } else { + _this5._rotate = false; + } + }); + }); + } + + /** + * Stat the file and assess information in order to create the proper stream. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "stat", + value: function stat(callback) { + var _this6 = this; + var target = this._getFile(); + var fullpath = path.join(this.dirname, target); + fs.stat(fullpath, function (err, stat) { + if (err && err.code === 'ENOENT') { + debug('ENOENT ok', fullpath); + // Update internally tracked filename with the new target name. + _this6.filename = target; + return callback(null, 0); + } + if (err) { + debug("err ".concat(err.code, " ").concat(fullpath)); + return callback(err); + } + if (!stat || _this6._needsNewFile(stat.size)) { + // If `stats.size` is greater than the `maxsize` for this + // instance then try again. + return _this6._incFile(function () { + return _this6.stat(callback); + }); + } + + // Once we have figured out what the filename is, set it + // and return the size. + _this6.filename = target; + callback(null, stat.size); + }); + } + + /** + * Closes the stream associated with this instance. + * @param {function} cb - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "close", + value: function close(cb) { + var _this7 = this; + if (!this._stream) { + return; + } + this._stream.end(function () { + if (cb) { + cb(); // eslint-disable-line callback-return + } + _this7.emit('flush'); + _this7.emit('closed'); + }); + } + + /** + * TODO: add method description. + * @param {number} size - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "_needsNewFile", + value: function _needsNewFile(size) { + size = size || this._size; + return this.maxsize && size >= this.maxsize; + } + + /** + * TODO: add method description. + * @param {Error} err - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "_onError", + value: function _onError(err) { + this.emit('error', err); + } + + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "_setupStream", + value: function _setupStream(stream) { + stream.on('error', this._onError); + return stream; + } + + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + }, { + key: "_cleanupStream", + value: function _cleanupStream(stream) { + stream.removeListener('error', this._onError); + stream.destroy(); + return stream; + } + + /** + * TODO: add method description. + */ + }, { + key: "_rotateFile", + value: function _rotateFile() { + var _this8 = this; + this._incFile(function () { + return _this8.open(); + }); + } + + /** + * Unpipe from the stream that has been marked as full and end it so it + * flushes to disk. + * + * @param {function} callback - Callback for when the current file has closed. + * @private + */ + }, { + key: "_endStream", + value: function _endStream() { + var _this9 = this; + var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {}; + if (this._dest) { + this._stream.unpipe(this._dest); + this._dest.end(function () { + _this9._cleanupStream(_this9._dest); + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + } + + /** + * Returns the WritableStream for the active file on this instance. If we + * should gzip the file then a zlib stream is returned. + * + * @param {ReadableStream} source –PassThrough to pipe to the file when open. + * @returns {WritableStream} Stream that writes to disk for the active file. + */ + }, { + key: "_createStream", + value: function _createStream(source) { + var _this10 = this; + var fullpath = path.join(this.dirname, this.filename); + debug('create stream start', fullpath, this.options); + var dest = fs.createWriteStream(fullpath, this.options) + // TODO: What should we do with errors here? + .on('error', function (err) { + return debug(err); + }).on('close', function () { + return debug('close', dest.path, dest.bytesWritten); + }).on('open', function () { + debug('file open ok', fullpath); + _this10.emit('open', fullpath); + source.pipe(dest); + + // If rotation occured during the open operation then we immediately + // start writing to a new PassThrough, begin opening the next file + // and cleanup the previous source and dest once the source has drained. + if (_this10.rotatedWhileOpening) { + _this10._stream = new PassThrough(); + _this10._stream.setMaxListeners(30); + _this10._rotateFile(); + _this10.rotatedWhileOpening = false; + _this10._cleanupStream(dest); + source.end(); + } + }); + debug('create stream ok', fullpath); + return dest; + } + + /** + * TODO: add method description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + }, { + key: "_incFile", + value: function _incFile(callback) { + debug('_incFile', this.filename); + var ext = path.extname(this._basename); + var basename = path.basename(this._basename, ext); + var tasks = []; + if (this.zippedArchive) { + tasks.push(function (cb) { + var num = this._created > 0 && !this.tailable ? this._created : ''; + this._compressFile(path.join(this.dirname, "".concat(basename).concat(num).concat(ext)), path.join(this.dirname, "".concat(basename).concat(num).concat(ext, ".gz")), cb); + }.bind(this)); + } + tasks.push(function (cb) { + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, cb); + } else { + this._checkMaxFilesTailable(ext, basename, cb); + } + }.bind(this)); + asyncSeries(tasks, callback); + } + + /** + * Gets the next filename to use for this instance in the case that log + * filesizes are being capped. + * @returns {string} - TODO: add return description. + * @private + */ + }, { + key: "_getFile", + value: function _getFile() { + var ext = path.extname(this._basename); + var basename = path.basename(this._basename, ext); + var isRotation = this.rotationFormat ? this.rotationFormat() : this._created; + + // Caveat emptor (indexzero): rotationFormat() was broken by design When + // combined with max files because the set of files to unlink is never + // stored. + return !this.tailable && this._created ? "".concat(basename).concat(isRotation).concat(ext) : "".concat(basename).concat(ext); + } + + /** + * Increment the number of files created or checked by this instance. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + }, { + key: "_checkMaxFilesIncrementing", + value: function _checkMaxFilesIncrementing(ext, basename, callback) { + // Check for maxFiles option and delete file. + if (!this.maxFiles || this._created < this.maxFiles) { + return setImmediate(callback); + } + var oldest = this._created - this.maxFiles; + var isOldest = oldest !== 0 ? oldest : ''; + var isZipped = this.zippedArchive ? '.gz' : ''; + var filePath = "".concat(basename).concat(isOldest).concat(ext).concat(isZipped); + var target = path.join(this.dirname, filePath); + fs.unlink(target, callback); + } + + /** + * Roll files forward based on integer, up to maxFiles. e.g. if base if + * file.log and it becomes oversized, roll to file1.log, and allow file.log + * to be re-used. If file is oversized again, roll file1.log to file2.log, + * roll file.log to file1.log, and so on. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + }, { + key: "_checkMaxFilesTailable", + value: function _checkMaxFilesTailable(ext, basename, callback) { + var _this12 = this; + var tasks = []; + if (!this.maxFiles) { + return; + } + + // const isZipped = this.zippedArchive ? '.gz' : ''; + var isZipped = this.zippedArchive ? '.gz' : ''; + for (var x = this.maxFiles - 1; x > 1; x--) { + tasks.push(function (i, cb) { + var _this11 = this; + var fileName = "".concat(basename).concat(i - 1).concat(ext).concat(isZipped); + var tmppath = path.join(this.dirname, fileName); + fs.exists(tmppath, function (exists) { + if (!exists) { + return cb(null); + } + fileName = "".concat(basename).concat(i).concat(ext).concat(isZipped); + fs.rename(tmppath, path.join(_this11.dirname, fileName), cb); + }); + }.bind(this, x)); + } + asyncSeries(tasks, function () { + fs.rename(path.join(_this12.dirname, "".concat(basename).concat(ext).concat(isZipped)), path.join(_this12.dirname, "".concat(basename, "1").concat(ext).concat(isZipped)), callback); + }); + } + + /** + * Compresses src to dest with gzip and unlinks src + * @param {string} src - path to source file. + * @param {string} dest - path to zipped destination file. + * @param {Function} callback - callback called after file has been compressed. + * @returns {undefined} + * @private + */ + }, { + key: "_compressFile", + value: function _compressFile(src, dest, callback) { + fs.access(src, fs.F_OK, function (err) { + if (err) { + return callback(); + } + var gzip = zlib.createGzip(); + var inp = fs.createReadStream(src); + var out = fs.createWriteStream(dest); + out.on('finish', function () { + fs.unlink(src, callback); + }); + inp.pipe(gzip).pipe(out); + }); + } + }, { + key: "_createLogDirIfNotExist", + value: function _createLogDirIfNotExist(dirPath) { + /* eslint-disable no-sync */ + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { + recursive: true + }); + } + /* eslint-enable no-sync */ + } + }]); + return File; +}(TransportStream); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/transports/http.js b/nodejs/node_modules/winston/dist/winston/transports/http.js new file mode 100644 index 00000000..84dec964 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/transports/http.js @@ -0,0 +1,283 @@ +/** + * http.js: Transport for outputting to a json-rpcserver. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var http = require('http'); +var https = require('https'); +var _require = require('readable-stream'), + Stream = _require.Stream; +var TransportStream = require('winston-transport'); +var jsonStringify = require('safe-stable-stringify'); + +/** + * Transport for outputting to a json-rpc server. + * @type {Stream} + * @extends {TransportStream} + */ +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(Http, _TransportStream); + /** + * Constructor function for the Http transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + // eslint-disable-next-line max-statements + function Http() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, Http); + _this = _callSuper(this, Http, [options]); + _this.options = options; + _this.name = options.name || 'http'; + _this.ssl = !!options.ssl; + _this.host = options.host || 'localhost'; + _this.port = options.port; + _this.auth = options.auth; + _this.path = options.path || ''; + _this.agent = options.agent; + _this.headers = options.headers || {}; + _this.headers['content-type'] = 'application/json'; + _this.batch = options.batch || false; + _this.batchInterval = options.batchInterval || 5000; + _this.batchCount = options.batchCount || 10; + _this.batchOptions = []; + _this.batchTimeoutID = -1; + _this.batchCallback = {}; + if (!_this.port) { + _this.port = _this.ssl ? 443 : 80; + } + return _this; + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + _createClass(Http, [{ + key: "log", + value: function log(info, callback) { + var _this2 = this; + this._request(info, null, null, function (err, res) { + if (res && res.statusCode !== 200) { + err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode)); + } + if (err) { + _this2.emit('warn', err); + } else { + _this2.emit('logged', info); + } + }); + + // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering + // and block more requests from happening? + if (callback) { + setImmediate(callback); + } + } + + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * @returns {undefined} + */ + }, { + key: "query", + value: function query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = { + method: 'query', + params: this.normalizeQuery(options) + }; + var auth = options.params.auth || null; + delete options.params.auth; + var path = options.params.path || null; + delete options.params.path; + this._request(options, auth, path, function (err, res, body) { + if (res && res.statusCode !== 200) { + err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode)); + } + if (err) { + return callback(err); + } + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + callback(null, body); + }); + } + + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description + */ + }, { + key: "stream", + value: function stream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var stream = new Stream(); + options = { + method: 'stream', + params: options + }; + var path = options.params.path || null; + delete options.params.path; + var auth = options.params.auth || null; + delete options.params.auth; + var buff = ''; + var req = this._request(options, auth, path); + stream.destroy = function () { + return req.destroy(); + }; + req.on('data', function (data) { + data = (buff + data).split(/\n+/); + var l = data.length - 1; + var i = 0; + for (; i < l; i++) { + try { + stream.emit('log', JSON.parse(data[i])); + } catch (e) { + stream.emit('error', e); + } + } + buff = data[l]; + }); + req.on('error', function (err) { + return stream.emit('error', err); + }); + return stream; + } + + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {Object?} auth - authentication options + * @param {string} path - request path + * @param {function} callback - Continuation to respond to when complete. + */ + }, { + key: "_request", + value: function _request(options, auth, path, callback) { + options = options || {}; + auth = auth || this.auth; + path = path || this.path || ''; + if (this.batch) { + this._doBatch(options, callback, auth, path); + } else { + this._doRequest(options, callback, auth, path); + } + } + + /** + * Send or memorize the options according to batch configuration + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + }, { + key: "_doBatch", + value: function _doBatch(options, callback, auth, path) { + this.batchOptions.push(options); + if (this.batchOptions.length === 1) { + // First message stored, it's time to start the timeout! + var me = this; + this.batchCallback = callback; + this.batchTimeoutID = setTimeout(function () { + // timeout is reached, send all messages to endpoint + me.batchTimeoutID = -1; + me._doBatchRequest(me.batchCallback, auth, path); + }, this.batchInterval); + } + if (this.batchOptions.length === this.batchCount) { + // max batch count is reached, send all messages to endpoint + this._doBatchRequest(this.batchCallback, auth, path); + } + } + + /** + * Initiate a request with the memorized batch options, stop the batch timeout + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + }, { + key: "_doBatchRequest", + value: function _doBatchRequest(callback, auth, path) { + if (this.batchTimeoutID > 0) { + clearTimeout(this.batchTimeoutID); + this.batchTimeoutID = -1; + } + var batchOptionsCopy = this.batchOptions.slice(); + this.batchOptions = []; + this._doRequest(batchOptionsCopy, callback, auth, path); + } + + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + }, { + key: "_doRequest", + value: function _doRequest(options, callback, auth, path) { + // Prepare options for outgoing HTTP request + var headers = Object.assign({}, this.headers); + if (auth && auth.bearer) { + headers.Authorization = "Bearer ".concat(auth.bearer); + } + var req = (this.ssl ? https : http).request(_objectSpread(_objectSpread({}, this.options), {}, { + method: 'POST', + host: this.host, + port: this.port, + path: "/".concat(path.replace(/^\//, '')), + headers: headers, + auth: auth && auth.username && auth.password ? "".concat(auth.username, ":").concat(auth.password) : '', + agent: this.agent + })); + req.on('error', callback); + req.on('response', function (res) { + return res.on('end', function () { + return callback(null, res); + }).resume(); + }); + req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8')); + } + }]); + return Http; +}(TransportStream); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/transports/index.js b/nodejs/node_modules/winston/dist/winston/transports/index.js new file mode 100644 index 00000000..a105ebe6 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/transports/index.js @@ -0,0 +1,56 @@ +/** + * transports.js: Set of all transports Winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * TODO: add property description. + * @type {Console} + */ +Object.defineProperty(exports, 'Console', { + configurable: true, + enumerable: true, + get: function get() { + return require('./console'); + } +}); + +/** + * TODO: add property description. + * @type {File} + */ +Object.defineProperty(exports, 'File', { + configurable: true, + enumerable: true, + get: function get() { + return require('./file'); + } +}); + +/** + * TODO: add property description. + * @type {Http} + */ +Object.defineProperty(exports, 'Http', { + configurable: true, + enumerable: true, + get: function get() { + return require('./http'); + } +}); + +/** + * TODO: add property description. + * @type {Stream} + */ +Object.defineProperty(exports, 'Stream', { + configurable: true, + enumerable: true, + get: function get() { + return require('./stream'); + } +}); \ No newline at end of file diff --git a/nodejs/node_modules/winston/dist/winston/transports/stream.js b/nodejs/node_modules/winston/dist/winston/transports/stream.js new file mode 100644 index 00000000..68a73ef6 --- /dev/null +++ b/nodejs/node_modules/winston/dist/winston/transports/stream.js @@ -0,0 +1,87 @@ +/** + * stream.js: Transport for outputting to any arbitrary stream. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var isStream = require('is-stream'); +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +var os = require('os'); +var TransportStream = require('winston-transport'); + +/** + * Transport for outputting to any arbitrary stream. + * @type {Stream} + * @extends {TransportStream} + */ +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(Stream, _TransportStream); + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + function Stream() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, Stream); + _this = _callSuper(this, Stream, [options]); + if (!options.stream || !isStream(options.stream)) { + throw new Error('options.stream is required.'); + } + + // We need to listen for drain events when write() returns false. This can + // make node mad at times. + _this._stream = options.stream; + _this._stream.setMaxListeners(Infinity); + _this.isObjectMode = options.stream._writableState.objectMode; + _this.eol = typeof options.eol === 'string' ? options.eol : os.EOL; + return _this; + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + _createClass(Stream, [{ + key: "log", + value: function log(info, callback) { + var _this2 = this; + setImmediate(function () { + return _this2.emit('logged', info); + }); + if (this.isObjectMode) { + this._stream.write(info); + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + this._stream.write("".concat(info[MESSAGE]).concat(this.eol)); + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + }]); + return Stream; +}(TransportStream); \ No newline at end of file diff --git a/nodejs/node_modules/winston/index.d.ts b/nodejs/node_modules/winston/index.d.ts new file mode 100644 index 00000000..16297ee6 --- /dev/null +++ b/nodejs/node_modules/winston/index.d.ts @@ -0,0 +1,212 @@ +// Type definitions for winston 3.0 +// Project: https://github.com/winstonjs/winston + +/// + +import * as NodeJSStream from 'stream'; + +import * as logform from 'logform'; +import * as Transport from 'winston-transport'; + +import * as Config from './lib/winston/config/index'; +import * as Transports from './lib/winston/transports/index'; + +declare namespace winston { + // Hoisted namespaces from other modules + export import format = logform.format; + export import Logform = logform; + export import config = Config; + export import transports = Transports; + export import transport = Transport; + + class ExceptionHandler { + constructor(logger: Logger); + logger: Logger; + handlers: Map; + catcher: Function | boolean; + + handle(...transports: Transport[]): void; + unhandle(...transports: Transport[]): void; + getAllInfo(err: string | Error): object; + getProcessInfo(): object; + getOsInfo(): object; + getTrace(err: Error): object; + } + + class RejectionHandler { + constructor(logger: Logger); + logger: Logger; + handlers: Map; + catcher: Function | boolean; + + handle(...transports: Transport[]): void; + unhandle(...transports: Transport[]): void; + getAllInfo(err: string | Error): object; + getProcessInfo(): object; + getOsInfo(): object; + getTrace(err: Error): object; + } + + interface QueryOptions { + rows?: number; + limit?: number; + start?: number; + from?: Date; + until?: Date; + order?: 'asc' | 'desc'; + fields: any; + } + + class Profiler { + logger: Logger; + start: Number; + done(info?: any): boolean; + } + + type LogCallback = ( + error?: any, + level?: string, + message?: string, + meta?: any + ) => void; + + interface LogEntry { + level: string; + message: string; + [optionName: string]: any; + } + + interface LogMethod { + (level: string, message: string, callback: LogCallback): Logger; + (level: string, message: string, meta: any, callback: LogCallback): Logger; + (level: string, message: string, ...meta: any[]): Logger; + (entry: LogEntry): Logger; + (level: string, message: any): Logger; + } + + interface LeveledLogMethod { + (message: string, callback: LogCallback): Logger; + (message: string, meta: any, callback: LogCallback): Logger; + (message: string, ...meta: any[]): Logger; + (message: any): Logger; + (infoObject: object): Logger; + } + + interface LoggerOptions { + levels?: Config.AbstractConfigSetLevels; + silent?: boolean; + format?: logform.Format; + level?: string; + exitOnError?: Function | boolean; + defaultMeta?: any; + transports?: Transport[] | Transport; + handleExceptions?: boolean; + handleRejections?: boolean; + exceptionHandlers?: any; + rejectionHandlers?: any; + } + + class Logger extends NodeJSStream.Transform { + constructor(options?: LoggerOptions); + + silent: boolean; + format: logform.Format; + levels: Config.AbstractConfigSetLevels; + level: string; + transports: Transport[]; + exceptions: ExceptionHandler; + rejections: RejectionHandler; + profilers: object; + exitOnError: Function | boolean; + defaultMeta?: any; + + log: LogMethod; + add(transport: Transport): this; + remove(transport: Transport): this; + clear(): this; + close(): this; + + // for cli and npm levels + error: LeveledLogMethod; + warn: LeveledLogMethod; + help: LeveledLogMethod; + data: LeveledLogMethod; + info: LeveledLogMethod; + debug: LeveledLogMethod; + prompt: LeveledLogMethod; + http: LeveledLogMethod; + verbose: LeveledLogMethod; + input: LeveledLogMethod; + silly: LeveledLogMethod; + + query( + options?: QueryOptions, + callback?: (err: Error, results: any) => void + ): any; + stream(options?: any): NodeJS.ReadableStream; + + startTimer(): Profiler; + profile(id: string | number, meta?: Record): this; + + configure(options: LoggerOptions): void; + + child(options: Object): this; + + isLevelEnabled(level: string): boolean; + isErrorEnabled(): boolean; + isWarnEnabled(): boolean; + isInfoEnabled(): boolean; + isVerboseEnabled(): boolean; + isDebugEnabled(): boolean; + isSillyEnabled(): boolean; + } + + class Container { + loggers: Map; + options: LoggerOptions; + + add(id: string, options?: LoggerOptions): Logger; + get(id: string, options?: LoggerOptions): Logger; + has(id: string): boolean; + close(id?: string): void; + + constructor(options?: LoggerOptions); + } + + let version: string; + let loggers: Container; + + let addColors: (target: Config.AbstractConfigSetColors) => any; + let createLogger: (options?: LoggerOptions) => Logger; + + // Pass-through npm level methods routed to the default logger. + let error: LeveledLogMethod; + let warn: LeveledLogMethod; + let info: LeveledLogMethod; + let http: LeveledLogMethod; + let verbose: LeveledLogMethod; + let debug: LeveledLogMethod; + let silly: LeveledLogMethod; + + // Other pass-through methods routed to the default logger. + let log: LogMethod; + let query: ( + options?: QueryOptions, + callback?: (err: Error, results: any) => void + ) => any; + let stream: (options?: any) => NodeJS.ReadableStream; + let add: (transport: Transport) => Logger; + let remove: (transport: Transport) => Logger; + let clear: () => Logger; + let startTimer: () => Profiler; + let profile: (id: string | number) => Logger; + let configure: (options: LoggerOptions) => void; + let child: (options: Object) => Logger; + let level: string; + let exceptions: ExceptionHandler; + let rejections: RejectionHandler; + let exitOnError: Function | boolean; + // let default: object; +} + +export = winston; diff --git a/nodejs/node_modules/winston/lib/winston.js b/nodejs/node_modules/winston/lib/winston.js new file mode 100644 index 00000000..a063b2b0 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston.js @@ -0,0 +1,191 @@ +/** + * winston.js: Top-level include defining Winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const logform = require('logform'); +const { warn } = require('./winston/common'); + +/** + * Expose version. Use `require` method for `webpack` support. + * @type {string} + */ +exports.version = require('../package.json').version; +/** + * Include transports defined by default by winston + * @type {Array} + */ +exports.transports = require('./winston/transports'); +/** + * Expose utility methods + * @type {Object} + */ +exports.config = require('./winston/config'); +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ +exports.addColors = logform.levels; +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ +exports.format = logform.format; +/** + * Expose core Logging-related prototypes. + * @type {function} + */ +exports.createLogger = require('./winston/create-logger'); +/** + * Expose core Logging-related prototypes. + * @type {function} + */ +exports.Logger = require('./winston/logger'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +exports.ExceptionHandler = require('./winston/exception-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +exports.RejectionHandler = require('./winston/rejection-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Container} + */ +exports.Container = require('./winston/container'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +exports.Transport = require('winston-transport'); +/** + * We create and expose a default `Container` to `winston.loggers` so that the + * programmer may manage multiple `winston.Logger` instances without any + * additional overhead. + * @example + * // some-file1.js + * const logger = require('winston').loggers.get('something'); + * + * // some-file2.js + * const logger = require('winston').loggers.get('something'); + */ +exports.loggers = new exports.Container(); + +/** + * We create and expose a 'defaultLogger' so that the programmer may do the + * following without the need to create an instance of winston.Logger directly: + * @example + * const winston = require('winston'); + * winston.log('info', 'some message'); + * winston.error('some error'); + */ +const defaultLogger = exports.createLogger(); + +// Pass through the target methods onto `winston. +Object.keys(exports.config.npm.levels) + .concat([ + 'log', + 'query', + 'stream', + 'add', + 'remove', + 'clear', + 'profile', + 'startTimer', + 'handleExceptions', + 'unhandleExceptions', + 'handleRejections', + 'unhandleRejections', + 'configure', + 'child' + ]) + .forEach( + method => (exports[method] = (...args) => defaultLogger[method](...args)) + ); + +/** + * Define getter / setter for the default logger level which need to be exposed + * by winston. + * @type {string} + */ +Object.defineProperty(exports, 'level', { + get() { + return defaultLogger.level; + }, + set(val) { + defaultLogger.level = val; + } +}); + +/** + * Define getter for `exceptions` which replaces `handleExceptions` and + * `unhandleExceptions`. + * @type {Object} + */ +Object.defineProperty(exports, 'exceptions', { + get() { + return defaultLogger.exceptions; + } +}); + +/** + * Define getter for `rejections` which replaces `handleRejections` and + * `unhandleRejections`. + * @type {Object} + */ +Object.defineProperty(exports, 'rejections', { + get() { + return defaultLogger.rejections; + } +}); + +/** + * Define getters / setters for appropriate properties of the default logger + * which need to be exposed by winston. + * @type {Logger} + */ +['exitOnError'].forEach(prop => { + Object.defineProperty(exports, prop, { + get() { + return defaultLogger[prop]; + }, + set(val) { + defaultLogger[prop] = val; + } + }); +}); + +/** + * The default transports and exceptionHandlers for the default winston logger. + * @type {Object} + */ +Object.defineProperty(exports, 'default', { + get() { + return { + exceptionHandlers: defaultLogger.exceptionHandlers, + rejectionHandlers: defaultLogger.rejectionHandlers, + transports: defaultLogger.transports + }; + } +}); + +// Have friendlier breakage notices for properties that were exposed by default +// on winston < 3.0. +warn.deprecated(exports, 'setLevels'); +warn.forFunctions(exports, 'useFormat', ['cli']); +warn.forProperties(exports, 'useFormat', ['padLevels', 'stripColors']); +warn.forFunctions(exports, 'deprecated', [ + 'addRewriter', + 'addFilter', + 'clone', + 'extend' +]); +warn.forProperties(exports, 'deprecated', ['emitErrs', 'levelLength']); + diff --git a/nodejs/node_modules/winston/lib/winston/common.js b/nodejs/node_modules/winston/lib/winston/common.js new file mode 100644 index 00000000..ac8e99d4 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/common.js @@ -0,0 +1,46 @@ +/** + * common.js: Internal helper and utility functions for winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { format } = require('util'); + +/** + * Set of simple deprecation notices and a way to expose them for a set of + * properties. + * @type {Object} + * @private + */ +exports.warn = { + deprecated(prop) { + return () => { + throw new Error(format('{ %s } was removed in winston@3.0.0.', prop)); + }; + }, + useFormat(prop) { + return () => { + throw new Error([ + format('{ %s } was removed in winston@3.0.0.', prop), + 'Use a custom winston.format = winston.format(function) instead.' + ].join('\n')); + }; + }, + forFunctions(obj, type, props) { + props.forEach(prop => { + obj[prop] = exports.warn[type](prop); + }); + }, + forProperties(obj, type, props) { + props.forEach(prop => { + const notice = exports.warn[type](prop); + Object.defineProperty(obj, prop, { + get: notice, + set: notice + }); + }); + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/config/index.d.ts b/nodejs/node_modules/winston/lib/winston/config/index.d.ts new file mode 100644 index 00000000..639f317e --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/config/index.d.ts @@ -0,0 +1,99 @@ +// Type definitions for winston 3.0 +// Project: https://github.com/winstonjs/winston + +/// + +declare namespace winston { + interface AbstractConfigSetLevels { + [key: string]: number; + } + + interface AbstractConfigSetColors { + [key: string]: string | string[]; + } + + interface AbstractConfigSet { + levels: AbstractConfigSetLevels; + colors: AbstractConfigSetColors; + } + + interface CliConfigSetLevels extends AbstractConfigSetLevels { + error: number; + warn: number; + help: number; + data: number; + info: number; + debug: number; + prompt: number; + verbose: number; + input: number; + silly: number; + } + + interface CliConfigSetColors extends AbstractConfigSetColors { + error: string | string[]; + warn: string | string[]; + help: string | string[]; + data: string | string[]; + info: string | string[]; + debug: string | string[]; + prompt: string | string[]; + verbose: string | string[]; + input: string | string[]; + silly: string | string[]; + } + + interface NpmConfigSetLevels extends AbstractConfigSetLevels { + error: number; + warn: number; + info: number; + http: number; + verbose: number; + debug: number; + silly: number; + } + + interface NpmConfigSetColors extends AbstractConfigSetColors { + error: string | string[]; + warn: string | string[]; + info: string | string[]; + http: string | string[]; + verbose: string | string[]; + debug: string | string[]; + silly: string | string[]; + } + + interface SyslogConfigSetLevels extends AbstractConfigSetLevels { + emerg: number; + alert: number; + crit: number; + error: number; + warning: number; + notice: number; + info: number; + debug: number; + } + + interface SyslogConfigSetColors extends AbstractConfigSetColors { + emerg: string | string[]; + alert: string | string[]; + crit: string | string[]; + error: string | string[]; + warning: string | string[]; + notice: string | string[]; + info: string | string[]; + debug: string | string[]; + } + + interface Config { + allColors: AbstractConfigSetColors; + cli: { levels: CliConfigSetLevels, colors: CliConfigSetColors }; + npm: { levels: NpmConfigSetLevels, colors: NpmConfigSetColors }; + syslog: { levels: SyslogConfigSetLevels, colors: SyslogConfigSetColors }; + + addColors(colors: AbstractConfigSetColors): void; + } +} + +declare const winston: winston.Config; +export = winston; diff --git a/nodejs/node_modules/winston/lib/winston/config/index.js b/nodejs/node_modules/winston/lib/winston/config/index.js new file mode 100644 index 00000000..6eb79de1 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/config/index.js @@ -0,0 +1,35 @@ +/** + * index.js: Default settings for all levels that winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const logform = require('logform'); +const { configs } = require('triple-beam'); + +/** + * Export config set for the CLI. + * @type {Object} + */ +exports.cli = logform.levels(configs.cli); + +/** + * Export config set for npm. + * @type {Object} + */ +exports.npm = logform.levels(configs.npm); + +/** + * Export config set for the syslog. + * @type {Object} + */ +exports.syslog = logform.levels(configs.syslog); + +/** + * Hoist addColors from logform where it was refactored into in winston@3. + * @type {Object} + */ +exports.addColors = logform.levels; diff --git a/nodejs/node_modules/winston/lib/winston/container.js b/nodejs/node_modules/winston/lib/winston/container.js new file mode 100644 index 00000000..57720306 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/container.js @@ -0,0 +1,118 @@ +/** + * container.js: Inversion of control container for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const createLogger = require('./create-logger'); + +/** + * Inversion of control container for winston logger instances. + * @type {Container} + */ +module.exports = class Container { + /** + * Constructor function for the Container object responsible for managing a + * set of `winston.Logger` instances based on string ids. + * @param {!Object} [options={}] - Default pass-thru options for Loggers. + */ + constructor(options = {}) { + this.loggers = new Map(); + this.options = options; + } + + /** + * Retrieves a `winston.Logger` instance for the specified `id`. If an + * instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + add(id, options) { + if (!this.loggers.has(id)) { + // Remark: Simple shallow clone for configuration options in case we pass + // in instantiated protoypal objects + options = Object.assign({}, options || this.options); + const existing = options.transports || this.options.transports; + + // Remark: Make sure if we have an array of transports we slice it to + // make copies of those references. + if (existing) { + options.transports = Array.isArray(existing) ? existing.slice() : [existing]; + } else { + options.transports = []; + } + + const logger = createLogger(options); + logger.on('close', () => this._delete(id)); + this.loggers.set(id, logger); + } + + return this.loggers.get(id); + } + + /** + * Retreives a `winston.Logger` instance for the specified `id`. If + * an instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + get(id, options) { + return this.add(id, options); + } + + /** + * Check if the container has a logger with the id. + * @param {?string} id - The id of the Logger instance to find. + * @returns {boolean} - Boolean value indicating if this instance has a + * logger with the specified `id`. + */ + has(id) { + return !!this.loggers.has(id); + } + + /** + * Closes a `Logger` instance with the specified `id` if it exists. + * If no `id` is supplied then all Loggers are closed. + * @param {?string} id - The id of the Logger instance to close. + * @returns {undefined} + */ + close(id) { + if (id) { + return this._removeLogger(id); + } + + this.loggers.forEach((val, key) => this._removeLogger(key)); + } + + /** + * Remove a logger based on the id. + * @param {!string} id - The id of the logger to remove. + * @returns {undefined} + * @private + */ + _removeLogger(id) { + if (!this.loggers.has(id)) { + return; + } + + const logger = this.loggers.get(id); + logger.close(); + this._delete(id); + } + + /** + * Deletes a `Logger` instance with the specified `id`. + * @param {!string} id - The id of the Logger instance to delete from + * container. + * @returns {undefined} + * @private + */ + _delete(id) { + this.loggers.delete(id); + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/create-logger.js b/nodejs/node_modules/winston/lib/winston/create-logger.js new file mode 100644 index 00000000..e868aeaa --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/create-logger.js @@ -0,0 +1,104 @@ +/** + * create-logger.js: Logger factory for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { LEVEL } = require('triple-beam'); +const config = require('./config'); +const Logger = require('./logger'); +const debug = require('@dabh/diagnostics')('winston:create-logger'); + +function isLevelEnabledFunctionName(level) { + return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled'; +} + +/** + * Create a new instance of a winston Logger. Creates a new + * prototype for each instance. + * @param {!Object} opts - Options for the created logger. + * @returns {Logger} - A newly created logger instance. + */ +module.exports = function (opts = {}) { + // + // Default levels: npm + // + opts.levels = opts.levels || config.npm.levels; + + /** + * DerivedLogger to attach the logs level methods. + * @type {DerivedLogger} + * @extends {Logger} + */ + class DerivedLogger extends Logger { + /** + * Create a new class derived logger for which the levels can be attached to + * the prototype of. This is a V8 optimization that is well know to increase + * performance of prototype functions. + * @param {!Object} options - Options for the created logger. + */ + constructor(options) { + super(options); + } + } + + const logger = new DerivedLogger(opts); + + // + // Create the log level methods for the derived logger. + // + Object.keys(opts.levels).forEach(function (level) { + debug('Define prototype method for "%s"', level); + if (level === 'log') { + // eslint-disable-next-line no-console + console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + return; + } + + // + // Define prototype methods for each log level e.g.: + // logger.log('info', msg) implies these methods are defined: + // - logger.info(msg) + // - logger.isInfoEnabled() + // + // Remark: to support logger.child this **MUST** be a function + // so it'll always be called on the instance instead of a fixed + // place in the prototype chain. + // + DerivedLogger.prototype[level] = function (...args) { + // Prefer any instance scope, but default to "root" logger + const self = this || logger; + + // Optimize the hot-path which is the single object. + if (args.length === 1) { + const [msg] = args; + const info = msg && msg.message && msg || { message: msg }; + info.level = info[LEVEL] = level; + self._addDefaultMeta(info); + self.write(info); + return (this || logger); + } + + // When provided nothing assume the empty string + if (args.length === 0) { + self.log(level, ''); + return self; + } + + // Otherwise build argument list which could potentially conform to + // either: + // . v3 API: log(obj) + // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback]) + return self.log(level, ...args); + }; + + DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () { + return (this || logger).isLevelEnabled(level); + }; + }); + + return logger; +}; diff --git a/nodejs/node_modules/winston/lib/winston/exception-handler.js b/nodejs/node_modules/winston/lib/winston/exception-handler.js new file mode 100644 index 00000000..a5f2b250 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/exception-handler.js @@ -0,0 +1,245 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const os = require('os'); +const asyncForEach = require('async/forEach'); +const debug = require('@dabh/diagnostics')('winston:exception'); +const once = require('one-time'); +const stackTrace = require('stack-trace'); +const ExceptionStream = require('./exception-stream'); + +/** + * Object for handling uncaughtException events. + * @type {ExceptionHandler} + */ +module.exports = class ExceptionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error('Logger is required to handle exceptions'); + } + + this.logger = logger; + this.handlers = new Map(); + } + + /** + * Handles `uncaughtException` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach(arg => { + if (Array.isArray(arg)) { + return arg.forEach(handler => this._addHandler(handler)); + } + + this._addHandler(arg); + }); + + if (!this.catcher) { + this.catcher = this._uncaughtException.bind(this); + process.on('uncaughtException', this.catcher); + } + } + + /** + * Removes any handlers to `uncaughtException` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener('uncaughtException', this.catcher); + this.catcher = false; + + Array.from(this.handlers.values()) + .forEach(wrapper => this.logger.unpipe(wrapper)); + } + } + + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let message = null; + if (err) { + message = typeof err === 'string' ? err : err.message; + } + + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: [ + `uncaughtException: ${(message || '(no error message)')}`, + err && err.stack || ' No stack trace' + ].join('\n'), + stack: err && err.stack, + exception: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(site => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleExceptions = true; + const wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _uncaughtException(err) { + const info = this.getAllInfo(err); + const handlers = this._getExceptionHandlers(); + // Calculate if we should exit on this error + let doExit = typeof this.logger.exitOnError === 'function' + ? this.logger.exitOnError(err) + : this.logger.exitOnError; + let timeout; + + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no exception handlers.'); + // eslint-disable-next-line no-console + console.warn('winston: not exiting process.'); + doExit = false; + } + + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + + if (doExit && !process._exiting) { + // Remark: Currently ignoring any exceptions from transports when + // catching uncaught exceptions. + if (timeout) { + clearTimeout(timeout); + } + // eslint-disable-next-line no-process-exit + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + + // Log to all transports attempting to listen for when they are completed. + asyncForEach(handlers, (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + + // Debug wrapping so that we can inspect what's going on under the covers. + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, () => doExit && gracefulExit()); + + this.logger.log(info); + + // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getExceptionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleExceptions: true` + return this.logger.transports.filter(wrap => { + const transport = wrap.transport || wrap; + return transport.handleExceptions; + }); + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/exception-stream.js b/nodejs/node_modules/winston/lib/winston/exception-stream.js new file mode 100644 index 00000000..477eba0a --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/exception-stream.js @@ -0,0 +1,54 @@ +/** + * exception-stream.js: TODO: add file header handler. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { Writable } = require('readable-stream'); + +/** + * TODO: add class description. + * @type {ExceptionStream} + * @extends {Writable} + */ +module.exports = class ExceptionStream extends Writable { + /** + * Constructor function for the ExceptionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.exception` set to true. + * @param {!TransportStream} transport - Stream to filter to exceptions + */ + constructor(transport) { + super({ objectMode: true }); + + if (!transport) { + throw new Error('ExceptionStream requires a TransportStream instance.'); + } + + // Remark (indexzero): we set `handleExceptions` here because it's the + // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers + this.handleExceptions = true; + this.transport = transport; + } + + /** + * Writes the info object to our transport instance if (and only if) the + * `exception` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.exception) { + return this.transport.log(info, callback); + } + + callback(); + return true; + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/logger.js b/nodejs/node_modules/winston/lib/winston/logger.js new file mode 100644 index 00000000..5f8758c8 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/logger.js @@ -0,0 +1,676 @@ +/** + * logger.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { Stream, Transform } = require('readable-stream'); +const asyncForEach = require('async/forEach'); +const { LEVEL, SPLAT } = require('triple-beam'); +const isStream = require('is-stream'); +const ExceptionHandler = require('./exception-handler'); +const RejectionHandler = require('./rejection-handler'); +const LegacyTransportStream = require('winston-transport/legacy'); +const Profiler = require('./profiler'); +const { warn } = require('./common'); +const config = require('./config'); + +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ +const formatRegExp = /%[scdjifoO%]/g; + +/** + * TODO: add class description. + * @type {Logger} + * @extends {Transform} + */ +class Logger extends Transform { + /** + * Constructor function for the Logger object responsible for persisting log + * messages and metadata to one or more transports. + * @param {!Object} options - foo + */ + constructor(options) { + super({ objectMode: true }); + this.configure(options); + } + + child(defaultRequestMetadata) { + const logger = this; + return Object.create(logger, { + write: { + value: function (info) { + const infoClone = Object.assign( + {}, + defaultRequestMetadata, + info + ); + + // Object.assign doesn't copy inherited Error + // properties so we have to do that explicitly + // + // Remark (indexzero): we should remove this + // since the errors format will handle this case. + // + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + } + + logger.write(infoClone); + } + } + }); + } + + /** + * This will wholesale reconfigure this instance by: + * 1. Resetting all transports. Older transports will be removed implicitly. + * 2. Set all other options including levels, colors, rewriters, filters, + * exceptionHandlers, etc. + * @param {!Object} options - TODO: add param description. + * @returns {undefined} + */ + configure({ + silent, + format, + defaultMeta, + levels, + level = 'info', + exitOnError = true, + transports, + colors, + emitErrs, + formatters, + padLevels, + rewriters, + stripColors, + exceptionHandlers, + rejectionHandlers + } = {}) { + // Reset transports if we already have them + if (this.transports.length) { + this.clear(); + } + + this.silent = silent; + this.format = format || this.format || require('logform/json')(); + + this.defaultMeta = defaultMeta || null; + // Hoist other options onto this instance. + this.levels = levels || this.levels || config.npm.levels; + this.level = level; + if (this.exceptions) { + this.exceptions.unhandle(); + } + if (this.rejections) { + this.rejections.unhandle(); + } + this.exceptions = new ExceptionHandler(this); + this.rejections = new RejectionHandler(this); + this.profilers = {}; + this.exitOnError = exitOnError; + + // Add all transports we have been provided. + if (transports) { + transports = Array.isArray(transports) ? transports : [transports]; + transports.forEach(transport => this.add(transport)); + } + + if ( + colors || + emitErrs || + formatters || + padLevels || + rewriters || + stripColors + ) { + throw new Error( + [ + '{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', + 'Use a custom winston.format(function) instead.', + 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md' + ].join('\n') + ); + } + + if (exceptionHandlers) { + this.exceptions.handle(exceptionHandlers); + } + if (rejectionHandlers) { + this.rejections.handle(rejectionHandlers); + } + } + + isLevelEnabled(level) { + const givenLevelValue = getLevelValue(this.levels, level); + if (givenLevelValue === null) { + return false; + } + + const configuredLevelValue = getLevelValue(this.levels, this.level); + if (configuredLevelValue === null) { + return false; + } + + if (!this.transports || this.transports.length === 0) { + return configuredLevelValue >= givenLevelValue; + } + + const index = this.transports.findIndex(transport => { + let transportLevelValue = getLevelValue(this.levels, transport.level); + if (transportLevelValue === null) { + transportLevelValue = configuredLevelValue; + } + return transportLevelValue >= givenLevelValue; + }); + return index !== -1; + } + + /* eslint-disable valid-jsdoc */ + /** + * Ensure backwards compatibility with a `log` method + * @param {mixed} level - Level the log message is written at. + * @param {mixed} msg - TODO: add param description. + * @param {mixed} meta - TODO: add param description. + * @returns {Logger} - TODO: add return description. + * + * @example + * // Supports the existing API: + * logger.log('info', 'Hello world', { custom: true }); + * logger.log('info', new Error('Yo, it\'s on fire')); + * + * // Requires winston.format.splat() + * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); + * + * // And the new API with a single JSON literal: + * logger.log({ level: 'info', message: 'Hello world', custom: true }); + * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); + * + * // Also requires winston.format.splat() + * logger.log({ + * level: 'info', + * message: '%s %d%%', + * [SPLAT]: ['A string', 50], + * meta: { thisIsMeta: true } + * }); + * + */ + /* eslint-enable valid-jsdoc */ + log(level, msg, ...splat) { + // eslint-disable-line max-params + // Optimize for the hotpath of logging JSON literals + if (arguments.length === 1) { + // Yo dawg, I heard you like levels ... seriously ... + // In this context the LHS `level` here is actually the `info` so read + // this as: info[LEVEL] = info.level; + level[LEVEL] = level.level; + this._addDefaultMeta(level); + this.write(level); + return this; + } + + // Slightly less hotpath, but worth optimizing for. + if (arguments.length === 2) { + if (msg && typeof msg === 'object') { + msg[LEVEL] = msg.level = level; + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + + msg = { [LEVEL]: level, level, message: msg }; + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + + const [meta] = splat; + if (typeof meta === 'object' && meta !== null) { + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + const tokens = msg && msg.match && msg.match(formatRegExp); + + if (!tokens) { + const info = Object.assign({}, this.defaultMeta, meta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + }); + + if (meta.message) info.message = `${info.message} ${meta.message}`; + if (meta.stack) info.stack = meta.stack; + + this.write(info); + return this; + } + } + + this.write(Object.assign({}, this.defaultMeta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + })); + + return this; + } + + /** + * Pushes data so that it can be picked up by all of our pipe targets. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - Continues stream processing. + * @returns {undefined} + * @private + */ + _transform(info, enc, callback) { + if (this.silent) { + return callback(); + } + + // [LEVEL] is only soft guaranteed to be set here since we are a proper + // stream. It is likely that `info` came in through `.log(info)` or + // `.info(info)`. If it is not defined, however, define it. + // This LEVEL symbol is provided by `triple-beam` and also used in: + // - logform + // - winston-transport + // - abstract-winston-transport + if (!info[LEVEL]) { + info[LEVEL] = info.level; + } + + // Remark: really not sure what to do here, but this has been reported as + // very confusing by pre winston@2.0.0 users as quite confusing when using + // custom levels. + if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { + // eslint-disable-next-line no-console + console.error('[winston] Unknown logger level: %s', info[LEVEL]); + } + + // Remark: not sure if we should simply error here. + if (!this._readableState.pipes) { + // eslint-disable-next-line no-console + console.error( + '[winston] Attempt to write logs with no transports, which can increase memory usage: %j', + info + ); + } + + // Here we write to the `format` pipe-chain, which on `readable` above will + // push the formatted `info` Object onto the buffer for this instance. We trap + // (and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + this.push(this.format.transform(info, this.format.options)); + } finally { + this._writableState.sync = false; + // eslint-disable-next-line callback-return + callback(); + } + } + + /** + * Delays the 'finish' event until all transport pipe targets have + * also emitted 'finish' or are already finished. + * @param {mixed} callback - Continues stream processing. + */ + _final(callback) { + const transports = this.transports.slice(); + asyncForEach( + transports, + (transport, next) => { + if (!transport || transport.finished) return setImmediate(next); + transport.once('finish', next); + transport.end(); + }, + callback + ); + } + + /** + * Adds the transport to this logger instance by piping to it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + add(transport) { + // Support backwards compatibility with all existing `winston < 3.x.x` + // transports which meet one of two criteria: + // 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream. + // 2. They expose a log method which has a length greater than 2 (i.e. more then + // just `log(info, callback)`. + const target = + !isStream(transport) || transport.log.length > 2 + ? new LegacyTransportStream({ transport }) + : transport; + + if (!target._writableState || !target._writableState.objectMode) { + throw new Error( + 'Transports must WritableStreams in objectMode. Set { objectMode: true }.' + ); + } + + // Listen for the `error` event and the `warn` event on the new Transport. + this._onEvent('error', target); + this._onEvent('warn', target); + this.pipe(target); + + if (transport.handleExceptions) { + this.exceptions.handle(); + } + + if (transport.handleRejections) { + this.rejections.handle(); + } + + return this; + } + + /** + * Removes the transport from this logger instance by unpiping from it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + remove(transport) { + if (!transport) return this; + let target = transport; + if (!isStream(transport) || transport.log.length > 2) { + target = this.transports.filter( + match => match.transport === transport + )[0]; + } + + if (target) { + this.unpipe(target); + } + return this; + } + + /** + * Removes all transports from this logger instance. + * @returns {Logger} - TODO: add return description. + */ + clear() { + this.unpipe(); + return this; + } + + /** + * Cleans up resources (streams, event listeners) for all transports + * associated with this instance (if necessary). + * @returns {Logger} - TODO: add return description. + */ + close() { + this.exceptions.unhandle(); + this.rejections.unhandle(); + this.clear(); + this.emit('close'); + return this; + } + + /** + * Sets the `target` levels specified on this instance. + * @param {Object} Target levels to use on this instance. + */ + setLevels() { + warn.deprecated('setLevels'); + } + + /** + * Queries the all transports for this instance with the specified `options`. + * This will aggregate each transport's results into one object containing + * a property per transport. + * @param {Object} options - Query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + */ + query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + const results = {}; + const queryObject = Object.assign({}, options.query || {}); + + // Helper function to query a single transport + function queryTransport(transport, next) { + if (options.query && typeof transport.formatQuery === 'function') { + options.query = transport.formatQuery(queryObject); + } + + transport.query(options, (err, res) => { + if (err) { + return next(err); + } + + if (typeof transport.formatResults === 'function') { + res = transport.formatResults(res, options.format); + } + + next(null, res); + }); + } + + // Helper function to accumulate the results from `queryTransport` into + // the `results`. + function addResults(transport, next) { + queryTransport(transport, (err, result) => { + // queryTransport could potentially invoke the callback multiple times + // since Transport code can be unpredictable. + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + + // eslint-disable-next-line callback-return + next(); + } + + next = null; + }); + } + + // Iterate over the transports in parallel setting the appropriate key in + // the `results`. + asyncForEach( + this.transports.filter(transport => !!transport.query), + addResults, + () => callback(null, results) + ); + } + + /** + * Returns a log stream for all transports. Options object is optional. + * @param{Object} options={} - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + */ + stream(options = {}) { + const out = new Stream(); + const streams = []; + + out._streams = streams; + out.destroy = () => { + let i = streams.length; + while (i--) { + streams[i].destroy(); + } + }; + + // Create a list of all transports for this instance. + this.transports + .filter(transport => !!transport.stream) + .forEach(transport => { + const str = transport.stream(options); + if (!str) { + return; + } + + streams.push(str); + + str.on('log', log => { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit('log', log); + }); + + str.on('error', err => { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit('error', err); + }); + }); + + return out; + } + + /** + * Returns an object corresponding to a specific timing. When done is called + * the timer will finish and log the duration. e.g.: + * @returns {Profile} - TODO: add return description. + * @example + * const timer = winston.startTimer() + * setTimeout(() => { + * timer.done({ + * message: 'Logging message' + * }); + * }, 1000); + */ + startTimer() { + return new Profiler(this); + } + + /** + * Tracks the time inbetween subsequent calls to this method with the same + * `id` parameter. The second call to this method will log the difference in + * milliseconds along with the message. + * @param {string} id Unique id of the profiler + * @returns {Logger} - TODO: add return description. + */ + profile(id, ...args) { + const time = Date.now(); + if (this.profilers[id]) { + const timeEnd = this.profilers[id]; + delete this.profilers[id]; + + // Attempt to be kind to users if they are still using older APIs. + if (typeof args[args.length - 2] === 'function') { + // eslint-disable-next-line no-console + console.warn( + 'Callback function no longer supported as of winston@3.0.0' + ); + args.pop(); + } + + // Set the duration property of the metadata + const info = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = time - timeEnd; + info.message = info.message || id; + return this.write(info); + } + + this.profilers[id] = time; + return this; + } + + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + handleExceptions(...args) { + // eslint-disable-next-line no-console + console.warn( + 'Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()' + ); + this.exceptions.handle(...args); + } + + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + unhandleExceptions(...args) { + // eslint-disable-next-line no-console + console.warn( + 'Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()' + ); + this.exceptions.unhandle(...args); + } + + /** + * Throw a more meaningful deprecation notice + * @throws {Error} - TODO: add throws description. + */ + cli() { + throw new Error( + [ + 'Logger.cli() was removed in winston@3.0.0', + 'Use a custom winston.formats.cli() instead.', + 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md' + ].join('\n') + ); + } + + /** + * Bubbles the `event` that occured on the specified `transport` up + * from this instance. + * @param {string} event - The event that occured + * @param {Object} transport - Transport on which the event occured + * @private + */ + _onEvent(event, transport) { + function transportEvent(err) { + // https://github.com/winstonjs/winston/issues/1364 + if (event === 'error' && !this.transports.includes(transport)) { + this.add(transport); + } + this.emit(event, err, transport); + } + + if (!transport['__winston' + event]) { + transport['__winston' + event] = transportEvent.bind(this); + transport.on(event, transport['__winston' + event]); + } + } + + _addDefaultMeta(msg) { + if (this.defaultMeta) { + Object.assign(msg, this.defaultMeta); + } + } +} + +function getLevelValue(levels, level) { + const value = levels[level]; + if (!value && value !== 0) { + return null; + } + return value; +} + +/** + * Represents the current readableState pipe targets for this Logger instance. + * @type {Array|Object} + */ +Object.defineProperty(Logger.prototype, 'transports', { + configurable: false, + enumerable: true, + get() { + const { pipes } = this._readableState; + return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + } +}); + +module.exports = Logger; diff --git a/nodejs/node_modules/winston/lib/winston/profiler.js b/nodejs/node_modules/winston/lib/winston/profiler.js new file mode 100644 index 00000000..d632fcee --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/profiler.js @@ -0,0 +1,53 @@ +/** + * profiler.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; +/** + * TODO: add class description. + * @type {Profiler} + * @private + */ +class Profiler { + /** + * Constructor function for the Profiler instance used by + * `Logger.prototype.startTimer`. When done is called the timer will finish + * and log the duration. + * @param {!Logger} logger - TODO: add param description. + * @private + */ + constructor(logger) { + const Logger = require('./logger'); + if (typeof logger !== 'object' || Array.isArray(logger) || !(logger instanceof Logger)) { + throw new Error('Logger is required for profiling'); + } else { + this.logger = logger; + this.start = Date.now(); + } + } + + /** + * Ends the current timer (i.e. Profiler) instance and logs the `msg` along + * with the duration since creation. + * @returns {mixed} - TODO: add return description. + * @private + */ + done(...args) { + if (typeof args[args.length - 1] === 'function') { + // eslint-disable-next-line no-console + console.warn('Callback function no longer supported as of winston@3.0.0'); + args.pop(); + } + + const info = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = (Date.now()) - this.start; + + return this.logger.write(info); + } +}; + +module.exports = Profiler; diff --git a/nodejs/node_modules/winston/lib/winston/rejection-handler.js b/nodejs/node_modules/winston/lib/winston/rejection-handler.js new file mode 100644 index 00000000..7c3b8019 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/rejection-handler.js @@ -0,0 +1,251 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const os = require('os'); +const asyncForEach = require('async/forEach'); +const debug = require('@dabh/diagnostics')('winston:rejection'); +const once = require('one-time'); +const stackTrace = require('stack-trace'); +const RejectionStream = require('./rejection-stream'); + +/** + * Object for handling unhandledRejection events. + * @type {RejectionHandler} + */ +module.exports = class RejectionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error('Logger is required to handle rejections'); + } + + this.logger = logger; + this.handlers = new Map(); + } + + /** + * Handles `unhandledRejection` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach(arg => { + if (Array.isArray(arg)) { + return arg.forEach(handler => this._addHandler(handler)); + } + + this._addHandler(arg); + }); + + if (!this.catcher) { + this.catcher = this._unhandledRejection.bind(this); + process.on('unhandledRejection', this.catcher); + } + } + + /** + * Removes any handlers to `unhandledRejection` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener('unhandledRejection', this.catcher); + this.catcher = false; + + Array.from(this.handlers.values()).forEach(wrapper => + this.logger.unpipe(wrapper) + ); + } + } + + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let message = null; + if (err) { + message = typeof err === 'string' ? err : err.message; + } + + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: [ + `unhandledRejection: ${message || '(no error message)'}`, + err && err.stack || ' No stack trace' + ].join('\n'), + stack: err && err.stack, + rejection: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(site => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleRejections = true; + const wrapper = new RejectionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _unhandledRejection(err) { + const info = this.getAllInfo(err); + const handlers = this._getRejectionHandlers(); + // Calculate if we should exit on this error + let doExit = + typeof this.logger.exitOnError === 'function' + ? this.logger.exitOnError(err) + : this.logger.exitOnError; + let timeout; + + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no rejection handlers.'); + // eslint-disable-next-line no-console + console.warn('winston: not exiting process.'); + doExit = false; + } + + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + + if (doExit && !process._exiting) { + // Remark: Currently ignoring any rejections from transports when + // catching unhandled rejections. + if (timeout) { + clearTimeout(timeout); + } + // eslint-disable-next-line no-process-exit + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + + // Log to all transports attempting to listen for when they are completed. + asyncForEach( + handlers, + (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + + // Debug wrapping so that we can inspect what's going on under the covers. + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, + () => doExit && gracefulExit() + ); + + this.logger.log(info); + + // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getRejectionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleRejections: true` + return this.logger.transports.filter(wrap => { + const transport = wrap.transport || wrap; + return transport.handleRejections; + }); + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/rejection-stream.js b/nodejs/node_modules/winston/lib/winston/rejection-stream.js new file mode 100644 index 00000000..92e6b670 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/rejection-stream.js @@ -0,0 +1,52 @@ +/** + * rejection-stream.js: TODO: add file header handler. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { Writable } = require('readable-stream'); + +/** + * TODO: add class description. + * @type {RejectionStream} + * @extends {Writable} + */ +module.exports = class RejectionStream extends Writable { + /** + * Constructor function for the RejectionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.rejection` set to true. + * @param {!TransportStream} transport - Stream to filter to rejections + */ + constructor(transport) { + super({ objectMode: true }); + + if (!transport) { + throw new Error('RejectionStream requires a TransportStream instance.'); + } + + this.handleRejections = true; + this.transport = transport; + } + + /** + * Writes the info object to our transport instance if (and only if) the + * `rejection` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.rejection) { + return this.transport.log(info, callback); + } + + callback(); + return true; + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/tail-file.js b/nodejs/node_modules/winston/lib/winston/tail-file.js new file mode 100644 index 00000000..86ea904c --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/tail-file.js @@ -0,0 +1,124 @@ +/** + * tail-file.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const fs = require('fs'); +const { StringDecoder } = require('string_decoder'); +const { Stream } = require('readable-stream'); + +/** + * Simple no-op function. + * @returns {undefined} + */ +function noop() {} + +/** + * TODO: add function description. + * @param {Object} options - Options for tail. + * @param {function} iter - Iterator function to execute on every line. +* `tail -f` a file. Options must include file. + * @returns {mixed} - TODO: add return description. + */ +module.exports = (options, iter) => { + const buffer = Buffer.alloc(64 * 1024); + const decode = new StringDecoder('utf8'); + const stream = new Stream(); + let buff = ''; + let pos = 0; + let row = 0; + + if (options.start === -1) { + delete options.start; + } + + stream.readable = true; + stream.destroy = () => { + stream.destroyed = true; + stream.emit('end'); + stream.emit('close'); + }; + + fs.open(options.file, 'a+', '0644', (err, fd) => { + if (err) { + if (!iter) { + stream.emit('error', err); + } else { + iter(err); + } + stream.destroy(); + return; + } + + (function read() { + if (stream.destroyed) { + fs.close(fd, noop); + return; + } + + return fs.read(fd, buffer, 0, buffer.length, pos, (error, bytes) => { + if (error) { + if (!iter) { + stream.emit('error', error); + } else { + iter(error); + } + stream.destroy(); + return; + } + + if (!bytes) { + if (buff) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', buff); + } else { + iter(null, buff); + } + } + row++; + buff = ''; + } + return setTimeout(read, 1000); + } + + let data = decode.write(buffer.slice(0, bytes)); + if (!iter) { + stream.emit('data', data); + } + + data = (buff + data).split(/\n+/); + + const l = data.length - 1; + let i = 0; + + for (; i < l; i++) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', data[i]); + } else { + iter(null, data[i]); + } + } + row++; + } + + buff = data[l]; + pos += bytes; + return read(); + }); + }()); + }); + + if (!iter) { + return stream; + } + + return stream.destroy; +}; diff --git a/nodejs/node_modules/winston/lib/winston/transports/console.js b/nodejs/node_modules/winston/lib/winston/transports/console.js new file mode 100644 index 00000000..b54f3da9 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/transports/console.js @@ -0,0 +1,117 @@ +/* eslint-disable no-console */ +/* + * console.js: Transport for outputting to the console. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const os = require('os'); +const { LEVEL, MESSAGE } = require('triple-beam'); +const TransportStream = require('winston-transport'); + +/** + * Transport for outputting to the console. + * @type {Console} + * @extends {TransportStream} + */ +module.exports = class Console extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + + // Expose the name of this Transport on the prototype + this.name = options.name || 'console'; + this.stderrLevels = this._stringArrayToSet(options.stderrLevels); + this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels); + this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL; + + this.setMaxListeners(30); + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit('logged', info)); + + // Remark: what if there is no raw...? + if (this.stderrLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + // console.error adds a newline + console.error(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } else if (this.consoleWarnLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + // in Node.js console.warn is an alias for console.error + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + // console.warn adds a newline + console.warn(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + + if (console._stdout) { + // Node.js maps `process.stdout` to `console._stdout`. + console._stdout.write(`${info[MESSAGE]}${this.eol}`); + } else { + // console.log adds a newline. + console.log(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + } + + /** + * Returns a Set-like object with strArray's elements as keys (each with the + * value true). + * @param {Array} strArray - Array of Set-elements as strings. + * @param {?string} [errMsg] - Custom error message thrown on invalid input. + * @returns {Object} - TODO: add return description. + * @private + */ + _stringArrayToSet(strArray, errMsg) { + if (!strArray) + return {}; + + errMsg = errMsg || 'Cannot make set from type other than Array of string elements'; + + if (!Array.isArray(strArray)) { + throw new Error(errMsg); + } + + return strArray.reduce((set, el) => { + if (typeof el !== 'string') { + throw new Error(errMsg); + } + set[el] = true; + + return set; + }, {}); + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/transports/file.js b/nodejs/node_modules/winston/lib/winston/transports/file.js new file mode 100644 index 00000000..99682453 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/transports/file.js @@ -0,0 +1,765 @@ +/* eslint-disable complexity,max-statements */ +/** + * file.js: Transport for outputting to a local log file. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const asyncSeries = require('async/series'); +const zlib = require('zlib'); +const { MESSAGE } = require('triple-beam'); +const { Stream, PassThrough } = require('readable-stream'); +const TransportStream = require('winston-transport'); +const debug = require('@dabh/diagnostics')('winston:file'); +const os = require('os'); +const tailFile = require('../tail-file'); + +/** + * Transport for outputting to a local log file. + * @type {File} + * @extends {TransportStream} + */ +module.exports = class File extends TransportStream { + /** + * Constructor function for the File transport object responsible for + * persisting log messages and metadata to one or more files. + * @param {Object} options - Options for this instance. + */ + constructor(options = {}) { + super(options); + + // Expose the name of this Transport on the prototype. + this.name = options.name || 'file'; + + // Helper function which throws an `Error` in the event that any of the + // rest of the arguments is present in `options`. + function throwIf(target, ...args) { + args.slice(1).forEach(name => { + if (options[name]) { + throw new Error(`Cannot set ${name} and ${target} together`); + } + }); + } + + // Setup the base stream that always gets piped to to handle buffering. + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + + // Bind this context for listener methods. + this._onError = this._onError.bind(this); + + if (options.filename || options.dirname) { + throwIf('filename or dirname', 'stream'); + this._basename = this.filename = options.filename + ? path.basename(options.filename) + : 'winston.log'; + + this.dirname = options.dirname || path.dirname(options.filename); + this.options = options.options || { flags: 'a' }; + } else if (options.stream) { + // eslint-disable-next-line no-console + console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream'); + throwIf('stream', 'filename', 'maxsize'); + this._dest = this._stream.pipe(this._setupStream(options.stream)); + this.dirname = path.dirname(this._dest.path); + // We need to listen for drain events when write() returns false. This + // can make node mad at times. + } else { + throw new Error('Cannot log to file without filename or stream.'); + } + + this.maxsize = options.maxsize || null; + this.rotationFormat = options.rotationFormat || false; + this.zippedArchive = options.zippedArchive || false; + this.maxFiles = options.maxFiles || null; + this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL; + this.tailable = options.tailable || false; + this.lazy = options.lazy || false; + + // Internal state variables representing the number of files this instance + // has created and the current size (in bytes) of the current logfile. + this._size = 0; + this._pendingSize = 0; + this._created = 0; + this._drain = false; + this._opening = false; + this._ending = false; + this._fileExist = false; + + if (this.dirname) this._createLogDirIfNotExist(this.dirname); + if (!this.lazy) this.open(); + } + + finishIfEnding() { + if (this._ending) { + if (this._opening) { + this.once('open', () => { + this._stream.once('finish', () => this.emit('finish')); + setImmediate(() => this._stream.end()); + }); + } else { + this._stream.once('finish', () => this.emit('finish')); + setImmediate(() => this._stream.end()); + } + } + } + + /** + * Core logging method exposed to Winston. Metadata is optional. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback = () => { }) { + // Remark: (jcrugzz) What is necessary about this callback(null, true) now + // when thinking about 3.x? Should silent be handled in the base + // TransportStream _write method? + if (this.silent) { + callback(); + return true; + } + + + // Output stream buffer is full and has asked us to wait for the drain event + if (this._drain) { + this._stream.once('drain', () => { + this._drain = false; + this.log(info, callback); + }); + return; + } + if (this._rotate) { + this._stream.once('rotate', () => { + this._rotate = false; + this.log(info, callback); + }); + return; + } + if (this.lazy) { + if (!this._fileExist) { + if (!this._opening) { + this.open(); + } + this.once('open', () => { + this._fileExist = true; + this.log(info, callback); + return; + }); + return; + } + if (this._needsNewFile(this._pendingSize)) { + this._dest.once('close', () => { + if (!this._opening) { + this.open(); + } + this.once('open', () => { + this.log(info, callback); + return; + }); + return; + }); + return; + } + } + + // Grab the raw string and append the expected EOL. + const output = `${info[MESSAGE]}${this.eol}`; + const bytes = Buffer.byteLength(output); + + // After we have written to the PassThrough check to see if we need + // to rotate to the next file. + // + // Remark: This gets called too early and does not depict when data + // has been actually flushed to disk. + function logged() { + this._size += bytes; + this._pendingSize -= bytes; + + debug('logged %s %s', this._size, output); + this.emit('logged', info); + + // Do not attempt to rotate files while rotating + if (this._rotate) { + return; + } + + // Do not attempt to rotate files while opening + if (this._opening) { + return; + } + + // Check to see if we need to end the stream and create a new one. + if (!this._needsNewFile()) { + return; + } + if (this.lazy) { + this._endStream(() => {this.emit('fileclosed');}); + return; + } + + // End the current stream, ensure it flushes and create a new one. + // This could potentially be optimized to not run a stat call but its + // the safest way since we are supporting `maxFiles`. + this._rotate = true; + this._endStream(() => this._rotateFile()); + } + + // Keep track of the pending bytes being written while files are opening + // in order to properly rotate the PassThrough this._stream when the file + // eventually does open. + this._pendingSize += bytes; + if (this._opening + && !this.rotatedWhileOpening + && this._needsNewFile(this._size + this._pendingSize)) { + this.rotatedWhileOpening = true; + } + + const written = this._stream.write(output, logged.bind(this)); + if (!written) { + this._drain = true; + this._stream.once('drain', () => { + this._drain = false; + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + + debug('written', written, this._drain); + + this.finishIfEnding(); + + return written; + } + + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * TODO: Refactor me. + */ + query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = normalizeQuery(options); + const file = path.join(this.dirname, this.filename); + let buff = ''; + let results = []; + let row = 0; + + const stream = fs.createReadStream(file, { + encoding: 'utf8' + }); + + stream.on('error', err => { + if (stream.readable) { + stream.destroy(); + } + if (!callback) { + return; + } + + return err.code !== 'ENOENT' ? callback(err) : callback(null, results); + }); + + stream.on('data', data => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; + } + + buff = data[l]; + }); + + stream.on('close', () => { + if (buff) { + add(buff, true); + } + if (options.order === 'desc') { + results = results.reverse(); + } + + // eslint-disable-next-line callback-return + if (callback) callback(null, results); + }); + + function add(buff, attempt) { + try { + const log = JSON.parse(buff); + if (check(log)) { + push(log); + } + } catch (e) { + if (!attempt) { + stream.emit('error', e); + } + } + } + + function push(log) { + if ( + options.rows && + results.length >= options.rows && + options.order !== 'desc' + ) { + if (stream.readable) { + stream.destroy(); + } + return; + } + + if (options.fields) { + log = options.fields.reduce((obj, key) => { + obj[key] = log[key]; + return obj; + }, {}); + } + + if (options.order === 'desc') { + if (results.length >= options.rows) { + results.shift(); + } + } + results.push(log); + } + + function check(log) { + if (!log) { + return; + } + + if (typeof log !== 'object') { + return; + } + + const time = new Date(log.timestamp); + if ( + (options.from && time < options.from) || + (options.until && time > options.until) || + (options.level && options.level !== log.level) + ) { + return; + } + + return true; + } + + function normalizeQuery(options) { + options = options || {}; + + // limit + options.rows = options.rows || options.limit || 10; + + // starting row offset + options.start = options.start || 0; + + // now + options.until = options.until || new Date(); + if (typeof options.until !== 'object') { + options.until = new Date(options.until); + } + + // now - 24 + options.from = options.from || (options.until - (24 * 60 * 60 * 1000)); + if (typeof options.from !== 'object') { + options.from = new Date(options.from); + } + + // 'asc' or 'desc' + options.order = options.order || 'desc'; + + return options; + } + } + + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + * TODO: Refactor me. + */ + stream(options = {}) { + const file = path.join(this.dirname, this.filename); + const stream = new Stream(); + const tail = { + file, + start: options.start + }; + + stream.destroy = tailFile(tail, (err, line) => { + if (err) { + return stream.emit('error', err); + } + + try { + stream.emit('data', line); + line = JSON.parse(line); + stream.emit('log', line); + } catch (e) { + stream.emit('error', e); + } + }); + + return stream; + } + + /** + * Checks to see the filesize of. + * @returns {undefined} + */ + open() { + // If we do not have a filename then we were passed a stream and + // don't need to keep track of size. + if (!this.filename) return; + if (this._opening) return; + + this._opening = true; + + // Stat the target file to get the size and create the stream. + this.stat((err, size) => { + if (err) { + return this.emit('error', err); + } + debug('stat done: %s { size: %s }', this.filename, size); + this._size = size; + this._dest = this._createStream(this._stream); + this._opening = false; + this.once('open', () => { + if (this._stream.eventNames().includes('rotate')) { + this._stream.emit('rotate'); + } else { + this._rotate = false; + } + }); + }); + } + + /** + * Stat the file and assess information in order to create the proper stream. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + stat(callback) { + const target = this._getFile(); + const fullpath = path.join(this.dirname, target); + + fs.stat(fullpath, (err, stat) => { + if (err && err.code === 'ENOENT') { + debug('ENOENT ok', fullpath); + // Update internally tracked filename with the new target name. + this.filename = target; + return callback(null, 0); + } + + if (err) { + debug(`err ${err.code} ${fullpath}`); + return callback(err); + } + + if (!stat || this._needsNewFile(stat.size)) { + // If `stats.size` is greater than the `maxsize` for this + // instance then try again. + return this._incFile(() => this.stat(callback)); + } + + // Once we have figured out what the filename is, set it + // and return the size. + this.filename = target; + callback(null, stat.size); + }); + } + + /** + * Closes the stream associated with this instance. + * @param {function} cb - TODO: add param description. + * @returns {undefined} + */ + close(cb) { + if (!this._stream) { + return; + } + + this._stream.end(() => { + if (cb) { + cb(); // eslint-disable-line callback-return + } + this.emit('flush'); + this.emit('closed'); + }); + } + + /** + * TODO: add method description. + * @param {number} size - TODO: add param description. + * @returns {undefined} + */ + _needsNewFile(size) { + size = size || this._size; + return this.maxsize && size >= this.maxsize; + } + + /** + * TODO: add method description. + * @param {Error} err - TODO: add param description. + * @returns {undefined} + */ + _onError(err) { + this.emit('error', err); + } + + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _setupStream(stream) { + stream.on('error', this._onError); + + return stream; + } + + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _cleanupStream(stream) { + stream.removeListener('error', this._onError); + stream.destroy(); + return stream; + } + + /** + * TODO: add method description. + */ + _rotateFile() { + this._incFile(() => this.open()); + } + + /** + * Unpipe from the stream that has been marked as full and end it so it + * flushes to disk. + * + * @param {function} callback - Callback for when the current file has closed. + * @private + */ + _endStream(callback = () => { }) { + if (this._dest) { + this._stream.unpipe(this._dest); + this._dest.end(() => { + this._cleanupStream(this._dest); + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + } + + /** + * Returns the WritableStream for the active file on this instance. If we + * should gzip the file then a zlib stream is returned. + * + * @param {ReadableStream} source –PassThrough to pipe to the file when open. + * @returns {WritableStream} Stream that writes to disk for the active file. + */ + _createStream(source) { + const fullpath = path.join(this.dirname, this.filename); + + debug('create stream start', fullpath, this.options); + const dest = fs.createWriteStream(fullpath, this.options) + // TODO: What should we do with errors here? + .on('error', err => debug(err)) + .on('close', () => debug('close', dest.path, dest.bytesWritten)) + .on('open', () => { + debug('file open ok', fullpath); + this.emit('open', fullpath); + source.pipe(dest); + + // If rotation occured during the open operation then we immediately + // start writing to a new PassThrough, begin opening the next file + // and cleanup the previous source and dest once the source has drained. + if (this.rotatedWhileOpening) { + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + this._rotateFile(); + this.rotatedWhileOpening = false; + this._cleanupStream(dest); + source.end(); + } + }); + + debug('create stream ok', fullpath); + return dest; + } + + /** + * TODO: add method description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + _incFile(callback) { + debug('_incFile', this.filename); + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const tasks = []; + + if (this.zippedArchive) { + tasks.push( + function (cb) { + const num = this._created > 0 && !this.tailable ? this._created : ''; + this._compressFile( + path.join(this.dirname, `${basename}${num}${ext}`), + path.join(this.dirname, `${basename}${num}${ext}.gz`), + cb + ); + }.bind(this) + ); + } + + tasks.push( + function (cb) { + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, cb); + } else { + this._checkMaxFilesTailable(ext, basename, cb); + } + }.bind(this) + ); + + asyncSeries(tasks, callback); + } + + /** + * Gets the next filename to use for this instance in the case that log + * filesizes are being capped. + * @returns {string} - TODO: add return description. + * @private + */ + _getFile() { + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const isRotation = this.rotationFormat + ? this.rotationFormat() + : this._created; + + // Caveat emptor (indexzero): rotationFormat() was broken by design When + // combined with max files because the set of files to unlink is never + // stored. + return !this.tailable && this._created + ? `${basename}${isRotation}${ext}` + : `${basename}${ext}`; + } + + /** + * Increment the number of files created or checked by this instance. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesIncrementing(ext, basename, callback) { + // Check for maxFiles option and delete file. + if (!this.maxFiles || this._created < this.maxFiles) { + return setImmediate(callback); + } + + const oldest = this._created - this.maxFiles; + const isOldest = oldest !== 0 ? oldest : ''; + const isZipped = this.zippedArchive ? '.gz' : ''; + const filePath = `${basename}${isOldest}${ext}${isZipped}`; + const target = path.join(this.dirname, filePath); + + fs.unlink(target, callback); + } + + /** + * Roll files forward based on integer, up to maxFiles. e.g. if base if + * file.log and it becomes oversized, roll to file1.log, and allow file.log + * to be re-used. If file is oversized again, roll file1.log to file2.log, + * roll file.log to file1.log, and so on. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesTailable(ext, basename, callback) { + const tasks = []; + if (!this.maxFiles) { + return; + } + + // const isZipped = this.zippedArchive ? '.gz' : ''; + const isZipped = this.zippedArchive ? '.gz' : ''; + for (let x = this.maxFiles - 1; x > 1; x--) { + tasks.push(function (i, cb) { + let fileName = `${basename}${(i - 1)}${ext}${isZipped}`; + const tmppath = path.join(this.dirname, fileName); + + fs.exists(tmppath, exists => { + if (!exists) { + return cb(null); + } + + fileName = `${basename}${i}${ext}${isZipped}`; + fs.rename(tmppath, path.join(this.dirname, fileName), cb); + }); + }.bind(this, x)); + } + + asyncSeries(tasks, () => { + fs.rename( + path.join(this.dirname, `${basename}${ext}${isZipped}`), + path.join(this.dirname, `${basename}1${ext}${isZipped}`), + callback + ); + }); + } + + /** + * Compresses src to dest with gzip and unlinks src + * @param {string} src - path to source file. + * @param {string} dest - path to zipped destination file. + * @param {Function} callback - callback called after file has been compressed. + * @returns {undefined} + * @private + */ + _compressFile(src, dest, callback) { + fs.access(src, fs.F_OK, (err) => { + if (err) { + return callback(); + } + var gzip = zlib.createGzip(); + var inp = fs.createReadStream(src); + var out = fs.createWriteStream(dest); + out.on('finish', () => { + fs.unlink(src, callback); + }); + inp.pipe(gzip).pipe(out); + }); + } + + _createLogDirIfNotExist(dirPath) { + /* eslint-disable no-sync */ + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + } + /* eslint-enable no-sync */ + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/transports/http.js b/nodejs/node_modules/winston/lib/winston/transports/http.js new file mode 100644 index 00000000..0653d78b --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/transports/http.js @@ -0,0 +1,258 @@ +/** + * http.js: Transport for outputting to a json-rpcserver. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const http = require('http'); +const https = require('https'); +const { Stream } = require('readable-stream'); +const TransportStream = require('winston-transport'); +const jsonStringify = require('safe-stable-stringify'); + +/** + * Transport for outputting to a json-rpc server. + * @type {Stream} + * @extends {TransportStream} + */ +module.exports = class Http extends TransportStream { + /** + * Constructor function for the Http transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + // eslint-disable-next-line max-statements + constructor(options = {}) { + super(options); + + this.options = options; + this.name = options.name || 'http'; + this.ssl = !!options.ssl; + this.host = options.host || 'localhost'; + this.port = options.port; + this.auth = options.auth; + this.path = options.path || ''; + this.agent = options.agent; + this.headers = options.headers || {}; + this.headers['content-type'] = 'application/json'; + this.batch = options.batch || false; + this.batchInterval = options.batchInterval || 5000; + this.batchCount = options.batchCount || 10; + this.batchOptions = []; + this.batchTimeoutID = -1; + this.batchCallback = {}; + + if (!this.port) { + this.port = this.ssl ? 443 : 80; + } + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + this._request(info, null, null, (err, res) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + + if (err) { + this.emit('warn', err); + } else { + this.emit('logged', info); + } + }); + + // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering + // and block more requests from happening? + if (callback) { + setImmediate(callback); + } + } + + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * @returns {undefined} + */ + query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = { + method: 'query', + params: this.normalizeQuery(options) + }; + + const auth = options.params.auth || null; + delete options.params.auth; + + const path = options.params.path || null; + delete options.params.path; + + this._request(options, auth, path, (err, res, body) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + + if (err) { + return callback(err); + } + + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + + callback(null, body); + }); + } + + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description + */ + stream(options = {}) { + const stream = new Stream(); + options = { + method: 'stream', + params: options + }; + + const path = options.params.path || null; + delete options.params.path; + + const auth = options.params.auth || null; + delete options.params.auth; + + let buff = ''; + const req = this._request(options, auth, path); + + stream.destroy = () => req.destroy(); + req.on('data', data => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + + let i = 0; + for (; i < l; i++) { + try { + stream.emit('log', JSON.parse(data[i])); + } catch (e) { + stream.emit('error', e); + } + } + + buff = data[l]; + }); + req.on('error', err => stream.emit('error', err)); + + return stream; + } + + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {Object?} auth - authentication options + * @param {string} path - request path + * @param {function} callback - Continuation to respond to when complete. + */ + _request(options, auth, path, callback) { + options = options || {}; + + auth = auth || this.auth; + path = path || this.path || ''; + + if (this.batch) { + this._doBatch(options, callback, auth, path); + } else { + this._doRequest(options, callback, auth, path); + } + } + + /** + * Send or memorize the options according to batch configuration + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doBatch(options, callback, auth, path) { + this.batchOptions.push(options); + if (this.batchOptions.length === 1) { + // First message stored, it's time to start the timeout! + const me = this; + this.batchCallback = callback; + this.batchTimeoutID = setTimeout(function () { + // timeout is reached, send all messages to endpoint + me.batchTimeoutID = -1; + me._doBatchRequest(me.batchCallback, auth, path); + }, this.batchInterval); + } + if (this.batchOptions.length === this.batchCount) { + // max batch count is reached, send all messages to endpoint + this._doBatchRequest(this.batchCallback, auth, path); + } + } + + /** + * Initiate a request with the memorized batch options, stop the batch timeout + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doBatchRequest(callback, auth, path) { + if (this.batchTimeoutID > 0) { + clearTimeout(this.batchTimeoutID); + this.batchTimeoutID = -1; + } + const batchOptionsCopy = this.batchOptions.slice(); + this.batchOptions = []; + this._doRequest(batchOptionsCopy, callback, auth, path); + } + + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doRequest(options, callback, auth, path) { + // Prepare options for outgoing HTTP request + const headers = Object.assign({}, this.headers); + if (auth && auth.bearer) { + headers.Authorization = `Bearer ${auth.bearer}`; + } + const req = (this.ssl ? https : http).request({ + ...this.options, + method: 'POST', + host: this.host, + port: this.port, + path: `/${path.replace(/^\//, '')}`, + headers: headers, + auth: (auth && auth.username && auth.password) ? (`${auth.username}:${auth.password}`) : '', + agent: this.agent + }); + + req.on('error', callback); + req.on('response', res => ( + res.on('end', () => callback(null, res)).resume() + )); + req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8')); + } +}; diff --git a/nodejs/node_modules/winston/lib/winston/transports/index.d.ts b/nodejs/node_modules/winston/lib/winston/transports/index.d.ts new file mode 100644 index 00000000..c3eb4504 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/transports/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for winston 3.0 +// Project: https://github.com/winstonjs/winston + +/// + +import {Agent} from "http"; + +import * as Transport from 'winston-transport'; + +declare namespace winston { + interface ConsoleTransportOptions extends Transport.TransportStreamOptions { + consoleWarnLevels?: string[], + stderrLevels?: string[]; + debugStdout?: boolean; + eol?: string; + } + + interface ConsoleTransportInstance extends Transport { + name: string; + stderrLevels: string[]; + eol: string; + + new(options?: ConsoleTransportOptions): ConsoleTransportInstance; + } + + interface FileTransportOptions extends Transport.TransportStreamOptions { + filename?: string; + dirname?: string; + options?: object; + maxsize?: number; + stream?: NodeJS.WritableStream; + rotationFormat?: Function; + zippedArchive?: boolean; + maxFiles?: number; + eol?: string; + tailable?: boolean; + lazy?: boolean; + } + + interface FileTransportInstance extends Transport { + name: string; + filename: string; + dirname: string; + options: object; + maxsize: number | null; + rotationFormat: Function | boolean; + zippedArchive: boolean; + maxFiles: number | null; + eol: string; + tailable: boolean; + lazy: boolean; + + new(options?: FileTransportOptions): FileTransportInstance; + } + + interface HttpTransportOptions extends Transport.TransportStreamOptions { + ssl?: any; + host?: string; + port?: number; + auth?: { username?: string | undefined, password?: string | undefined, bearer?: string | undefined }; + path?: string; + agent?: Agent; + headers?: object; + batch?: boolean; + batchInterval?: number; + batchCount?: number; + replacer?: (key: string, value: any) => any; + } + + interface HttpTransportInstance extends Transport { + name: string; + ssl: boolean; + host: string; + port: number; + auth?: { username?: string | undefined, password?: string | undefined, bearer?: string | undefined }; + path: string; + agent?: Agent | null; + + new(options?: HttpTransportOptions): HttpTransportInstance; + } + + interface StreamTransportOptions extends Transport.TransportStreamOptions { + stream: NodeJS.WritableStream; + eol?: string; + } + + interface StreamTransportInstance extends Transport { + eol: string; + + new(options?: StreamTransportOptions): StreamTransportInstance; + } + + interface Transports { + FileTransportOptions: FileTransportOptions; + File: FileTransportInstance; + ConsoleTransportOptions: ConsoleTransportOptions; + Console: ConsoleTransportInstance; + HttpTransportOptions: HttpTransportOptions; + Http: HttpTransportInstance; + StreamTransportOptions: StreamTransportOptions; + Stream: StreamTransportInstance; + } +} + +declare const winston: winston.Transports; +export = winston; diff --git a/nodejs/node_modules/winston/lib/winston/transports/index.js b/nodejs/node_modules/winston/lib/winston/transports/index.js new file mode 100644 index 00000000..f2f7cc35 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/transports/index.js @@ -0,0 +1,56 @@ +/** + * transports.js: Set of all transports Winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * TODO: add property description. + * @type {Console} + */ +Object.defineProperty(exports, 'Console', { + configurable: true, + enumerable: true, + get() { + return require('./console'); + } +}); + +/** + * TODO: add property description. + * @type {File} + */ +Object.defineProperty(exports, 'File', { + configurable: true, + enumerable: true, + get() { + return require('./file'); + } +}); + +/** + * TODO: add property description. + * @type {Http} + */ +Object.defineProperty(exports, 'Http', { + configurable: true, + enumerable: true, + get() { + return require('./http'); + } +}); + +/** + * TODO: add property description. + * @type {Stream} + */ +Object.defineProperty(exports, 'Stream', { + configurable: true, + enumerable: true, + get() { + return require('./stream'); + } +}); diff --git a/nodejs/node_modules/winston/lib/winston/transports/stream.js b/nodejs/node_modules/winston/lib/winston/transports/stream.js new file mode 100644 index 00000000..8027f640 --- /dev/null +++ b/nodejs/node_modules/winston/lib/winston/transports/stream.js @@ -0,0 +1,63 @@ +/** + * stream.js: Transport for outputting to any arbitrary stream. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const isStream = require('is-stream'); +const { MESSAGE } = require('triple-beam'); +const os = require('os'); +const TransportStream = require('winston-transport'); + +/** + * Transport for outputting to any arbitrary stream. + * @type {Stream} + * @extends {TransportStream} + */ +module.exports = class Stream extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + + if (!options.stream || !isStream(options.stream)) { + throw new Error('options.stream is required.'); + } + + // We need to listen for drain events when write() returns false. This can + // make node mad at times. + this._stream = options.stream; + this._stream.setMaxListeners(Infinity); + this.isObjectMode = options.stream._writableState.objectMode; + this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL; + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit('logged', info)); + if (this.isObjectMode) { + this._stream.write(info); + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + + this._stream.write(`${info[MESSAGE]}${this.eol}`); + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } +}; diff --git a/nodejs/node_modules/winston/package.json b/nodejs/node_modules/winston/package.json new file mode 100644 index 00000000..bfb94b72 --- /dev/null +++ b/nodejs/node_modules/winston/package.json @@ -0,0 +1,74 @@ +{ + "name": "winston", + "description": "A logger for just about everything.", + "version": "3.12.0", + "author": "Charlie Robbins ", + "maintainers": [ + "David Hyde " + ], + "repository": { + "type": "git", + "url": "https://github.com/winstonjs/winston.git" + }, + "keywords": [ + "winston", + "logger", + "logging", + "logs", + "sysadmin", + "bunyan", + "pino", + "loglevel", + "tools", + "json", + "stream" + ], + "dependencies": { + "@dabh/diagnostics": "^2.0.2", + "@colors/colors": "^1.6.0", + "async": "^3.2.3", + "is-stream": "^2.0.0", + "logform": "^2.4.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.7.0" + }, + "devDependencies": { + "@babel/cli": "^7.23.9", + "@babel/core": "^7.24.0", + "@babel/preset-env": "^7.24.0", + "@dabh/eslint-config-populist": "^5.0.0", + "@types/node": "^20.11.24", + "abstract-winston-transport": "^0.5.1", + "assume": "^2.2.0", + "cross-spawn-async": "^2.2.5", + "eslint": "^8.57.0", + "hock": "^1.4.1", + "mocha": "^10.3.0", + "nyc": "^15.1.0", + "rimraf": "^5.0.5", + "split2": "^4.1.0", + "std-mocks": "^2.0.0", + "through2": "^4.0.2", + "winston-compat": "^0.1.5" + }, + "main": "./lib/winston.js", + "browser": "./dist/winston", + "types": "./index.d.ts", + "scripts": { + "lint": "eslint lib/*.js lib/winston/*.js lib/winston/**/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", + "test": "rimraf test/fixtures/logs/* && mocha", + "test:coverage": "nyc npm run test:unit", + "test:unit": "mocha test/unit", + "test:integration": "mocha test/integration", + "build": "rimraf dist && babel lib -d dist", + "prepublishOnly": "npm run build" + }, + "engines": { + "node": ">= 12.0.0" + }, + "license": "MIT" +} diff --git a/nodejs/node_modules/ws/LICENSE b/nodejs/node_modules/ws/LICENSE new file mode 100644 index 00000000..1da5b96a --- /dev/null +++ b/nodejs/node_modules/ws/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/nodejs/node_modules/ws/README.md b/nodejs/node_modules/ws/README.md new file mode 100644 index 00000000..80d98865 --- /dev/null +++ b/nodejs/node_modules/ws/README.md @@ -0,0 +1,549 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) + - [Legacy opt-in for performance](#legacy-opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [Round-trip time](#round-trip-time) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +[bufferutil][] is an optional module that can be installed alongside the ws +module: + +``` +npm install --save-optional bufferutil +``` + +This is a binary addon that improves the performance of certain operations such +as masking and unmasking the data payload of the WebSocket frames. Prebuilt +binaries are available for the most popular platforms, so you don't necessarily +need to have a C++ compiler installed on your machine. + +To force ws to not use bufferutil, use the +[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) environment variable. This +can be useful to enhance security in systems where a user can put a package in +the package search path of an application of another user, due to how the +Node.js resolver algorithm works. + +#### Legacy opt-in for performance + +If you are running on an old version of Node.js (prior to v18.14.0), ws also +supports the [utf-8-validate][] module: + +``` +npm install --save-optional utf-8-validate +``` + +This contains a binary polyfill for [`buffer.isUtf8()`][]. + +To force ws to not use utf-8-validate, use the +[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment variable. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function message(data) { + console.log('received: %s', data); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { parse } from 'url'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +wss2.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = parse(request.url); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +function onSocketError(err) { + console.error(err); +} + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log(`Received message ${data} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + socket.on('error', onSocketError); + + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, function next(err, client) { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + socket.removeListener('error', onSocketError); + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### Round-trip time + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +ws.on('error', console.error); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function message(data) { + console.log(`Round-trip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.on('error', console.error); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; + + ws.on('error', console.error); +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); + + ws.on('error', console.error); +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a way +that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('error', console.error); + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://websocket-echo.com/'); + +client.on('error', console.error); +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input +[bufferutil]: https://github.com/websockets/bufferutil +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[utf-8-validate]: https://github.com/websockets/utf-8-validate +[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/nodejs/node_modules/ws/browser.js b/nodejs/node_modules/ws/browser.js new file mode 100644 index 00000000..ca4f628a --- /dev/null +++ b/nodejs/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/nodejs/node_modules/ws/index.js b/nodejs/node_modules/ws/index.js new file mode 100644 index 00000000..41edb3b8 --- /dev/null +++ b/nodejs/node_modules/ws/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.createWebSocketStream = require('./lib/stream'); +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocket.Server; + +module.exports = WebSocket; diff --git a/nodejs/node_modules/ws/lib/buffer-util.js b/nodejs/node_modules/ws/lib/buffer-util.js new file mode 100644 index 00000000..f7536e28 --- /dev/null +++ b/nodejs/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/nodejs/node_modules/ws/lib/constants.js b/nodejs/node_modules/ws/lib/constants.js new file mode 100644 index 00000000..d691b30a --- /dev/null +++ b/nodejs/node_modules/ws/lib/constants.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/nodejs/node_modules/ws/lib/event-target.js b/nodejs/node_modules/ws/lib/event-target.js new file mode 100644 index 00000000..fea4cbc5 --- /dev/null +++ b/nodejs/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/nodejs/node_modules/ws/lib/extension.js b/nodejs/node_modules/ws/lib/extension.js new file mode 100644 index 00000000..3d7895c1 --- /dev/null +++ b/nodejs/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/nodejs/node_modules/ws/lib/limiter.js b/nodejs/node_modules/ws/lib/limiter.js new file mode 100644 index 00000000..3fd35784 --- /dev/null +++ b/nodejs/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/nodejs/node_modules/ws/lib/permessage-deflate.js b/nodejs/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 00000000..77d918b5 --- /dev/null +++ b/nodejs/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,514 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/nodejs/node_modules/ws/lib/receiver.js b/nodejs/node_modules/ws/lib/receiver.js new file mode 100644 index 00000000..9e87d811 --- /dev/null +++ b/nodejs/node_modules/ws/lib/receiver.js @@ -0,0 +1,742 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; +const promise = Promise.resolve(); + +// +// `queueMicrotask()` is not available in Node.js < 11. +// +const queueTask = + typeof queueMicrotask === 'function' ? queueMicrotask : queueMicrotaskShim; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const DEFER_EVENT = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._allowSynchronousEvents = !!options.allowSynchronousEvents; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + + if (!this._errored) cb(); + } + + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + const error = this.createError( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + + cb(error); + return; + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if (!this._fragmented) { + const error = this.createError( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + const error = this.createError( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + + cb(error); + return; + } + + if (compressed) { + const error = this.createError( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + + cb(error); + return; + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + const error = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + } else { + const error = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + + cb(error); + return; + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + const error = this.createError( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + + cb(error); + return; + } + } else if (this._masked) { + const error = this.createError( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + + cb(error); + return; + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + const error = this.createError( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + + cb(error); + return; + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) { + this.controlMessage(data, cb); + return; + } + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + this.dataMessage(cb); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error = this.createError( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + + cb(error); + return; + } + + this._fragments.push(buf); + } + + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + // + // If the state is `INFLATING`, it means that the frame data was + // decompressed asynchronously, so there is no need to defer the event + // as it will be emitted asynchronously anyway. + // + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit('message', data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + queueTask(() => { + this.emit('message', data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit('message', buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + queueTask(() => { + this.emit('message', buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data, cb) { + if (this._opcode === 0x08) { + if (data.length === 0) { + this._loop = false; + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + const error = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + + cb(error); + return; + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error = this.createError( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + + cb(error); + return; + } + + this._loop = false; + this.emit('conclude', code, buf); + this.end(); + } + + this._state = GET_INFO; + return; + } + + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + queueTask(() => { + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } +} + +module.exports = Receiver; + +/** + * A shim for `queueMicrotask()`. + * + * @param {Function} cb Callback + */ +function queueMicrotaskShim(cb) { + promise.then(cb).catch(throwErrorNextTick); +} + +/** + * Throws an error. + * + * @param {Error} err The error to throw + * @private + */ +function throwError(err) { + throw err; +} + +/** + * Throws an error in the next tick. + * + * @param {Error} err The error to throw + * @private + */ +function throwErrorNextTick(err) { + process.nextTick(throwError, err); +} diff --git a/nodejs/node_modules/ws/lib/sender.js b/nodejs/node_modules/ws/lib/sender.js new file mode 100644 index 00000000..1ed04b02 --- /dev/null +++ b/nodejs/node_modules/ws/lib/sender.js @@ -0,0 +1,477 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + +'use strict'; + +const { Duplex } = require('stream'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER } = require('./constants'); +const { isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; diff --git a/nodejs/node_modules/ws/lib/stream.js b/nodejs/node_modules/ws/lib/stream.js new file mode 100644 index 00000000..230734b7 --- /dev/null +++ b/nodejs/node_modules/ws/lib/stream.js @@ -0,0 +1,159 @@ +'use strict'; + +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/nodejs/node_modules/ws/lib/subprotocol.js b/nodejs/node_modules/ws/lib/subprotocol.js new file mode 100644 index 00000000..d4381e88 --- /dev/null +++ b/nodejs/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/nodejs/node_modules/ws/lib/validation.js b/nodejs/node_modules/ws/lib/validation.js new file mode 100644 index 00000000..c352e6ea --- /dev/null +++ b/nodejs/node_modules/ws/lib/validation.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +module.exports = { + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/nodejs/node_modules/ws/lib/websocket-server.js b/nodejs/node_modules/ws/lib/websocket-server.js new file mode 100644 index 00000000..377c45a8 --- /dev/null +++ b/nodejs/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,539 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const { Duplex } = require('stream'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + allowSynchronousEvents: false, + autoPong: true, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!key || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 8 && version !== 13) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null, undefined, this.options); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @private + */ +function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message); + } +} diff --git a/nodejs/node_modules/ws/lib/websocket.js b/nodejs/node_modules/ws/lib/websocket.js new file mode 100644 index 00000000..df5034cc --- /dev/null +++ b/nodejs/node_modules/ws/lib/websocket.js @@ -0,0 +1,1336 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Duplex, Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether any + * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple + * times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: false, + autoPong: true, + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + websocket._autoPong = opts.autoPong; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/nodejs/node_modules/ws/package.json b/nodejs/node_modules/ws/package.json new file mode 100644 index 00000000..a2443200 --- /dev/null +++ b/nodejs/node_modules/ws/package.json @@ -0,0 +1,68 @@ +{ + "name": "ws", + "version": "8.16.0", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + ".": { + "browser": "./browser.js", + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^8.0.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-prettier": "^5.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^3.0.0", + "utf-8-validate": "^6.0.0" + } +} diff --git a/nodejs/node_modules/ws/wrapper.mjs b/nodejs/node_modules/ws/wrapper.mjs new file mode 100644 index 00000000..7245ad15 --- /dev/null +++ b/nodejs/node_modules/ws/wrapper.mjs @@ -0,0 +1,8 @@ +import createWebSocketStream from './lib/stream.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; +export default WebSocket; diff --git a/nodejs/node_modules/xtend/.jshintrc b/nodejs/node_modules/xtend/.jshintrc new file mode 100644 index 00000000..77887b5f --- /dev/null +++ b/nodejs/node_modules/xtend/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/nodejs/node_modules/xtend/LICENSE b/nodejs/node_modules/xtend/LICENSE new file mode 100644 index 00000000..0099f4f6 --- /dev/null +++ b/nodejs/node_modules/xtend/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2012-2014 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/nodejs/node_modules/xtend/README.md b/nodejs/node_modules/xtend/README.md new file mode 100644 index 00000000..4a2703cf --- /dev/null +++ b/nodejs/node_modules/xtend/README.md @@ -0,0 +1,32 @@ +# xtend + +[![browser support][3]][4] + +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) + +Extend like a boss + +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. + +## Examples + +```js +var extend = require("xtend") + +// extend returns a new object. Does not mutate arguments +var combination = extend({ + a: "a", + b: "c" +}, { + b: "b" +}) +// { a: "a", b: "b" } +``` + +## Stability status: Locked + +## MIT Licensed + + + [3]: http://ci.testling.com/Raynos/xtend.png + [4]: http://ci.testling.com/Raynos/xtend diff --git a/nodejs/node_modules/xtend/immutable.js b/nodejs/node_modules/xtend/immutable.js new file mode 100644 index 00000000..94889c9d --- /dev/null +++ b/nodejs/node_modules/xtend/immutable.js @@ -0,0 +1,19 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/nodejs/node_modules/xtend/mutable.js b/nodejs/node_modules/xtend/mutable.js new file mode 100644 index 00000000..72debede --- /dev/null +++ b/nodejs/node_modules/xtend/mutable.js @@ -0,0 +1,17 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/nodejs/node_modules/xtend/package.json b/nodejs/node_modules/xtend/package.json new file mode 100644 index 00000000..f7a39d10 --- /dev/null +++ b/nodejs/node_modules/xtend/package.json @@ -0,0 +1,55 @@ +{ + "name": "xtend", + "version": "4.0.2", + "description": "extend like a boss", + "keywords": [ + "extend", + "merge", + "options", + "opts", + "object", + "array" + ], + "author": "Raynos ", + "repository": "git://github.com/Raynos/xtend.git", + "main": "immutable", + "scripts": { + "test": "node test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.0" + }, + "homepage": "https://github.com/Raynos/xtend", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Matt Esch" + } + ], + "bugs": { + "url": "https://github.com/Raynos/xtend/issues", + "email": "raynos2@gmail.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/7..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "engines": { + "node": ">=0.4" + } +} diff --git a/nodejs/node_modules/xtend/test.js b/nodejs/node_modules/xtend/test.js new file mode 100644 index 00000000..b895b42b --- /dev/null +++ b/nodejs/node_modules/xtend/test.js @@ -0,0 +1,103 @@ +var test = require("tape") +var extend = require("./") +var mutableExtend = require("./mutable") + +test("merge", function(assert) { + var a = { a: "foo" } + var b = { b: "bar" } + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("replace", function(assert) { + var a = { a: "foo" } + var b = { a: "bar" } + + assert.deepEqual(extend(a, b), { a: "bar" }) + assert.end() +}) + +test("undefined", function(assert) { + var a = { a: undefined } + var b = { b: "foo" } + + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) + assert.end() +}) + +test("handle 0", function(assert) { + var a = { a: "default" } + var b = { a: 0 } + + assert.deepEqual(extend(a, b), { a: 0 }) + assert.deepEqual(extend(b, a), { a: "default" }) + assert.end() +}) + +test("is immutable", function (assert) { + var record = {} + + extend(record, { foo: "bar" }) + assert.equal(record.foo, undefined) + assert.end() +}) + +test("null as argument", function (assert) { + var a = { foo: "bar" } + var b = null + var c = void 0 + + assert.deepEqual(extend(b, a, c), { foo: "bar" }) + assert.end() +}) + +test("mutable", function (assert) { + var a = { foo: "bar" } + + mutableExtend(a, { bar: "baz" }) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("null prototype", function(assert) { + var a = { a: "foo" } + var b = Object.create(null) + b.b = "bar"; + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("null prototype mutable", function (assert) { + var a = { foo: "bar" } + var b = Object.create(null) + b.bar = "baz"; + + mutableExtend(a, b) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("prototype pollution", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + extend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) + +test("prototype pollution mutable", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + mutableExtend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) diff --git a/nodejs/node_modules/y-leveldb/LICENSE b/nodejs/node_modules/y-leveldb/LICENSE new file mode 100644 index 00000000..7ea771ed --- /dev/null +++ b/nodejs/node_modules/y-leveldb/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2020 + - Kevin Jahns . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nodejs/node_modules/y-leveldb/README.md b/nodejs/node_modules/y-leveldb/README.md new file mode 100644 index 00000000..947b31c9 --- /dev/null +++ b/nodejs/node_modules/y-leveldb/README.md @@ -0,0 +1,114 @@ +# LevelDB database adapter for [Yjs](https://github.com/yjs/yjs) + +LevelDB is a fast embedded database. It is the underlying technology of IndexedDB. + +Internally, y-leveldb uses [`level`](https://github.com/Level/level) which +allows to exchange the storage medium for a different supported database. +Hence this adapter also supports rocksdb, lmdb, and many more.. + +* Persistent storage for the server +* Exchangeable storage medium +* Can be used in [y-websocket](https://github.com/yjs/y-websocket) +* A single y-leveldb instance can handle many documents. + +## Use it + +```sh +npm install y-leveldb --save +``` + +```js +import { LeveldbPersistence } from 'y-leveldb' + +const persistence = new LeveldbPersistence('./storage-location') + +const ydoc = new Y.Doc() +ydoc.getArray('arr').insert(0, [1, 2, 3]) +ydoc.getArray('arr').toArray() // => [1, 2, 3] + +// store document updates retrieved from other clients +persistence.storeUpdate('my-doc', Y.encodeStateAsUpdate(ydoc)) + +// when you want to sync, or store data to a database, +// retrieve the temporary Y.Doc to consume data +persistence.getYDoc('my-doc').getArray('arr') // [1, 2, 3] +``` + +## API + +### `persistence = LeveldbPersistence(storageLocation, [{ [level] }])` + +Create a y-leveldb persistence instance. + +You can use any levelup-compatible adapter. + +```js +import { LeveldbPersistence } from 'y-leveldb' +import level from 'level-mem' + +const persistence = new LeveldbPersistence('./storage-location', { level }) +``` + +#### `persistence.getYDoc(docName: string): Promise` + +Create a Y.Doc instance with the data persistet in leveldb. Use this to +temporarily create a Yjs document to sync changes or extract data. + +#### `persistence.storeUpdate(docName: string, update: Uint8Array): Promise` + +Store a single document update to the database. + +#### `persistence.getStateVector(docName: string): Promise` + +The state vector (describing the state of the persisted document - see +[Yjs docs](https://github.com/yjs/yjs#Document-Updates)) is maintained in a separate +field and constantly updated. + +This allows you to sync changes without actually creating a Yjs document. + +#### `persistence.getDiff(docName: string, stateVector: Uint8Array): Promise` + +Get the differences directly from the database. The same as +`Y.encodeStateAsUpdate(ydoc, stateVector)`. + +#### `persistence.clearDocument(docName: string): Promise` + +Delete a document, and all associated data from the database. + +#### `persistence.setMeta(docName: string, metaKey: string, value: any): Promise` + +Persist some meta information in the database and associate it with a document. +It is up to you what you store here. You could, for example, store credentials +here. + +#### `persistence.getMeta(docName: string, metaKey: string): Promise` + +Retrieve a store meta value from the database. Returns undefined if the +`metaKey` doesn't exist. + +#### `persistence.delMeta(docName: string, metaKey: string): Promise` + +Delete a store meta value. + +#### `persistence.getAllDocNames(docName: string): Promise>` + +Retrieve the names of all stored documents. + +#### `persistence.getAllDocStateVectors(docName: string): Promise diff --git a/nodejs/node_modules/y-leveldb/dist/src/y-leveldb.d.ts b/nodejs/node_modules/y-leveldb/dist/src/y-leveldb.d.ts new file mode 100644 index 00000000..e05ac95e --- /dev/null +++ b/nodejs/node_modules/y-leveldb/dist/src/y-leveldb.d.ts @@ -0,0 +1,121 @@ +/// +export const PREFERRED_TRIM_SIZE: 500; +export function writeUint32BigEndian(encoder: encoding.Encoder, num: number): void; +export function readUint32BigEndian(decoder: decoding.Decoder): number; +export const keyEncoding: { + buffer: boolean; + type: string; + encode: (arr: Array) => Buffer; + decode: (buf: Uint8Array) => (string | number)[]; +}; +export function getLevelBulkData(db: any, opts: object): Promise>; +export function getLevelUpdates(db: any, docName: string, opts?: any): Promise>; +export function getAllDocs(db: any, values: boolean, keys: boolean): Promise>; +export function getCurrentUpdateClock(db: any, docName: string): Promise; +export class LeveldbPersistence { + /** + * @param {string} location + * @param {object} [opts] + * @param {any} [opts.level] Level-compatible adapter. E.g. leveldown, level-rem, level-indexeddb. Defaults to `level` + * @param {object} [opts.levelOptions] Options that are passed down to the level instance + */ + constructor(location: string, { level, levelOptions }?: { + level?: any; + levelOptions?: object; + } | undefined); + tr: Promise; + /** + * Execute an transaction on a database. This will ensure that other processes are currently not writing. + * + * This is a private method and might change in the future. + * + * @todo only transact on the same room-name. Allow for concurrency of different rooms. + * + * @template T + * + * @param {function(any):Promise} f A transaction that receives the db object + * @return {Promise} + */ + _transact: (f: (arg0: any) => Promise) => Promise; + /** + * @param {string} docName + */ + flushDocument(docName: string): Promise; + /** + * @param {string} docName + * @return {Promise} + */ + getYDoc(docName: string): Promise; + /** + * @param {string} docName + * @return {Promise} + */ + getStateVector(docName: string): Promise; + /** + * @param {string} docName + * @param {Uint8Array} update + * @return {Promise} Returns the clock of the stored update + */ + storeUpdate(docName: string, update: Uint8Array): Promise; + /** + * @param {string} docName + * @param {Uint8Array} stateVector + */ + getDiff(docName: string, stateVector: Uint8Array): Promise; + /** + * @param {string} docName + * @return {Promise} + */ + clearDocument(docName: string): Promise; + /** + * @param {string} docName + * @param {string} metaKey + * @param {any} value + * @return {Promise} + */ + setMeta(docName: string, metaKey: string, value: any): Promise; + /** + * @param {string} docName + * @param {string} metaKey + * @return {Promise} + */ + delMeta(docName: string, metaKey: string): Promise; + /** + * @param {string} docName + * @param {string} metaKey + * @return {Promise} + */ + getMeta(docName: string, metaKey: string): Promise; + /** + * @return {Promise>} + */ + getAllDocNames(): Promise>; + /** + * @return {Promise>} + */ + getAllDocStateVectors(): Promise>; + /** + * @param {string} docName + * @return {Promise>} + */ + getMetas(docName: string): Promise>; + /** + * Close connection to a leveldb database and discard all state and bindings + * + * @return {Promise} + */ + destroy(): Promise; + /** + * Delete all data in database. + */ + clearAll(): Promise; +} +import * as encoding from "lib0/encoding"; +import * as decoding from "lib0/decoding"; +import { Buffer } from "buffer"; +import * as Y from "yjs"; +//# sourceMappingURL=y-leveldb.d.ts.map \ No newline at end of file diff --git a/nodejs/node_modules/y-leveldb/dist/src/y-leveldb.d.ts.map b/nodejs/node_modules/y-leveldb/dist/src/y-leveldb.d.ts.map new file mode 100644 index 00000000..85321663 --- /dev/null +++ b/nodejs/node_modules/y-leveldb/dist/src/y-leveldb.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"y-leveldb.d.ts","sourceRoot":"","sources":["../../src/y-leveldb.js"],"names":[],"mappings":";AAUA,sCAAsC;AAoB/B,8CAHI,QAAQ,CAAC,OAAO,OAChB,MAAM,QAMhB;AAYM,6CAHI,QAAQ,CAAC,OAAO,GACf,MAAM,CAUjB;AAED;;;kBAIsB,KAAK,CAAC,MAAM,GAAC,MAAM,CAAC;kBAgBpB,UAAU;EAe/B;AA4CM,qCAJI,GAAG,QACH,MAAM,GACL,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAc7B;AAUK,oCALI,GAAG,WACH,MAAM,SACN,GAAG,GACF,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAMhC;AAUK,+BALI,GAAG,UACH,OAAO,QAC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C,CAcpC;IAED;;;;OAIG;IACH,WAFY,OAAO,CAAC,IAAI,CAAC,CAIxB;IAED;;OAEG;IACH,yBAEC;CACF"} \ No newline at end of file diff --git a/nodejs/node_modules/y-leveldb/dist/test.cjs b/nodejs/node_modules/y-leveldb/dist/test.cjs new file mode 100644 index 00000000..c97de745 --- /dev/null +++ b/nodejs/node_modules/y-leveldb/dist/test.cjs @@ -0,0 +1,861 @@ +'use strict'; + +var Y = require('yjs'); +var encoding = require('lib0/dist/encoding.cjs'); +var decoding = require('lib0/dist/decoding.cjs'); +var binary = require('lib0/dist/binary.cjs'); +var promise = require('lib0/dist/promise.cjs'); +var buffer = require('lib0/dist/buffer.cjs'); +var defaultLevel = require('level'); +var buffer$1 = require('buffer'); +var t = require('lib0/dist/testing.cjs'); +var environment_js = require('lib0/dist/environment.cjs'); +var log = require('lib0/dist/logging.cjs'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var Y__namespace = /*#__PURE__*/_interopNamespace(Y); +var encoding__namespace = /*#__PURE__*/_interopNamespace(encoding); +var decoding__namespace = /*#__PURE__*/_interopNamespace(decoding); +var binary__namespace = /*#__PURE__*/_interopNamespace(binary); +var promise__namespace = /*#__PURE__*/_interopNamespace(promise); +var buffer__namespace = /*#__PURE__*/_interopNamespace(buffer); +var defaultLevel__default = /*#__PURE__*/_interopDefaultLegacy(defaultLevel); +var t__namespace = /*#__PURE__*/_interopNamespace(t); +var log__namespace = /*#__PURE__*/_interopNamespace(log); + +const PREFERRED_TRIM_SIZE = 500; + +const YEncodingString = 0; +const YEncodingUint32 = 1; + +const valueEncoding = { + buffer: true, + type: 'y-value', + encode: /** @param {any} data */ data => data, + decode: /** @param {any} data */ data => data +}; + +/** + * Write two bytes as an unsigned integer in big endian order. + * (most significant byte first) + * + * @function + * @param {encoding.Encoder} encoder + * @param {number} num The number that is to be encoded. + */ +const writeUint32BigEndian = (encoder, num) => { + for (let i = 3; i >= 0; i--) { + encoding__namespace.write(encoder, (num >>> (8 * i)) & binary__namespace.BITS8); + } +}; + +/** + * Read 4 bytes as unsigned integer in big endian order. + * (most significant byte first) + * + * @todo use lib0/decoding instead + * + * @function + * @param {decoding.Decoder} decoder + * @return {number} An unsigned integer. + */ +const readUint32BigEndian = decoder => { + const uint = + (decoder.arr[decoder.pos + 3] + + (decoder.arr[decoder.pos + 2] << 8) + + (decoder.arr[decoder.pos + 1] << 16) + + (decoder.arr[decoder.pos] << 24)) >>> 0; + decoder.pos += 4; + return uint +}; + +const keyEncoding = { + buffer: true, + type: 'y-keys', + /* istanbul ignore next */ + encode: /** @param {Array} arr */ arr => { + const encoder = encoding__namespace.createEncoder(); + for (let i = 0; i < arr.length; i++) { + const v = arr[i]; + if (typeof v === 'string') { + encoding__namespace.writeUint8(encoder, YEncodingString); + encoding__namespace.writeVarString(encoder, v); + } else /* istanbul ignore else */ if (typeof v === 'number') { + encoding__namespace.writeUint8(encoder, YEncodingUint32); + writeUint32BigEndian(encoder, v); + } else { + throw new Error('Unexpected key value') + } + } + return buffer$1.Buffer.from(encoding__namespace.toUint8Array(encoder)) + }, + decode: /** @param {Uint8Array} buf */ buf => { + const decoder = decoding__namespace.createDecoder(buf); + const key = []; + while (decoding__namespace.hasContent(decoder)) { + switch (decoding__namespace.readUint8(decoder)) { + case YEncodingString: + key.push(decoding__namespace.readVarString(decoder)); + break + case YEncodingUint32: + key.push(readUint32BigEndian(decoder)); + break + } + } + return key + } +}; + +/** + * level returns an error if a value is not found. + * + * This helper method for level returns `null` instead if the key is not found. + * + * @param {any} db + * @param {any} key + */ +const levelGet = async (db, key) => { + let res; + try { + res = await db.get(key); + } catch (err) { + /* istanbul ignore else */ + if (err.notFound) { + return null + } else { + throw err + } + } + return res +}; + +/** + * Level expects a Buffer, but in Yjs we typically work with Uint8Arrays. + * + * Since Level thinks that these are two entirely different things, + * we transform the Uint8array to a Buffer before storing it. + * + * @param {any} db + * @param {any} key + * @param {Uint8Array} val + */ +const levelPut = async (db, key, val) => db.put(key, buffer$1.Buffer.from(val)); + +/** + * A "bulkier" implementation of level streams. Returns the result in one flush. + * + * @param {any} db + * @param {object} opts + * @return {Promise>} + */ +const getLevelBulkData = (db, opts) => promise__namespace.create((resolve, reject) => { + /** + * @type {Array} result + */ + const result = []; + db.createReadStream( + opts + ).on('data', /** @param {any} data */ data => + result.push(data) + ).on('end', () => + resolve(result) + ).on('error', reject); +}); + +/** + * Get all document updates for a specific document. + * + * @param {any} db + * @param {string} docName + * @param {any} [opts] + * @return {Promise>} + */ +const getLevelUpdates = (db, docName, opts = { values: true, keys: false }) => getLevelBulkData(db, { + gte: createDocumentUpdateKey(docName, 0), + lt: createDocumentUpdateKey(docName, binary__namespace.BITS32), + ...opts +}); + +/** + * Get all document updates for a specific document. + * + * @param {any} db + * @param {boolean} values + * @param {boolean} keys + * @return {Promise>} + */ +const getAllDocs = (db, values, keys) => getLevelBulkData(db, { + gte: ['v1_sv'], + lt: ['v1_sw'], + keys, + values +}); + +/** + * @param {any} db + * @param {string} docName + * @return {Promise} Returns -1 if this document doesn't exist yet + */ +const getCurrentUpdateClock = (db, docName) => getLevelUpdates(db, docName, { keys: true, values: false, reverse: true, limit: 1 }).then(keys => { + if (keys.length === 0) { + return -1 + } else { + return keys[0][3] + } +}); + +/** + * @param {any} db + * @param {Array} gte Greater than or equal + * @param {Array} lt lower than (not equal) + * @return {Promise} + */ +const clearRange = async (db, gte, lt) => { + /* istanbul ignore else */ + if (db.supports.clear) { + await db.clear({ gte, lt }); + } else { + const keys = await getLevelBulkData(db, { values: false, keys: true, gte, lt }); + const ops = keys.map(key => ({ type: 'del', key })); + await db.batch(ops); + } +}; + +/** + * @param {any} db + * @param {string} docName + * @param {number} from Greater than or equal + * @param {number} to lower than (not equal) + * @return {Promise} + */ +const clearUpdatesRange = async (db, docName, from, to) => clearRange(db, createDocumentUpdateKey(docName, from), createDocumentUpdateKey(docName, to)); + +/** + * Create a unique key for a update message. + * We encode the result using `keyEncoding` which expects an array. + * + * @param {string} docName + * @param {number} clock must be unique + * @return {Array} + */ +const createDocumentUpdateKey = (docName, clock) => ['v1', docName, 'update', clock]; + +/** + * @param {string} docName + * @param {string} metaKey + */ +const createDocumentMetaKey = (docName, metaKey) => ['v1', docName, 'meta', metaKey]; + +/** + * @param {string} docName + */ +const createDocumentMetaEndKey = (docName) => ['v1', docName, 'metb']; // simple trick + +/** + * We have a separate state vector key so we can iterate efficiently over all documents + * @param {string} docName + */ +const createDocumentStateVectorKey = (docName) => ['v1_sv', docName]; + +/** + * @param {string} docName + */ +const createDocumentFirstKey = (docName) => ['v1', docName]; + +/** + * We use this key as the upper limit of all keys that can be written. + * Make sure that all document keys are smaller! Strings are encoded using varLength string encoding, + * so we need to make sure that this key has the biggest size! + * + * @param {string} docName + */ +const createDocumentLastKey = (docName) => ['v1', docName, 'zzzzzzz']; + +// const emptyStateVector = (() => Y.encodeStateVector(new Y.Doc()))() + +/** + * For now this is a helper method that creates a Y.Doc and then re-encodes a document update. + * In the future this will be handled by Yjs without creating a Y.Doc (constant memory consumption). + * + * @param {Array} updates + * @return {{update:Uint8Array, sv: Uint8Array}} + */ +const mergeUpdates = (updates) => { + const ydoc = new Y__namespace.Doc(); + ydoc.transact(() => { + for (let i = 0; i < updates.length; i++) { + Y__namespace.applyUpdate(ydoc, updates[i]); + } + }); + return { update: Y__namespace.encodeStateAsUpdate(ydoc), sv: Y__namespace.encodeStateVector(ydoc) } +}; + +/** + * @param {any} db + * @param {string} docName + * @param {Uint8Array} sv state vector + * @param {number} clock current clock of the document so we can determine when this statevector was created + */ +const writeStateVector = async (db, docName, sv, clock) => { + const encoder = encoding__namespace.createEncoder(); + encoding__namespace.writeVarUint(encoder, clock); + encoding__namespace.writeVarUint8Array(encoder, sv); + await levelPut(db, createDocumentStateVectorKey(docName), encoding__namespace.toUint8Array(encoder)); +}; + +/** + * @param {Uint8Array} buf + * @return {{ sv: Uint8Array, clock: number }} + */ +const decodeLeveldbStateVector = buf => { + const decoder = decoding__namespace.createDecoder(buf); + const clock = decoding__namespace.readVarUint(decoder); + const sv = decoding__namespace.readVarUint8Array(decoder); + return { sv, clock } +}; + +/** + * @param {any} db + * @param {string} docName + */ +const readStateVector$1 = async (db, docName) => { + const buf = await levelGet(db, createDocumentStateVectorKey(docName)); + if (buf === null) { + // no state vector created yet or no document exists + return { sv: null, clock: -1 } + } + return decodeLeveldbStateVector(buf) +}; + +/** + * @param {any} db + * @param {string} docName + * @param {Uint8Array} stateAsUpdate + * @param {Uint8Array} stateVector + * @return {Promise} returns the clock of the flushed doc + */ +const flushDocument = async (db, docName, stateAsUpdate, stateVector) => { + const clock = await storeUpdate(db, docName, stateAsUpdate); + await writeStateVector(db, docName, stateVector, clock); + await clearUpdatesRange(db, docName, 0, clock); // intentionally not waiting for the promise to resolve! + return clock +}; + +/** + * @param {any} db + * @param {string} docName + * @param {Uint8Array} update + * @return {Promise} Returns the clock of the stored update + */ +const storeUpdate = async (db, docName, update) => { + const clock = await getCurrentUpdateClock(db, docName); + if (clock === -1) { + // make sure that a state vector is aways written, so we can search for available documents + const ydoc = new Y__namespace.Doc(); + Y__namespace.applyUpdate(ydoc, update); + const sv = Y__namespace.encodeStateVector(ydoc); + await writeStateVector(db, docName, sv, 0); + } + await levelPut(db, createDocumentUpdateKey(docName, clock + 1), update); + return clock + 1 +}; + +class LeveldbPersistence { + /** + * @param {string} location + * @param {object} [opts] + * @param {any} [opts.level] Level-compatible adapter. E.g. leveldown, level-rem, level-indexeddb. Defaults to `level` + * @param {object} [opts.levelOptions] Options that are passed down to the level instance + */ + constructor (location, /* istanbul ignore next */ { level = defaultLevel__default["default"], levelOptions = {} } = {}) { + const db = level(location, { ...levelOptions, valueEncoding, keyEncoding }); + this.tr = promise__namespace.resolve(); + /** + * Execute an transaction on a database. This will ensure that other processes are currently not writing. + * + * This is a private method and might change in the future. + * + * @todo only transact on the same room-name. Allow for concurrency of different rooms. + * + * @template T + * + * @param {function(any):Promise} f A transaction that receives the db object + * @return {Promise} + */ + this._transact = f => { + const currTr = this.tr; + this.tr = (async () => { + await currTr; + let res = /** @type {any} */ (null); + try { + res = await f(db); + } catch (err) { + /* istanbul ignore next */ + console.warn('Error during y-leveldb transaction', err); + } + return res + })(); + return this.tr + }; + } + + /** + * @param {string} docName + */ + flushDocument (docName) { + return this._transact(async db => { + const updates = await getLevelUpdates(db, docName); + const { update, sv } = mergeUpdates(updates); + await flushDocument(db, docName, update, sv); + }) + } + + /** + * @param {string} docName + * @return {Promise} + */ + getYDoc (docName) { + return this._transact(async db => { + const updates = await getLevelUpdates(db, docName); + const ydoc = new Y__namespace.Doc(); + ydoc.transact(() => { + for (let i = 0; i < updates.length; i++) { + Y__namespace.applyUpdate(ydoc, updates[i]); + } + }); + if (updates.length > PREFERRED_TRIM_SIZE) { + await flushDocument(db, docName, Y__namespace.encodeStateAsUpdate(ydoc), Y__namespace.encodeStateVector(ydoc)); + } + return ydoc + }) + } + + /** + * @param {string} docName + * @return {Promise} + */ + getStateVector (docName) { + return this._transact(async db => { + const { clock, sv } = await readStateVector$1(db, docName); + let curClock = -1; + if (sv !== null) { + curClock = await getCurrentUpdateClock(db, docName); + } + if (sv !== null && clock === curClock) { + return sv + } else { + // current state vector is outdated + const updates = await getLevelUpdates(db, docName); + const { update, sv } = mergeUpdates(updates); + await flushDocument(db, docName, update, sv); + return sv + } + }) + } + + /** + * @param {string} docName + * @param {Uint8Array} update + * @return {Promise} Returns the clock of the stored update + */ + storeUpdate (docName, update) { + return this._transact(db => storeUpdate(db, docName, update)) + } + + /** + * @param {string} docName + * @param {Uint8Array} stateVector + */ + async getDiff (docName, stateVector) { + const ydoc = await this.getYDoc(docName); + return Y__namespace.encodeStateAsUpdate(ydoc, stateVector) + } + + /** + * @param {string} docName + * @return {Promise} + */ + clearDocument (docName) { + return this._transact(async db => { + await db.del(createDocumentStateVectorKey(docName)); + await clearRange(db, createDocumentFirstKey(docName), createDocumentLastKey(docName)); + }) + } + + /** + * @param {string} docName + * @param {string} metaKey + * @param {any} value + * @return {Promise} + */ + setMeta (docName, metaKey, value) { + return this._transact(db => levelPut(db, createDocumentMetaKey(docName, metaKey), buffer__namespace.encodeAny(value))) + } + + /** + * @param {string} docName + * @param {string} metaKey + * @return {Promise} + */ + delMeta (docName, metaKey) { + return this._transact(db => db.del(createDocumentMetaKey(docName, metaKey))) + } + + /** + * @param {string} docName + * @param {string} metaKey + * @return {Promise} + */ + getMeta (docName, metaKey) { + return this._transact(async db => { + const res = await levelGet(db, createDocumentMetaKey(docName, metaKey)); + if (res === null) { + return// return void + } + return buffer__namespace.decodeAny(res) + }) + } + + /** + * @return {Promise>} + */ + getAllDocNames () { + return this._transact(async db => { + const docKeys = await getAllDocs(db, false, true); + return docKeys.map(key => key[1]) + }) + } + + /** + * @return {Promise>} + */ + getAllDocStateVectors () { + return this._transact(async db => { + const docs = /** @type {any} */ (await getAllDocs(db, true, true)); + return docs.map(doc => { + const { sv, clock } = decodeLeveldbStateVector(doc.value); + return { name: doc.key[1], sv, clock } + }) + }) + } + + /** + * @param {string} docName + * @return {Promise>} + */ + getMetas (docName) { + return this._transact(async db => { + const data = await getLevelBulkData(db, { + gte: createDocumentMetaKey(docName, ''), + lt: createDocumentMetaEndKey(docName), + keys: true, + values: true + }); + const metas = new Map(); + data.forEach(v => { metas.set(v.key[3], buffer__namespace.decodeAny(v.value)); }); + return metas + }) + } + + /** + * Close connection to a leveldb database and discard all state and bindings + * + * @return {Promise} + */ + destroy () { + return this._transact(db => db.close()) + } + + /** + * Delete all data in database. + */ + clearAll () { + return this._transact(async db => db.clear()) + } +} + +// When changing this, also make sure to change the file in gitignore +const storageName = 'tmp-leveldb-storage'; + +/** + * Read state vector from Decoder and return as Map. This is a helper method that will be exported by Yjs directly. + * + * @param {decoding.Decoder} decoder + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ +const readStateVector = decoder => { + const ss = new Map(); + const ssLength = decoding__namespace.readVarUint(decoder); + for (let i = 0; i < ssLength; i++) { + const client = decoding__namespace.readVarUint(decoder); + const clock = decoding__namespace.readVarUint(decoder); + ss.set(client, clock); + } + return ss +}; + +/** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ +const decodeStateVector = decodedState => readStateVector(decoding__namespace.createDecoder(decodedState)); + +/** + * Flushes all updates to ldb and delets items from updates array. + * + * @param {LeveldbPersistence} ldb + * @param {string} docName + * @param {Array} updates + */ +const flushUpdatesHelper = (ldb, docName, updates) => + Promise.all(updates.splice(0).map(update => ldb.storeUpdate(docName, update))); + +/** + * @param {t.TestCase} tc + */ +const testLeveldbUpdateStorage = async tc => { + const docName = tc.testName; + const ydoc1 = new Y__namespace.Doc(); + ydoc1.clientID = 0; // so we can check the state vector + const leveldbPersistence = new LeveldbPersistence(storageName); + // clear all data, so we can check allData later + await leveldbPersistence._transact(async db => db.clear()); + t__namespace.compareArrays([], await leveldbPersistence.getAllDocNames()); + + const updates = []; + + ydoc1.on('update', update => { + updates.push(update); + }); + + ydoc1.getArray('arr').insert(0, [1]); + ydoc1.getArray('arr').insert(0, [2]); + + await flushUpdatesHelper(leveldbPersistence, docName, updates); + + const encodedSv = await leveldbPersistence.getStateVector(docName); + const sv = decodeStateVector(encodedSv); + t__namespace.assert(sv.size === 1); + t__namespace.assert(sv.get(0) === 2); + + const ydoc2 = await leveldbPersistence.getYDoc(docName); + t__namespace.compareArrays(ydoc2.getArray('arr').toArray(), [2, 1]); + + const allData = await leveldbPersistence._transact(async db => getLevelBulkData(db, { gte: ['v1'], lt: ['v2'] })); + t__namespace.assert(allData.length > 0, 'some data exists'); + + t__namespace.compareArrays([docName], await leveldbPersistence.getAllDocNames()); + await leveldbPersistence.clearDocument(docName); + t__namespace.compareArrays([], await leveldbPersistence.getAllDocNames()); + const allData2 = await leveldbPersistence._transact(async db => getLevelBulkData(db, { gte: ['v1'], lt: ['v2'] })); + console.log(allData2); + t__namespace.assert(allData2.length === 0, 'really deleted all data'); + + await leveldbPersistence.destroy(); +}; + +/** + * @param {t.TestCase} tc + */ +const testEncodeManyUpdates = async tc => { + const N = PREFERRED_TRIM_SIZE * 7; + const docName = tc.testName; + const ydoc1 = new Y__namespace.Doc(); + ydoc1.clientID = 0; // so we can check the state vector + const leveldbPersistence = new LeveldbPersistence(storageName); + await leveldbPersistence.clearDocument(docName); + + const updates = []; + + ydoc1.on('update', update => { + updates.push(update); + }); + await flushUpdatesHelper(leveldbPersistence, docName, updates); + + const keys = await leveldbPersistence._transact(db => getLevelUpdates(db, docName, { keys: true, values: false })); + + for (let i = 0; i < keys.length; i++) { + t__namespace.assert(keys[i][3] === i); + } + + const yarray = ydoc1.getArray('arr'); + for (let i = 0; i < N; i++) { + yarray.insert(0, [i]); + } + await flushUpdatesHelper(leveldbPersistence, docName, updates); + + const ydoc2 = await leveldbPersistence.getYDoc(docName); + t__namespace.assert(ydoc2.getArray('arr').length === N); + + await leveldbPersistence.flushDocument(docName); + const mergedKeys = await leveldbPersistence._transact(db => getLevelUpdates(db, docName, { keys: true, values: false })); + t__namespace.assert(mergedKeys.length === 1); + + // getYDoc still works after flush/merge + const ydoc3 = await leveldbPersistence.getYDoc(docName); + t__namespace.assert(ydoc3.getArray('arr').length === N); + + // test if state vector is properly generated + t__namespace.compare(Y__namespace.encodeStateVector(ydoc1), await leveldbPersistence.getStateVector(docName)); + // add new update so that sv needs to be updated + ydoc1.getArray('arr').insert(0, ['new']); + await flushUpdatesHelper(leveldbPersistence, docName, updates); + t__namespace.compare(Y__namespace.encodeStateVector(ydoc1), await leveldbPersistence.getStateVector(docName)); + + await leveldbPersistence.destroy(); +}; + +/** + * @param {t.TestCase} tc + */ +const testDiff = async tc => { + const N = PREFERRED_TRIM_SIZE * 2; // primes are awesome - ensure that the document is at least flushed once + const docName = tc.testName; + const ydoc1 = new Y__namespace.Doc(); + ydoc1.clientID = 0; // so we can check the state vector + const leveldbPersistence = new LeveldbPersistence(storageName); + await leveldbPersistence.clearDocument(docName); + + const updates = []; + ydoc1.on('update', update => { + updates.push(update); + }); + + const yarray = ydoc1.getArray('arr'); + // create N changes + for (let i = 0; i < N; i++) { + yarray.insert(0, [i]); + } + await flushUpdatesHelper(leveldbPersistence, docName, updates); + + // create partially merged doc + const ydoc2 = await leveldbPersistence.getYDoc(docName); + + // another N updates + for (let i = 0; i < N; i++) { + yarray.insert(0, [i]); + } + await flushUpdatesHelper(leveldbPersistence, docName, updates); + + // apply diff to doc + const diffUpdate = await leveldbPersistence.getDiff(docName, Y__namespace.encodeStateVector(ydoc2)); + Y__namespace.applyUpdate(ydoc2, diffUpdate); + + t__namespace.assert(ydoc2.getArray('arr').length === ydoc1.getArray('arr').length); + t__namespace.assert(ydoc2.getArray('arr').length === N * 2); + + await leveldbPersistence.destroy(); +}; + +/** + * @param {t.TestCase} tc + */ +const testMetas = async tc => { + const docName = tc.testName; + const leveldbPersistence = new LeveldbPersistence(storageName); + await leveldbPersistence.clearDocument(docName); + + await leveldbPersistence.setMeta(docName, 'a', 4); + await leveldbPersistence.setMeta(docName, 'a', 5); + await leveldbPersistence.setMeta(docName, 'b', 4); + const a = await leveldbPersistence.getMeta(docName, 'a'); + const b = await leveldbPersistence.getMeta(docName, 'b'); + t__namespace.assert(a === 5); + t__namespace.assert(b === 4); + const metas = await leveldbPersistence.getMetas(docName); + t__namespace.assert(metas.size === 2); + t__namespace.assert(metas.get('a') === 5); + t__namespace.assert(metas.get('b') === 4); + await leveldbPersistence.delMeta(docName, 'a'); + const c = await leveldbPersistence.getMeta(docName, 'a'); + t__namespace.assert(c === undefined); + await leveldbPersistence.clearDocument(docName); + const metasEmpty = await leveldbPersistence.getMetas(docName); + t__namespace.assert(metasEmpty.size === 0); + + await leveldbPersistence.destroy(); +}; + +/** + * @param {t.TestCase} tc + */ +const testDeleteEmptySv = async tc => { + const docName = tc.testName; + const leveldbPersistence = new LeveldbPersistence(storageName); + await leveldbPersistence.clearAll(); + + const ydoc = new Y__namespace.Doc(); + ydoc.clientID = 0; + ydoc.getArray('arr').insert(0, [1]); + const singleUpdate = Y__namespace.encodeStateAsUpdate(ydoc); + + t__namespace.compareArrays([], await leveldbPersistence.getAllDocNames()); + await leveldbPersistence.storeUpdate(docName, singleUpdate); + t__namespace.compareArrays([docName], await leveldbPersistence.getAllDocNames()); + const docSvs = await leveldbPersistence.getAllDocStateVectors(); + t__namespace.assert(docSvs.length === 1); + t__namespace.compare([{ name: docName, clock: 0, sv: Y__namespace.encodeStateVector(ydoc) }], docSvs); + + await leveldbPersistence.clearDocument(docName); + t__namespace.compareArrays([], await leveldbPersistence.getAllDocNames()); + await leveldbPersistence.destroy(); +}; + +const testMisc = async tc => { + const docName = tc.testName; + const leveldbPersistence = new LeveldbPersistence(storageName); + await leveldbPersistence.clearDocument(docName); + + const sv = await leveldbPersistence.getStateVector('does not exist'); + t__namespace.assert(sv.byteLength === 1); + + await leveldbPersistence.destroy(); +}; + +var leveldb = /*#__PURE__*/Object.freeze({ + __proto__: null, + testLeveldbUpdateStorage: testLeveldbUpdateStorage, + testEncodeManyUpdates: testEncodeManyUpdates, + testDiff: testDiff, + testMetas: testMetas, + testDeleteEmptySv: testDeleteEmptySv, + testMisc: testMisc +}); + +if (environment_js.isBrowser) { + log__namespace.createVConsole(document.body); +} +t.runTests({ + leveldb +}).then(success => { + /* istanbul ignore next */ + if (environment_js.isNode) { + process.exit(success ? 0 : 1); + } +}); +//# sourceMappingURL=test.cjs.map diff --git a/nodejs/node_modules/y-leveldb/dist/test.cjs.map b/nodejs/node_modules/y-leveldb/dist/test.cjs.map new file mode 100644 index 00000000..b69f5587 --- /dev/null +++ b/nodejs/node_modules/y-leveldb/dist/test.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"test.cjs","sources":["../src/y-leveldb.js","../tests/y-leveldb.tests.js","../tests/index.js"],"sourcesContent":["import * as Y from 'yjs'\nimport * as encoding from 'lib0/encoding.js'\nimport * as decoding from 'lib0/decoding.js'\nimport * as binary from 'lib0/binary.js'\nimport * as promise from 'lib0/promise.js'\nimport * as buffer from 'lib0/buffer.js'\n// @ts-ignore\nimport defaultLevel from 'level'\nimport { Buffer } from 'buffer'\n\nexport const PREFERRED_TRIM_SIZE = 500\n\nconst YEncodingString = 0\nconst YEncodingUint32 = 1\n\nconst valueEncoding = {\n buffer: true,\n type: 'y-value',\n encode: /** @param {any} data */ data => data,\n decode: /** @param {any} data */ data => data\n}\n\n/**\n * Write two bytes as an unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @function\n * @param {encoding.Encoder} encoder\n * @param {number} num The number that is to be encoded.\n */\nexport const writeUint32BigEndian = (encoder, num) => {\n for (let i = 3; i >= 0; i--) {\n encoding.write(encoder, (num >>> (8 * i)) & binary.BITS8)\n }\n}\n\n/**\n * Read 4 bytes as unsigned integer in big endian order.\n * (most significant byte first)\n *\n * @todo use lib0/decoding instead\n *\n * @function\n * @param {decoding.Decoder} decoder\n * @return {number} An unsigned integer.\n */\nexport const readUint32BigEndian = decoder => {\n const uint =\n (decoder.arr[decoder.pos + 3] +\n (decoder.arr[decoder.pos + 2] << 8) +\n (decoder.arr[decoder.pos + 1] << 16) +\n (decoder.arr[decoder.pos] << 24)) >>> 0\n decoder.pos += 4\n return uint\n}\n\nexport const keyEncoding = {\n buffer: true,\n type: 'y-keys',\n /* istanbul ignore next */\n encode: /** @param {Array} arr */ arr => {\n const encoder = encoding.createEncoder()\n for (let i = 0; i < arr.length; i++) {\n const v = arr[i]\n if (typeof v === 'string') {\n encoding.writeUint8(encoder, YEncodingString)\n encoding.writeVarString(encoder, v)\n } else /* istanbul ignore else */ if (typeof v === 'number') {\n encoding.writeUint8(encoder, YEncodingUint32)\n writeUint32BigEndian(encoder, v)\n } else {\n throw new Error('Unexpected key value')\n }\n }\n return Buffer.from(encoding.toUint8Array(encoder))\n },\n decode: /** @param {Uint8Array} buf */ buf => {\n const decoder = decoding.createDecoder(buf)\n const key = []\n while (decoding.hasContent(decoder)) {\n switch (decoding.readUint8(decoder)) {\n case YEncodingString:\n key.push(decoding.readVarString(decoder))\n break\n case YEncodingUint32:\n key.push(readUint32BigEndian(decoder))\n break\n }\n }\n return key\n }\n}\n\n/**\n * level returns an error if a value is not found.\n *\n * This helper method for level returns `null` instead if the key is not found.\n *\n * @param {any} db\n * @param {any} key\n */\nconst levelGet = async (db, key) => {\n let res\n try {\n res = await db.get(key)\n } catch (err) {\n /* istanbul ignore else */\n if (err.notFound) {\n return null\n } else {\n throw err\n }\n }\n return res\n}\n\n/**\n * Level expects a Buffer, but in Yjs we typically work with Uint8Arrays.\n *\n * Since Level thinks that these are two entirely different things,\n * we transform the Uint8array to a Buffer before storing it.\n *\n * @param {any} db\n * @param {any} key\n * @param {Uint8Array} val\n */\nconst levelPut = async (db, key, val) => db.put(key, Buffer.from(val))\n\n/**\n * A \"bulkier\" implementation of level streams. Returns the result in one flush.\n *\n * @param {any} db\n * @param {object} opts\n * @return {Promise>}\n */\nexport const getLevelBulkData = (db, opts) => promise.create((resolve, reject) => {\n /**\n * @type {Array} result\n */\n const result = []\n db.createReadStream(\n opts\n ).on('data', /** @param {any} data */ data =>\n result.push(data)\n ).on('end', () =>\n resolve(result)\n ).on('error', reject)\n})\n\n/**\n * Get all document updates for a specific document.\n *\n * @param {any} db\n * @param {string} docName\n * @param {any} [opts]\n * @return {Promise>}\n */\nexport const getLevelUpdates = (db, docName, opts = { values: true, keys: false }) => getLevelBulkData(db, {\n gte: createDocumentUpdateKey(docName, 0),\n lt: createDocumentUpdateKey(docName, binary.BITS32),\n ...opts\n})\n\n/**\n * Get all document updates for a specific document.\n *\n * @param {any} db\n * @param {boolean} values\n * @param {boolean} keys\n * @return {Promise>}\n */\nexport const getAllDocs = (db, values, keys) => getLevelBulkData(db, {\n gte: ['v1_sv'],\n lt: ['v1_sw'],\n keys,\n values\n})\n\n/**\n * @param {any} db\n * @param {string} docName\n * @return {Promise} Returns -1 if this document doesn't exist yet\n */\nexport const getCurrentUpdateClock = (db, docName) => getLevelUpdates(db, docName, { keys: true, values: false, reverse: true, limit: 1 }).then(keys => {\n if (keys.length === 0) {\n return -1\n } else {\n return keys[0][3]\n }\n})\n\n/**\n * @param {any} db\n * @param {Array} gte Greater than or equal\n * @param {Array} lt lower than (not equal)\n * @return {Promise}\n */\nconst clearRange = async (db, gte, lt) => {\n /* istanbul ignore else */\n if (db.supports.clear) {\n await db.clear({ gte, lt })\n } else {\n const keys = await getLevelBulkData(db, { values: false, keys: true, gte, lt })\n const ops = keys.map(key => ({ type: 'del', key }))\n await db.batch(ops)\n }\n}\n\n/**\n * @param {any} db\n * @param {string} docName\n * @param {number} from Greater than or equal\n * @param {number} to lower than (not equal)\n * @return {Promise}\n */\nconst clearUpdatesRange = async (db, docName, from, to) => clearRange(db, createDocumentUpdateKey(docName, from), createDocumentUpdateKey(docName, to))\n\n/**\n * Create a unique key for a update message.\n * We encode the result using `keyEncoding` which expects an array.\n *\n * @param {string} docName\n * @param {number} clock must be unique\n * @return {Array}\n */\nconst createDocumentUpdateKey = (docName, clock) => ['v1', docName, 'update', clock]\n\n/**\n * @param {string} docName\n * @param {string} metaKey\n */\nconst createDocumentMetaKey = (docName, metaKey) => ['v1', docName, 'meta', metaKey]\n\n/**\n * @param {string} docName\n */\nconst createDocumentMetaEndKey = (docName) => ['v1', docName, 'metb'] // simple trick\n\n/**\n * We have a separate state vector key so we can iterate efficiently over all documents\n * @param {string} docName\n */\nconst createDocumentStateVectorKey = (docName) => ['v1_sv', docName]\n\n/**\n * @param {string} docName\n */\nconst createDocumentFirstKey = (docName) => ['v1', docName]\n\n/**\n * We use this key as the upper limit of all keys that can be written.\n * Make sure that all document keys are smaller! Strings are encoded using varLength string encoding,\n * so we need to make sure that this key has the biggest size!\n *\n * @param {string} docName\n */\nconst createDocumentLastKey = (docName) => ['v1', docName, 'zzzzzzz']\n\n// const emptyStateVector = (() => Y.encodeStateVector(new Y.Doc()))()\n\n/**\n * For now this is a helper method that creates a Y.Doc and then re-encodes a document update.\n * In the future this will be handled by Yjs without creating a Y.Doc (constant memory consumption).\n *\n * @param {Array} updates\n * @return {{update:Uint8Array, sv: Uint8Array}}\n */\nconst mergeUpdates = (updates) => {\n const ydoc = new Y.Doc()\n ydoc.transact(() => {\n for (let i = 0; i < updates.length; i++) {\n Y.applyUpdate(ydoc, updates[i])\n }\n })\n return { update: Y.encodeStateAsUpdate(ydoc), sv: Y.encodeStateVector(ydoc) }\n}\n\n/**\n * @param {any} db\n * @param {string} docName\n * @param {Uint8Array} sv state vector\n * @param {number} clock current clock of the document so we can determine when this statevector was created\n */\nconst writeStateVector = async (db, docName, sv, clock) => {\n const encoder = encoding.createEncoder()\n encoding.writeVarUint(encoder, clock)\n encoding.writeVarUint8Array(encoder, sv)\n await levelPut(db, createDocumentStateVectorKey(docName), encoding.toUint8Array(encoder))\n}\n\n/**\n * @param {Uint8Array} buf\n * @return {{ sv: Uint8Array, clock: number }}\n */\nconst decodeLeveldbStateVector = buf => {\n const decoder = decoding.createDecoder(buf)\n const clock = decoding.readVarUint(decoder)\n const sv = decoding.readVarUint8Array(decoder)\n return { sv, clock }\n}\n\n/**\n * @param {any} db\n * @param {string} docName\n */\nconst readStateVector = async (db, docName) => {\n const buf = await levelGet(db, createDocumentStateVectorKey(docName))\n if (buf === null) {\n // no state vector created yet or no document exists\n return { sv: null, clock: -1 }\n }\n return decodeLeveldbStateVector(buf)\n}\n\n/**\n * @param {any} db\n * @param {string} docName\n * @param {Uint8Array} stateAsUpdate\n * @param {Uint8Array} stateVector\n * @return {Promise} returns the clock of the flushed doc\n */\nconst flushDocument = async (db, docName, stateAsUpdate, stateVector) => {\n const clock = await storeUpdate(db, docName, stateAsUpdate)\n await writeStateVector(db, docName, stateVector, clock)\n await clearUpdatesRange(db, docName, 0, clock) // intentionally not waiting for the promise to resolve!\n return clock\n}\n\n/**\n * @param {any} db\n * @param {string} docName\n * @param {Uint8Array} update\n * @return {Promise} Returns the clock of the stored update\n */\nconst storeUpdate = async (db, docName, update) => {\n const clock = await getCurrentUpdateClock(db, docName)\n if (clock === -1) {\n // make sure that a state vector is aways written, so we can search for available documents\n const ydoc = new Y.Doc()\n Y.applyUpdate(ydoc, update)\n const sv = Y.encodeStateVector(ydoc)\n await writeStateVector(db, docName, sv, 0)\n }\n await levelPut(db, createDocumentUpdateKey(docName, clock + 1), update)\n return clock + 1\n}\n\nexport class LeveldbPersistence {\n /**\n * @param {string} location\n * @param {object} [opts]\n * @param {any} [opts.level] Level-compatible adapter. E.g. leveldown, level-rem, level-indexeddb. Defaults to `level`\n * @param {object} [opts.levelOptions] Options that are passed down to the level instance\n */\n constructor (location, /* istanbul ignore next */ { level = defaultLevel, levelOptions = {} } = {}) {\n const db = level(location, { ...levelOptions, valueEncoding, keyEncoding })\n this.tr = promise.resolve()\n /**\n * Execute an transaction on a database. This will ensure that other processes are currently not writing.\n *\n * This is a private method and might change in the future.\n *\n * @todo only transact on the same room-name. Allow for concurrency of different rooms.\n *\n * @template T\n *\n * @param {function(any):Promise} f A transaction that receives the db object\n * @return {Promise}\n */\n this._transact = f => {\n const currTr = this.tr\n this.tr = (async () => {\n await currTr\n let res = /** @type {any} */ (null)\n try {\n res = await f(db)\n } catch (err) {\n /* istanbul ignore next */\n console.warn('Error during y-leveldb transaction', err)\n }\n return res\n })()\n return this.tr\n }\n }\n\n /**\n * @param {string} docName\n */\n flushDocument (docName) {\n return this._transact(async db => {\n const updates = await getLevelUpdates(db, docName)\n const { update, sv } = mergeUpdates(updates)\n await flushDocument(db, docName, update, sv)\n })\n }\n\n /**\n * @param {string} docName\n * @return {Promise}\n */\n getYDoc (docName) {\n return this._transact(async db => {\n const updates = await getLevelUpdates(db, docName)\n const ydoc = new Y.Doc()\n ydoc.transact(() => {\n for (let i = 0; i < updates.length; i++) {\n Y.applyUpdate(ydoc, updates[i])\n }\n })\n if (updates.length > PREFERRED_TRIM_SIZE) {\n await flushDocument(db, docName, Y.encodeStateAsUpdate(ydoc), Y.encodeStateVector(ydoc))\n }\n return ydoc\n })\n }\n\n /**\n * @param {string} docName\n * @return {Promise}\n */\n getStateVector (docName) {\n return this._transact(async db => {\n const { clock, sv } = await readStateVector(db, docName)\n let curClock = -1\n if (sv !== null) {\n curClock = await getCurrentUpdateClock(db, docName)\n }\n if (sv !== null && clock === curClock) {\n return sv\n } else {\n // current state vector is outdated\n const updates = await getLevelUpdates(db, docName)\n const { update, sv } = mergeUpdates(updates)\n await flushDocument(db, docName, update, sv)\n return sv\n }\n })\n }\n\n /**\n * @param {string} docName\n * @param {Uint8Array} update\n * @return {Promise} Returns the clock of the stored update\n */\n storeUpdate (docName, update) {\n return this._transact(db => storeUpdate(db, docName, update))\n }\n\n /**\n * @param {string} docName\n * @param {Uint8Array} stateVector\n */\n async getDiff (docName, stateVector) {\n const ydoc = await this.getYDoc(docName)\n return Y.encodeStateAsUpdate(ydoc, stateVector)\n }\n\n /**\n * @param {string} docName\n * @return {Promise}\n */\n clearDocument (docName) {\n return this._transact(async db => {\n await db.del(createDocumentStateVectorKey(docName))\n await clearRange(db, createDocumentFirstKey(docName), createDocumentLastKey(docName))\n })\n }\n\n /**\n * @param {string} docName\n * @param {string} metaKey\n * @param {any} value\n * @return {Promise}\n */\n setMeta (docName, metaKey, value) {\n return this._transact(db => levelPut(db, createDocumentMetaKey(docName, metaKey), buffer.encodeAny(value)))\n }\n\n /**\n * @param {string} docName\n * @param {string} metaKey\n * @return {Promise}\n */\n delMeta (docName, metaKey) {\n return this._transact(db => db.del(createDocumentMetaKey(docName, metaKey)))\n }\n\n /**\n * @param {string} docName\n * @param {string} metaKey\n * @return {Promise}\n */\n getMeta (docName, metaKey) {\n return this._transact(async db => {\n const res = await levelGet(db, createDocumentMetaKey(docName, metaKey))\n if (res === null) {\n return// return void\n }\n return buffer.decodeAny(res)\n })\n }\n\n /**\n * @return {Promise>}\n */\n getAllDocNames () {\n return this._transact(async db => {\n const docKeys = await getAllDocs(db, false, true)\n return docKeys.map(key => key[1])\n })\n }\n\n /**\n * @return {Promise>}\n */\n getAllDocStateVectors () {\n return this._transact(async db => {\n const docs = /** @type {any} */ (await getAllDocs(db, true, true))\n return docs.map(doc => {\n const { sv, clock } = decodeLeveldbStateVector(doc.value)\n return { name: doc.key[1], sv, clock }\n })\n })\n }\n\n /**\n * @param {string} docName\n * @return {Promise>}\n */\n getMetas (docName) {\n return this._transact(async db => {\n const data = await getLevelBulkData(db, {\n gte: createDocumentMetaKey(docName, ''),\n lt: createDocumentMetaEndKey(docName),\n keys: true,\n values: true\n })\n const metas = new Map()\n data.forEach(v => { metas.set(v.key[3], buffer.decodeAny(v.value)) })\n return metas\n })\n }\n\n /**\n * Close connection to a leveldb database and discard all state and bindings\n *\n * @return {Promise}\n */\n destroy () {\n return this._transact(db => db.close())\n }\n\n /**\n * Delete all data in database.\n */\n clearAll () {\n return this._transact(async db => db.clear())\n }\n}\n","\nimport * as Y from 'yjs'\nimport { PREFERRED_TRIM_SIZE, LeveldbPersistence, getLevelUpdates, getLevelBulkData } from '../src/y-leveldb.js'\nimport * as t from 'lib0/testing.js'\nimport * as decoding from 'lib0/decoding.js'\n\n// When changing this, also make sure to change the file in gitignore\nconst storageName = 'tmp-leveldb-storage'\n\n/**\n * Read state vector from Decoder and return as Map. This is a helper method that will be exported by Yjs directly.\n *\n * @param {decoding.Decoder} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst readStateVector = decoder => {\n const ss = new Map()\n const ssLength = decoding.readVarUint(decoder)\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder)\n const clock = decoding.readVarUint(decoder)\n ss.set(client, clock)\n }\n return ss\n}\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst decodeStateVector = decodedState => readStateVector(decoding.createDecoder(decodedState))\n\n/**\n * Flushes all updates to ldb and delets items from updates array.\n *\n * @param {LeveldbPersistence} ldb\n * @param {string} docName\n * @param {Array} updates\n */\nconst flushUpdatesHelper = (ldb, docName, updates) =>\n Promise.all(updates.splice(0).map(update => ldb.storeUpdate(docName, update)))\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testLeveldbUpdateStorage = async tc => {\n const docName = tc.testName\n const ydoc1 = new Y.Doc()\n ydoc1.clientID = 0 // so we can check the state vector\n const leveldbPersistence = new LeveldbPersistence(storageName)\n // clear all data, so we can check allData later\n await leveldbPersistence._transact(async db => db.clear())\n t.compareArrays([], await leveldbPersistence.getAllDocNames())\n\n const updates = []\n\n ydoc1.on('update', update => {\n updates.push(update)\n })\n\n ydoc1.getArray('arr').insert(0, [1])\n ydoc1.getArray('arr').insert(0, [2])\n\n await flushUpdatesHelper(leveldbPersistence, docName, updates)\n\n const encodedSv = await leveldbPersistence.getStateVector(docName)\n const sv = decodeStateVector(encodedSv)\n t.assert(sv.size === 1)\n t.assert(sv.get(0) === 2)\n\n const ydoc2 = await leveldbPersistence.getYDoc(docName)\n t.compareArrays(ydoc2.getArray('arr').toArray(), [2, 1])\n\n const allData = await leveldbPersistence._transact(async db => getLevelBulkData(db, { gte: ['v1'], lt: ['v2'] }))\n t.assert(allData.length > 0, 'some data exists')\n\n t.compareArrays([docName], await leveldbPersistence.getAllDocNames())\n await leveldbPersistence.clearDocument(docName)\n t.compareArrays([], await leveldbPersistence.getAllDocNames())\n const allData2 = await leveldbPersistence._transact(async db => getLevelBulkData(db, { gte: ['v1'], lt: ['v2'] }))\n console.log(allData2)\n t.assert(allData2.length === 0, 'really deleted all data')\n\n await leveldbPersistence.destroy()\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testEncodeManyUpdates = async tc => {\n const N = PREFERRED_TRIM_SIZE * 7\n const docName = tc.testName\n const ydoc1 = new Y.Doc()\n ydoc1.clientID = 0 // so we can check the state vector\n const leveldbPersistence = new LeveldbPersistence(storageName)\n await leveldbPersistence.clearDocument(docName)\n\n const updates = []\n\n ydoc1.on('update', update => {\n updates.push(update)\n })\n await flushUpdatesHelper(leveldbPersistence, docName, updates)\n\n const keys = await leveldbPersistence._transact(db => getLevelUpdates(db, docName, { keys: true, values: false }))\n\n for (let i = 0; i < keys.length; i++) {\n t.assert(keys[i][3] === i)\n }\n\n const yarray = ydoc1.getArray('arr')\n for (let i = 0; i < N; i++) {\n yarray.insert(0, [i])\n }\n await flushUpdatesHelper(leveldbPersistence, docName, updates)\n\n const ydoc2 = await leveldbPersistence.getYDoc(docName)\n t.assert(ydoc2.getArray('arr').length === N)\n\n await leveldbPersistence.flushDocument(docName)\n const mergedKeys = await leveldbPersistence._transact(db => getLevelUpdates(db, docName, { keys: true, values: false }))\n t.assert(mergedKeys.length === 1)\n\n // getYDoc still works after flush/merge\n const ydoc3 = await leveldbPersistence.getYDoc(docName)\n t.assert(ydoc3.getArray('arr').length === N)\n\n // test if state vector is properly generated\n t.compare(Y.encodeStateVector(ydoc1), await leveldbPersistence.getStateVector(docName))\n // add new update so that sv needs to be updated\n ydoc1.getArray('arr').insert(0, ['new'])\n await flushUpdatesHelper(leveldbPersistence, docName, updates)\n t.compare(Y.encodeStateVector(ydoc1), await leveldbPersistence.getStateVector(docName))\n\n await leveldbPersistence.destroy()\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testDiff = async tc => {\n const N = PREFERRED_TRIM_SIZE * 2 // primes are awesome - ensure that the document is at least flushed once\n const docName = tc.testName\n const ydoc1 = new Y.Doc()\n ydoc1.clientID = 0 // so we can check the state vector\n const leveldbPersistence = new LeveldbPersistence(storageName)\n await leveldbPersistence.clearDocument(docName)\n\n const updates = []\n ydoc1.on('update', update => {\n updates.push(update)\n })\n\n const yarray = ydoc1.getArray('arr')\n // create N changes\n for (let i = 0; i < N; i++) {\n yarray.insert(0, [i])\n }\n await flushUpdatesHelper(leveldbPersistence, docName, updates)\n\n // create partially merged doc\n const ydoc2 = await leveldbPersistence.getYDoc(docName)\n\n // another N updates\n for (let i = 0; i < N; i++) {\n yarray.insert(0, [i])\n }\n await flushUpdatesHelper(leveldbPersistence, docName, updates)\n\n // apply diff to doc\n const diffUpdate = await leveldbPersistence.getDiff(docName, Y.encodeStateVector(ydoc2))\n Y.applyUpdate(ydoc2, diffUpdate)\n\n t.assert(ydoc2.getArray('arr').length === ydoc1.getArray('arr').length)\n t.assert(ydoc2.getArray('arr').length === N * 2)\n\n await leveldbPersistence.destroy()\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testMetas = async tc => {\n const docName = tc.testName\n const leveldbPersistence = new LeveldbPersistence(storageName)\n await leveldbPersistence.clearDocument(docName)\n\n await leveldbPersistence.setMeta(docName, 'a', 4)\n await leveldbPersistence.setMeta(docName, 'a', 5)\n await leveldbPersistence.setMeta(docName, 'b', 4)\n const a = await leveldbPersistence.getMeta(docName, 'a')\n const b = await leveldbPersistence.getMeta(docName, 'b')\n t.assert(a === 5)\n t.assert(b === 4)\n const metas = await leveldbPersistence.getMetas(docName)\n t.assert(metas.size === 2)\n t.assert(metas.get('a') === 5)\n t.assert(metas.get('b') === 4)\n await leveldbPersistence.delMeta(docName, 'a')\n const c = await leveldbPersistence.getMeta(docName, 'a')\n t.assert(c === undefined)\n await leveldbPersistence.clearDocument(docName)\n const metasEmpty = await leveldbPersistence.getMetas(docName)\n t.assert(metasEmpty.size === 0)\n\n await leveldbPersistence.destroy()\n}\n\n/**\n * @param {t.TestCase} tc\n */\nexport const testDeleteEmptySv = async tc => {\n const docName = tc.testName\n const leveldbPersistence = new LeveldbPersistence(storageName)\n await leveldbPersistence.clearAll()\n\n const ydoc = new Y.Doc()\n ydoc.clientID = 0\n ydoc.getArray('arr').insert(0, [1])\n const singleUpdate = Y.encodeStateAsUpdate(ydoc)\n\n t.compareArrays([], await leveldbPersistence.getAllDocNames())\n await leveldbPersistence.storeUpdate(docName, singleUpdate)\n t.compareArrays([docName], await leveldbPersistence.getAllDocNames())\n const docSvs = await leveldbPersistence.getAllDocStateVectors()\n t.assert(docSvs.length === 1)\n t.compare([{ name: docName, clock: 0, sv: Y.encodeStateVector(ydoc) }], docSvs)\n\n await leveldbPersistence.clearDocument(docName)\n t.compareArrays([], await leveldbPersistence.getAllDocNames())\n await leveldbPersistence.destroy()\n}\n\nexport const testMisc = async tc => {\n const docName = tc.testName\n const leveldbPersistence = new LeveldbPersistence(storageName)\n await leveldbPersistence.clearDocument(docName)\n\n const sv = await leveldbPersistence.getStateVector('does not exist')\n t.assert(sv.byteLength === 1)\n\n await leveldbPersistence.destroy()\n}\n","\nimport * as leveldb from './y-leveldb.tests.js'\n\nimport { runTests } from 'lib0/testing.js'\nimport { isBrowser, isNode } from 'lib0/environment.js'\nimport * as log from 'lib0/logging.js'\n\nif (isBrowser) {\n log.createVConsole(document.body)\n}\nrunTests({\n leveldb\n}).then(success => {\n /* istanbul ignore next */\n if (isNode) {\n process.exit(success ? 0 : 1)\n }\n})\n"],"names":["encoding","binary","Buffer","decoding","promise","Y","readStateVector","defaultLevel","buffer","t","isBrowser","log","runTests","isNode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,MAAM,mBAAmB,GAAG,IAAG;AACtC;AACA,MAAM,eAAe,GAAG,EAAC;AACzB,MAAM,eAAe,GAAG,EAAC;AACzB;AACA,MAAM,aAAa,GAAG;AACtB,EAAE,MAAM,EAAE,IAAI;AACd,EAAE,IAAI,EAAE,SAAS;AACjB,EAAE,MAAM,2BAA2B,IAAI,IAAI,IAAI;AAC/C,EAAE,MAAM,2BAA2B,IAAI,IAAI,IAAI;AAC/C,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,oBAAoB,GAAG,CAAC,OAAO,EAAE,GAAG,KAAK;AACtD,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IA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AAO,EAAC;AACjD;AACA,EAAE,MAAM,EAAE,GAAG,MAAM,kBAAkB,CAAC,cAAc,CAAC,gBAAgB,EAAC;AACtE,EAAEA,YAAC,CAAC,MAAM,CAAC,EAAE,CAAC,UAAU,KAAK,CAAC,EAAC;AAC/B;AACA,EAAE,MAAM,kBAAkB,CAAC,OAAO,GAAE;AACpC;;;;;;;;;;;;ACjPA,IAAIC,wBAAS,EAAE;AACf,EAAEC,cAAG,CAAC,cAAc,CAAC,QAAQ,CAAC,IAAI,EAAC;AACnC,CAAC;AACDC,UAAQ,CAAC;AACT,EAAE,OAAO;AACT,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,IAAI;AACnB;AACA,EAAE,IAAIC,qBAAM,EAAE;AACd,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,GAAG,CAAC,EAAC;AACjC,GAAG;AACH,CAAC;;"} \ No newline at end of file diff --git a/nodejs/node_modules/y-leveldb/dist/test.js b/nodejs/node_modules/y-leveldb/dist/test.js new file mode 100644 index 00000000..37d24ba3 --- /dev/null +++ b/nodejs/node_modules/y-leveldb/dist/test.js @@ -0,0 +1,23086 @@ +(function () { + 'use strict'; + + /** + * Utility module to work with key-value stores. + * + * @module map + */ + + /** + * Creates a new Map instance. + * + * @function + * @return {Map} + * + * @function + */ + const create$6 = () => new Map(); + + /** + * Copy a Map object into a fresh Map object. + * + * @function + * @template X,Y + * @param {Map} m + * @return {Map} + */ + const copy = m => { + const r = create$6(); + m.forEach((v, k) => { r.set(k, v); }); + return r + }; + + /** + * Get map property. Create T if property is undefined and set T on map. + * + * ```js + * const listeners = map.setIfUndefined(events, 'eventName', set.create) + * listeners.add(listener) + * ``` + * + * @function + * @template T,K + * @param {Map} map + * @param {K} key + * @param {function():T} createT + * @return {T} + */ + const setIfUndefined = (map, key, createT) => { + let set = map.get(key); + if (set === undefined) { + map.set(key, set = createT()); + } + return set + }; + + /** + * Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function. + * + * @function + * @template K + * @template V + * @template R + * @param {Map} m + * @param {function(V,K):R} f + * @return {Array} + */ + const map$1 = (m, f) => { + const res = []; + for (const [key, value] of m) { + res.push(f(value, key)); + } + return res + }; + + /** + * Tests whether any key-value pairs pass the test implemented by `f(value, key)`. + * + * @todo should rename to some - similarly to Array.some + * + * @function + * @template K + * @template V + * @param {Map} m + * @param {function(V,K):boolean} f + * @return {boolean} + */ + const any = (m, f) => { + for (const [key, value] of m) { + if (f(value, key)) { + return true + } + } + return false + }; + + /** + * Utility module to work with sets. + * + * @module set + */ + + const create$5 = () => new Set(); + + /** + * Utility module to work with Arrays. + * + * @module array + */ + + /** + * Return the last element of an array. The element must exist + * + * @template L + * @param {Array} arr + * @return {L} + */ + const last = arr => arr[arr.length - 1]; + + /** + * Append elements from src to dest + * + * @template M + * @param {Array} dest + * @param {Array} src + */ + const appendTo = (dest, src) => { + for (let i = 0; i < src.length; i++) { + dest.push(src[i]); + } + }; + + /** + * Transforms something array-like to an actual Array. + * + * @function + * @template T + * @param {ArrayLike|Iterable} arraylike + * @return {T} + */ + const from$1 = Array.from; + + const isArray$1 = Array.isArray; + + /** + * Observable class prototype. + * + * @module observable + */ + + /** + * Handles named events. + * + * @template N + */ + class Observable { + constructor () { + /** + * Some desc. + * @type {Map} + */ + this._observers = create$6(); + } + + /** + * @param {N} name + * @param {function} f + */ + on (name, f) { + setIfUndefined(this._observers, name, create$5).add(f); + } + + /** + * @param {N} name + * @param {function} f + */ + once (name, f) { + /** + * @param {...any} args + */ + const _f = (...args) => { + this.off(name, _f); + f(...args); + }; + this.on(name, _f); + } + + /** + * @param {N} name + * @param {function} f + */ + off (name, f) { + const observers = this._observers.get(name); + if (observers !== undefined) { + observers.delete(f); + if (observers.size === 0) { + this._observers.delete(name); + } + } + } + + /** + * Emit a named event. All registered event listeners that listen to the + * specified name will receive the event. + * + * @todo This should catch exceptions + * + * @param {N} name The event name. + * @param {Array} args The arguments that are applied to the event listener. + */ + emit (name, args) { + // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. + return from$1((this._observers.get(name) || create$6()).values()).forEach(f => f(...args)) + } + + destroy () { + this._observers = create$6(); + } + } + + /** + * Common Math expressions. + * + * @module math + */ + + const floor = Math.floor; + const ceil = Math.ceil; + const abs = Math.abs; + const round = Math.round; + const log10 = Math.log10; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The sum of a and b + */ + const add = (a, b) => a + b; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The smaller element of a and b + */ + const min = (a, b) => a < b ? a : b; + + /** + * @function + * @param {number} a + * @param {number} b + * @return {number} The bigger element of a and b + */ + const max = (a, b) => a > b ? a : b; + /** + * Base 10 exponential function. Returns the value of 10 raised to the power of pow. + * + * @param {number} exp + * @return {number} + */ + const exp10 = exp => Math.pow(10, exp); + + /** + * @param {number} n + * @return {boolean} Wether n is negative. This function also differentiates between -0 and +0 + */ + const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + var byteLength_1 = byteLength; + var toByteArray_1 = toByteArray; + var fromByteArray_1 = fromByteArray; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i$1 = 0, len$1 = code.length; i$1 < len$1; ++i$1) { + lookup[i$1] = code[i$1]; + revLookup[code.charCodeAt(i$1)] = i$1; + } + + // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + + function getLens (b64) { + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('='); + if (validLen === -1) validLen = len; + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4); + + return [validLen, placeHoldersLen] + } + + // base64 is 4/3 + up to two characters of the original data + function byteLength (b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function toByteArray (b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + + var curByte = 0; + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen; + + var i; + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = (tmp >> 16) & 0xFF; + arr[curByte++] = (tmp >> 8) & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[curByte++] = (tmp >> 8) & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ); + } + + return parts.join('') + } + + var base64Js = { + byteLength: byteLength_1, + toByteArray: toByteArray_1, + fromByteArray: fromByteArray_1 + }; + + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + var read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + }; + + var write$1 = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + }; + + var ieee754 = { + read: read, + write: write$1 + }; + + var buffer = createCommonjsModule(function (module, exports) { + + + + var customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null; + + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ); + } + + function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { foo: function () { return 42 } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42 + } catch (e) { + return false + } + } + + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } + }); + + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } + }); + + function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value); + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) + }; + + // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer, Uint8Array); + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + } + + function alloc (size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) + }; + + function allocUnsafe (size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0) + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) + }; + + function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); + + var actual = buf.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } + + return buf + } + + function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf + } + + function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) + } + + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf; + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype); + + return buf + } + + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len); + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } + + function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false + }; + + Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length; + var mustMatch = (arguments.length > 2 && arguments[2] === true); + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.toLocaleString = Buffer.prototype.toString; + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = exports.INSPECT_MAX_BYTES; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) str += ' ... '; + return '' + }; + if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + var strLen = string.length; + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64Js.fromByteArray(buf) + } else { + return base64Js.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUintLE = + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUintBE = + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUint8 = + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUint16LE = + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUint16BE = + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUint32LE = + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUint32BE = + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUintLE = + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUintBE = + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUint8 = + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeUint16LE = + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + return offset + 2 + }; + + Buffer.prototype.writeUint16BE = + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + return offset + 2 + }; + + Buffer.prototype.writeUint32LE = + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + return offset + 4 + }; + + Buffer.prototype.writeUint32BE = + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code; + } + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding); + var len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0]; + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + function base64ToBytes (str) { + return base64Js.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass + // the `instanceof` check but they should be treated as of that type. + // See: https://github.com/feross/buffer/issues/166 + function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) + } + function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare + } + + // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table + })(); + }); + + /** + * Utility module to work with strings. + * + * @module string + */ + + /** + * @param {string} s + * @return {string} + */ + const toLowerCase = s => s.toLowerCase(); + + const trimLeftRegex = /^\s*/g; + + /** + * @param {string} s + * @return {string} + */ + const trimLeft = s => s.replace(trimLeftRegex, ''); + + const fromCamelCaseRegex = /([A-Z])/g; + + /** + * @param {string} s + * @param {string} separator + * @return {string} + */ + const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`)); + + /** + * @param {string} str + * @return {Uint8Array} + */ + const _encodeUtf8Polyfill = str => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + const buf = new Uint8Array(len); + for (let i = 0; i < len; i++) { + buf[i] = /** @type {number} */ (encodedString.codePointAt(i)); + } + return buf + }; + + /* istanbul ignore next */ + const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null); + + /** + * @param {string} str + * @return {Uint8Array} + */ + const _encodeUtf8Native = str => utf8TextEncoder.encode(str); + + /** + * @param {string} str + * @return {Uint8Array} + */ + /* istanbul ignore next */ + const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; + + /* istanbul ignore next */ + let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + + /* istanbul ignore next */ + if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { + // Safari doesn't handle BOM correctly. + // This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called. + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and + // utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call + // Another issue is that from then on no BOM chars are recognized anymore + /* istanbul ignore next */ + utf8TextDecoder = null; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue$2 = []; + var draining$1 = false; + var currentQueue$1; + var queueIndex$1 = -1; + + function cleanUpNextTick$1() { + if (!draining$1 || !currentQueue$1) { + return; + } + draining$1 = false; + if (currentQueue$1.length) { + queue$2 = currentQueue$1.concat(queue$2); + } else { + queueIndex$1 = -1; + } + if (queue$2.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining$1) { + return; + } + var timeout = runTimeout(cleanUpNextTick$1); + draining$1 = true; + + var len = queue$2.length; + while(len) { + currentQueue$1 = queue$2; + queue$2 = []; + while (++queueIndex$1 < len) { + if (currentQueue$1) { + currentQueue$1[queueIndex$1].run(); + } + } + queueIndex$1 = -1; + len = queue$2.length; + } + currentQueue$1 = null; + draining$1 = false; + runClearTimeout(timeout); + } + function nextTick$1(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue$2.push(new Item$2(fun, args)); + if (queue$2.length === 1 && !draining$1) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item$2(fun, array) { + this.fun = fun; + this.array = array; + } + Item$2.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$2 = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config$1 = {}; + + function noop$3() {} + + var on = noop$3; + var addListener = noop$3; + var once$2 = noop$3; + var off = noop$3; + var removeListener = noop$3; + var removeAllListeners = noop$3; + var emit = noop$3; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance$1 = global$1.performance || {}; + var performanceNow = + performance$1.now || + performance$1.mozNow || + performance$1.msNow || + performance$1.oNow || + performance$1.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance$1)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var browser$1$1 = { + nextTick: nextTick$1, + title: title, + browser: browser$2, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once$2, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config$1, + uptime: uptime + }; + + var process$1 = browser$1$1; + + /** + * Often used conditions. + * + * @module conditions + */ + + /** + * @template T + * @param {T|null|undefined} v + * @return {T|null} + */ + /* istanbul ignore next */ + const undefinedToNull = v => v === undefined ? null : v; + + /* global localStorage, addEventListener */ + + /** + * Isomorphic variable storage. + * + * Uses LocalStorage in the browser and falls back to in-memory storage. + * + * @module storage + */ + + /* istanbul ignore next */ + class VarStoragePolyfill { + constructor () { + this.map = new Map(); + } + + /** + * @param {string} key + * @param {any} newValue + */ + setItem (key, newValue) { + this.map.set(key, newValue); + } + + /** + * @param {string} key + */ + getItem (key) { + return this.map.get(key) + } + } + + /* istanbul ignore next */ + /** + * @type {any} + */ + let _localStorage = new VarStoragePolyfill(); + let usePolyfill = true; + + try { + // if the same-origin rule is violated, accessing localStorage might thrown an error + /* istanbul ignore next */ + if (typeof localStorage !== 'undefined') { + _localStorage = localStorage; + usePolyfill = false; + } + } catch (e) { } + + /* istanbul ignore next */ + /** + * This is basically localStorage in browser, or a polyfill in nodejs + */ + const varStorage = _localStorage; + + /** + * Utility functions for working with EcmaScript objects. + * + * @module object + */ + + /** + * @param {Object} obj + */ + const keys$1 = Object.keys; + + /** + * @param {Object} obj + * @param {function(any,string):any} f + */ + const forEach$1 = (obj, f) => { + for (const key in obj) { + f(obj[key], key); + } + }; + + /** + * @template R + * @param {Object} obj + * @param {function(any,string):R} f + * @return {Array} + */ + const map = (obj, f) => { + const results = []; + for (const key in obj) { + results.push(f(obj[key], key)); + } + return results + }; + + /** + * @param {Object} obj + * @return {number} + */ + const length$1 = obj => keys$1(obj).length; + + /** + * @param {Object} obj + * @param {function(any,string):boolean} f + * @return {boolean} + */ + const every = (obj, f) => { + for (const key in obj) { + if (!f(obj[key], key)) { + return false + } + } + return true + }; + + /** + * Calls `Object.prototype.hasOwnProperty`. + * + * @param {any} obj + * @param {string|symbol} key + * @return {boolean} + */ + const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); + + /** + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ + const equalFlat = (a, b) => a === b || (length$1(a) === length$1(b) && every(a, (val, key) => (val !== undefined || hasProperty(b, key)) && b[key] === val)); + + /** + * Common functions and function call helpers. + * + * @module function + */ + + /** + * Calls all functions in `fs` with args. Only throws after all functions were called. + * + * @param {Array} fs + * @param {Array} args + */ + const callAll = (fs, args, i = 0) => { + try { + for (; i < fs.length; i++) { + fs[i](...args); + } + } finally { + if (i < fs.length) { + callAll(fs, args, i + 1); + } + } + }; + + /** + * @template V + * @template {V} OPTS + * + * @param {V} value + * @param {Array} options + */ + // @ts-ignore + const isOneOf = (value, options) => options.includes(value); + + /* istanbul ignore next */ + // @ts-ignore + const isNode = typeof process$1 !== 'undefined' && process$1.release && + /node|io\.js/.test(process$1.release.name); + /* istanbul ignore next */ + const isBrowser = typeof window !== 'undefined' && !isNode; + /* istanbul ignore next */ + typeof navigator !== 'undefined' + ? /Mac/.test(navigator.platform) + : false; + + /** + * @type {Map} + */ + let params; + + /* istanbul ignore next */ + const computeParams = () => { + if (params === undefined) { + if (isNode) { + params = create$6(); + const pargs = process$1.argv; + let currParamName = null; + /* istanbul ignore next */ + for (let i = 0; i < pargs.length; i++) { + const parg = pargs[i]; + if (parg[0] === '-') { + if (currParamName !== null) { + params.set(currParamName, ''); + } + currParamName = parg; + } else { + if (currParamName !== null) { + params.set(currParamName, parg); + currParamName = null; + } + } + } + if (currParamName !== null) { + params.set(currParamName, ''); + } + // in ReactNative for example this would not be true (unless connected to the Remote Debugger) + } else if (typeof location === 'object') { + params = create$6(); // eslint-disable-next-line no-undef + (location.search || '?').slice(1).split('&').forEach((kv) => { + if (kv.length !== 0) { + const [key, value] = kv.split('='); + params.set(`--${fromCamelCase(key, '-')}`, value); + params.set(`-${fromCamelCase(key, '-')}`, value); + } + }); + } else { + params = create$6(); + } + } + return params + }; + + /** + * @param {string} name + * @return {boolean} + */ + /* istanbul ignore next */ + const hasParam = (name) => computeParams().has(name); + + /** + * @param {string} name + * @param {string} defaultVal + * @return {string} + */ + /* istanbul ignore next */ + const getParam = (name, defaultVal) => + computeParams().get(name) || defaultVal; + // export const getArgs = name => computeParams() && args + + /** + * @param {string} name + * @return {string|null} + */ + /* istanbul ignore next */ + const getVariable = (name) => + isNode + ? undefinedToNull(process$1.env[name.toUpperCase()]) + : undefinedToNull(varStorage.getItem(name)); + + /** + * @param {string} name + * @return {boolean} + */ + /* istanbul ignore next */ + const hasConf = (name) => + hasParam('--' + name) || getVariable(name) !== null; + + /* istanbul ignore next */ + hasConf('production'); + + /* istanbul ignore next */ + const forceColor = isNode && + isOneOf(process$1.env.FORCE_COLOR, ['true', '1', '2']); + + /* istanbul ignore next */ + const supportsColor = !hasParam('no-colors') && + (!isNode || process$1.stdout.isTTY || forceColor) && ( + !isNode || hasParam('color') || forceColor || + getVariable('COLORTERM') !== null || + (getVariable('TERM') || '').includes('color') + ); + + /* eslint-env browser */ + + /** + * Binary data constants. + * + * @module binary + */ + + /** + * n-th bit activated. + * + * @type {number} + */ + const BIT1 = 1; + const BIT2 = 2; + const BIT3 = 4; + const BIT4 = 8; + const BIT6 = 32; + const BIT7 = 64; + const BIT8 = 128; + const BITS5 = 31; + const BITS6 = 63; + const BITS7 = 127; + const BITS8 = 255; + /** + * @type {number} + */ + const BITS31 = 0x7FFFFFFF; + /** + * @type {number} + */ + const BITS32 = 0xFFFFFFFF; + + /** + * Utility helpers for working with numbers. + * + * @module number + */ + + const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; + + /** + * @module number + */ + + /* istanbul ignore next */ + const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && floor(num) === num); + + /** + * Error helpers. + * + * @module error + */ + + /* istanbul ignore next */ + /** + * @param {string} s + * @return {Error} + */ + const create$4 = s => new Error(s); + + /* istanbul ignore next */ + /** + * @throws {Error} + * @return {never} + */ + const methodUnimplemented = () => { + throw create$4('Method unimplemented') + }; + + /* istanbul ignore next */ + /** + * @throws {Error} + * @return {never} + */ + const unexpectedCase = () => { + throw create$4('Unexpected case') + }; + + /** + * Efficient schema-less binary decoding with support for variable length encoding. + * + * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = new encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = new decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module decoding + */ + + const errorUnexpectedEndOfArray = create$4('Unexpected end of array'); + const errorIntegerOutOfRange = create$4('Integer out of Range'); + + /** + * A Decoder handles the decoding of an Uint8Array. + */ + class Decoder { + /** + * @param {Uint8Array} uint8Array Binary data to decode + */ + constructor (uint8Array) { + /** + * Decoding target. + * + * @type {Uint8Array} + */ + this.arr = uint8Array; + /** + * Current decoding position. + * + * @type {number} + */ + this.pos = 0; + } + } + + /** + * @function + * @param {Uint8Array} uint8Array + * @return {Decoder} + */ + const createDecoder = uint8Array => new Decoder(uint8Array); + + /** + * @function + * @param {Decoder} decoder + * @return {boolean} + */ + const hasContent = decoder => decoder.pos !== decoder.arr.length; + + /** + * Create an Uint8Array view of the next `len` bytes and advance the position by `len`. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder The decoder instance + * @param {number} len The length of bytes to read + * @return {Uint8Array} + */ + const readUint8Array = (decoder, len) => { + const view = createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); + decoder.pos += len; + return view + }; + + /** + * Read variable length Uint8Array. + * + * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks. + * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array. + * + * @function + * @param {Decoder} decoder + * @return {Uint8Array} + */ + const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder)); + + /** + * Read one byte as unsigned integer. + * @function + * @param {Decoder} decoder The decoder instance + * @return {number} Unsigned 8-bit integer + */ + const readUint8 = decoder => decoder.arr[decoder.pos++]; + + /** + * Read unsigned integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ + const readVarUint = decoder => { + let num = 0; + let mult = 1; + const len = decoder.arr.length; + while (decoder.pos < len) { + const r = decoder.arr[decoder.pos++]; + // num = num | ((r & binary.BITS7) << len) + num = num + (r & BITS7) * mult; // shift $r << (7*#iterations) and add it to num + mult *= 128; // next iteration, shift 7 "more" to the left + if (r < BIT8) { + return num + } + /* istanbul ignore if */ + if (num > MAX_SAFE_INTEGER) { + throw errorIntegerOutOfRange + } + } + throw errorUnexpectedEndOfArray + }; + + /** + * Read signed integer (32bit) with variable length. + * 1/8th of the storage is used as encoding overhead. + * * numbers < 2^7 is stored in one bytlength + * * numbers < 2^14 is stored in two bylength + * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change. + * + * @function + * @param {Decoder} decoder + * @return {number} An unsigned integer.length + */ + const readVarInt = decoder => { + let r = decoder.arr[decoder.pos++]; + let num = r & BITS6; + let mult = 64; + const sign = (r & BIT7) > 0 ? -1 : 1; + if ((r & BIT8) === 0) { + // don't continue reading + return sign * num + } + const len = decoder.arr.length; + while (decoder.pos < len) { + r = decoder.arr[decoder.pos++]; + // num = num | ((r & binary.BITS7) << len) + num = num + (r & BITS7) * mult; + mult *= 128; + if (r < BIT8) { + return sign * num + } + /* istanbul ignore if */ + if (num > MAX_SAFE_INTEGER) { + throw errorIntegerOutOfRange + } + } + throw errorUnexpectedEndOfArray + }; + + /** + * We don't test this function anymore as we use native decoding/encoding by default now. + * Better not modify this anymore.. + * + * Transforming utf8 to a string is pretty expensive. The code performs 10x better + * when String.fromCodePoint is fed with all characters as arguments. + * But most environments have a maximum number of arguments per functions. + * For effiency reasons we apply a maximum of 10000 characters at once. + * + * @function + * @param {Decoder} decoder + * @return {String} The read String. + */ + /* istanbul ignore next */ + const _readVarStringPolyfill = decoder => { + let remainingLen = readVarUint(decoder); + if (remainingLen === 0) { + return '' + } else { + let encodedString = String.fromCodePoint(readUint8(decoder)); // remember to decrease remainingLen + if (--remainingLen < 100) { // do not create a Uint8Array for small strings + while (remainingLen--) { + encodedString += String.fromCodePoint(readUint8(decoder)); + } + } else { + while (remainingLen > 0) { + const nextLen = remainingLen < 10000 ? remainingLen : 10000; + // this is dangerous, we create a fresh array view from the existing buffer + const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); + decoder.pos += nextLen; + // Starting with ES5.1 we can supply a generic array-like object as arguments + encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes)); + remainingLen -= nextLen; + } + } + return decodeURIComponent(escape(encodedString)) + } + }; + + /** + * @function + * @param {Decoder} decoder + * @return {String} The read String + */ + const _readVarStringNative = decoder => + /** @type any */ (utf8TextDecoder).decode(readVarUint8Array(decoder)); + + /** + * Read string of variable length + * * varUint is used to store the length of the string + * + * @function + * @param {Decoder} decoder + * @return {String} The read String + * + */ + /* istanbul ignore next */ + const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; + + /** + * @param {Decoder} decoder + * @param {number} len + * @return {DataView} + */ + const readFromDataView = (decoder, len) => { + const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); + decoder.pos += len; + return dv + }; + + /** + * @param {Decoder} decoder + */ + const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false); + + /** + * @param {Decoder} decoder + */ + const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false); + + /** + * @param {Decoder} decoder + */ + const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false); + + /** + * @type {Array} + */ + const readAnyLookupTable = [ + decoder => undefined, // CASE 127: undefined + decoder => null, // CASE 126: null + readVarInt, // CASE 125: integer + readFloat32, // CASE 124: float32 + readFloat64, // CASE 123: float64 + readBigInt64, // CASE 122: bigint + decoder => false, // CASE 121: boolean (false) + decoder => true, // CASE 120: boolean (true) + readVarString, // CASE 119: string + decoder => { // CASE 118: object + const len = readVarUint(decoder); + /** + * @type {Object} + */ + const obj = {}; + for (let i = 0; i < len; i++) { + const key = readVarString(decoder); + obj[key] = readAny(decoder); + } + return obj + }, + decoder => { // CASE 117: array + const len = readVarUint(decoder); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(readAny(decoder)); + } + return arr + }, + readVarUint8Array // CASE 116: Uint8Array + ]; + + /** + * @param {Decoder} decoder + */ + const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder); + + /** + * T must not be null. + * + * @template T + */ + class RleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + * @param {function(Decoder):T} reader + */ + constructor (uint8Array, reader) { + super(uint8Array); + /** + * The reader + */ + this.reader = reader; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = this.reader(this); + if (hasContent(this)) { + this.count = readVarUint(this) + 1; // see encoder implementation for the reason why this is incremented + } else { + this.count = -1; // read the current value forever + } + } + this.count--; + return /** @type {T} */ (this.s) + } + } + + class UintOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + read () { + if (this.count === 0) { + this.s = readVarInt(this); + // if the sign is negative, we read the count too, otherwise count is 1 + const isNegative = isNegativeZero(this.s); + this.count = 1; + if (isNegative) { + this.s = -this.s; + this.count = readVarUint(this) + 2; + } + } + this.count--; + return /** @type {number} */ (this.s) + } + } + + class IntDiffOptRleDecoder extends Decoder { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + super(uint8Array); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @return {number} + */ + read () { + if (this.count === 0) { + const diff = readVarInt(this); + // if the first bit is set, we read more data + const hasCount = diff & 1; + this.diff = floor(diff / 2); // shift >> 1 + this.count = 1; + if (hasCount) { + this.count = readVarUint(this) + 2; + } + } + this.s += this.diff; + this.count--; + return this.s + } + } + + class StringDecoder$2 { + /** + * @param {Uint8Array} uint8Array + */ + constructor (uint8Array) { + this.decoder = new UintOptRleDecoder(uint8Array); + this.str = readVarString(this.decoder); + /** + * @type {number} + */ + this.spos = 0; + } + + /** + * @return {string} + */ + read () { + const end = this.spos + this.decoder.read(); + const res = this.str.slice(this.spos, end); + this.spos = end; + return res + } + } + + /** + * @param {number} len + */ + const createUint8ArrayFromLen = len => new Uint8Array(len); + + /** + * Create Uint8Array with initial content from buffer + * + * @param {ArrayBuffer} buffer + * @param {number} byteOffset + * @param {number} length + */ + const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length); + + /** + * Copy the content of an Uint8Array view to a new ArrayBuffer. + * + * @param {Uint8Array} uint8Array + * @return {Uint8Array} + */ + const copyUint8Array = uint8Array => { + const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); + newBuf.set(uint8Array); + return newBuf + }; + + /** + * Encode anything as a UInt8Array. It's a pun on typescripts's `any` type. + * See encoding.writeAny for more information. + * + * @param {any} data + * @return {Uint8Array} + */ + const encodeAny = data => { + const encoder = createEncoder(); + writeAny(encoder, data); + return toUint8Array(encoder) + }; + + /** + * Decode an any-encoded value. + * + * @param {Uint8Array} buf + * @return {any} + */ + const decodeAny = buf => readAny(createDecoder(buf)); + + /** + * Efficient schema-less binary encoding with support for variable length encoding. + * + * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function. + * + * Encodes numbers in little-endian order (least to most significant byte order) + * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/) + * which is also used in Protocol Buffers. + * + * ```js + * // encoding step + * const encoder = new encoding.createEncoder() + * encoding.writeVarUint(encoder, 256) + * encoding.writeVarString(encoder, 'Hello world!') + * const buf = encoding.toUint8Array(encoder) + * ``` + * + * ```js + * // decoding step + * const decoder = new decoding.createDecoder(buf) + * decoding.readVarUint(decoder) // => 256 + * decoding.readVarString(decoder) // => 'Hello world!' + * decoding.hasContent(decoder) // => false - all data is read + * ``` + * + * @module encoding + */ + + /** + * A BinaryEncoder handles the encoding to an Uint8Array. + */ + class Encoder { + constructor () { + this.cpos = 0; + this.cbuf = new Uint8Array(100); + /** + * @type {Array} + */ + this.bufs = []; + } + } + + /** + * @function + * @return {Encoder} + */ + const createEncoder = () => new Encoder(); + + /** + * The current length of the encoded data. + * + * @function + * @param {Encoder} encoder + * @return {number} + */ + const length = encoder => { + let len = encoder.cpos; + for (let i = 0; i < encoder.bufs.length; i++) { + len += encoder.bufs[i].length; + } + return len + }; + + /** + * Transform to Uint8Array. + * + * @function + * @param {Encoder} encoder + * @return {Uint8Array} The created ArrayBuffer. + */ + const toUint8Array = encoder => { + const uint8arr = new Uint8Array(length(encoder)); + let curPos = 0; + for (let i = 0; i < encoder.bufs.length; i++) { + const d = encoder.bufs[i]; + uint8arr.set(d, curPos); + curPos += d.length; + } + uint8arr.set(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos); + return uint8arr + }; + + /** + * Verify that it is possible to write `len` bytes wtihout checking. If + * necessary, a new Buffer with the required length is attached. + * + * @param {Encoder} encoder + * @param {number} len + */ + const verifyLen = (encoder, len) => { + const bufferLen = encoder.cbuf.length; + if (bufferLen - encoder.cpos < len) { + encoder.bufs.push(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos)); + encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); + encoder.cpos = 0; + } + }; + + /** + * Write one byte to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {number} num The byte that is to be encoded. + */ + const write = (encoder, num) => { + const bufferLen = encoder.cbuf.length; + if (encoder.cpos === bufferLen) { + encoder.bufs.push(encoder.cbuf); + encoder.cbuf = new Uint8Array(bufferLen * 2); + encoder.cpos = 0; + } + encoder.cbuf[encoder.cpos++] = num; + }; + + /** + * Write one byte as an unsigned integer. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeUint8 = write; + + /** + * Write a variable length unsigned integer. Max encodable integer is 2^53. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeVarUint = (encoder, num) => { + while (num > BITS7) { + write(encoder, BIT8 | (BITS7 & num)); + num = floor(num / 128); // shift >>> 7 + } + write(encoder, BITS7 & num); + }; + + /** + * Write a variable length integer. + * + * We use the 7th bit instead for signaling that this is a negative number. + * + * @function + * @param {Encoder} encoder + * @param {number} num The number that is to be encoded. + */ + const writeVarInt = (encoder, num) => { + const isNegative = isNegativeZero(num); + if (isNegative) { + num = -num; + } + // |- whether to continue reading |- whether is negative |- number + write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | (BITS6 & num)); + num = floor(num / 64); // shift >>> 6 + // We don't need to consider the case of num === 0 so we can use a different + // pattern here than above. + while (num > 0) { + write(encoder, (num > BITS7 ? BIT8 : 0) | (BITS7 & num)); + num = floor(num / 128); // shift >>> 7 + } + }; + + /** + * A cache to store strings temporarily + */ + const _strBuffer = new Uint8Array(30000); + const _maxStrBSize = _strBuffer.length / 3; + + /** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ + const _writeVarStringNative = (encoder, str) => { + if (str.length < _maxStrBSize) { + // We can encode the string into the existing buffer + /* istanbul ignore else */ + const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; + writeVarUint(encoder, written); + for (let i = 0; i < written; i++) { + write(encoder, _strBuffer[i]); + } + } else { + writeVarUint8Array(encoder, encodeUtf8(str)); + } + }; + + /** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ + const _writeVarStringPolyfill = (encoder, str) => { + const encodedString = unescape(encodeURIComponent(str)); + const len = encodedString.length; + writeVarUint(encoder, len); + for (let i = 0; i < len; i++) { + write(encoder, /** @type {number} */ (encodedString.codePointAt(i))); + } + }; + + /** + * Write a variable length string. + * + * @function + * @param {Encoder} encoder + * @param {String} str The string that is to be encoded. + */ + /* istanbul ignore next */ + const writeVarString = (utf8TextEncoder && utf8TextEncoder.encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill; + + /** + * Append fixed-length Uint8Array to the encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ + const writeUint8Array = (encoder, uint8Array) => { + const bufferLen = encoder.cbuf.length; + const cpos = encoder.cpos; + const leftCopyLen = min(bufferLen - cpos, uint8Array.length); + const rightCopyLen = uint8Array.length - leftCopyLen; + encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); + encoder.cpos += leftCopyLen; + if (rightCopyLen > 0) { + // Still something to write, write right half.. + // Append new buffer + encoder.bufs.push(encoder.cbuf); + // must have at least size of remaining buffer + encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); + // copy array + encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); + encoder.cpos = rightCopyLen; + } + }; + + /** + * Append an Uint8Array to Encoder. + * + * @function + * @param {Encoder} encoder + * @param {Uint8Array} uint8Array + */ + const writeVarUint8Array = (encoder, uint8Array) => { + writeVarUint(encoder, uint8Array.byteLength); + writeUint8Array(encoder, uint8Array); + }; + + /** + * Create an DataView of the next `len` bytes. Use it to write data after + * calling this function. + * + * ```js + * // write float32 using DataView + * const dv = writeOnDataView(encoder, 4) + * dv.setFloat32(0, 1.1) + * // read float32 using DataView + * const dv = readFromDataView(encoder, 4) + * dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result) + * ``` + * + * @param {Encoder} encoder + * @param {number} len + * @return {DataView} + */ + const writeOnDataView = (encoder, len) => { + verifyLen(encoder, len); + const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); + encoder.cpos += len; + return dview + }; + + /** + * @param {Encoder} encoder + * @param {number} num + */ + const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); + + /** + * @param {Encoder} encoder + * @param {number} num + */ + const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); + + /** + * @param {Encoder} encoder + * @param {bigint} num + */ + const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false); + + const floatTestBed = new DataView(new ArrayBuffer(4)); + /** + * Check if a number can be encoded as a 32 bit float. + * + * @param {number} num + * @return {boolean} + */ + const isFloat32 = num => { + floatTestBed.setFloat32(0, num); + return floatTestBed.getFloat32(0) === num + }; + + /** + * Encode data with efficient binary format. + * + * Differences to JSON: + * • Transforms data to a binary format (not to a string) + * • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON) + * • Numbers are efficiently encoded either as a variable length integer, as a + * 32 bit float, as a 64 bit float, or as a 64 bit bigint. + * + * Encoding table: + * + * | Data Type | Prefix | Encoding Method | Comment | + * | ------------------- | -------- | ------------------ | ------- | + * | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined | + * | null | 126 | | | + * | integer | 125 | writeVarInt | Only encodes 32 bit signed integers | + * | float32 | 124 | writeFloat32 | | + * | float64 | 123 | writeFloat64 | | + * | bigint | 122 | writeBigInt64 | | + * | boolean (false) | 121 | | True and false are different data types so we save the following byte | + * | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false | + * | string | 119 | writeVarString | | + * | object | 118 | custom | Writes {length} then {length} key-value pairs | + * | array | 117 | custom | Writes {length} then {length} json values | + * | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data | + * + * Reasons for the decreasing prefix: + * We need the first bit for extendability (later we may want to encode the + * prefix with writeVarUint). The remaining 7 bits are divided as follows: + * [0-30] the beginning of the data range is used for custom purposes + * (defined by the function that uses this library) + * [31-127] the end of the data range is used for data encoding by + * lib0/encoding.js + * + * @param {Encoder} encoder + * @param {undefined|null|number|bigint|boolean|string|Object|Array|Uint8Array} data + */ + const writeAny = (encoder, data) => { + switch (typeof data) { + case 'string': + // TYPE 119: STRING + write(encoder, 119); + writeVarString(encoder, data); + break + case 'number': + if (isInteger(data) && abs(data) <= BITS31) { + // TYPE 125: INTEGER + write(encoder, 125); + writeVarInt(encoder, data); + } else if (isFloat32(data)) { + // TYPE 124: FLOAT32 + write(encoder, 124); + writeFloat32(encoder, data); + } else { + // TYPE 123: FLOAT64 + write(encoder, 123); + writeFloat64(encoder, data); + } + break + case 'bigint': + // TYPE 122: BigInt + write(encoder, 122); + writeBigInt64(encoder, data); + break + case 'object': + if (data === null) { + // TYPE 126: null + write(encoder, 126); + } else if (data instanceof Array) { + // TYPE 117: Array + write(encoder, 117); + writeVarUint(encoder, data.length); + for (let i = 0; i < data.length; i++) { + writeAny(encoder, data[i]); + } + } else if (data instanceof Uint8Array) { + // TYPE 116: ArrayBuffer + write(encoder, 116); + writeVarUint8Array(encoder, data); + } else { + // TYPE 118: Object + write(encoder, 118); + const keys = Object.keys(data); + writeVarUint(encoder, keys.length); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + writeVarString(encoder, key); + writeAny(encoder, data[key]); + } + } + break + case 'boolean': + // TYPE 120/121: boolean (true/false) + write(encoder, data ? 120 : 121); + break + default: + // TYPE 127: undefined + write(encoder, 127); + } + }; + + /** + * Now come a few stateful encoder that have their own classes. + */ + + /** + * Basic Run Length Encoder - a basic compression implementation. + * + * Encodes [1,1,1,7] to [1,3,7,1] (3 times 1, 1 time 7). This encoder might do more harm than good if there are a lot of values that are not repeated. + * + * It was originally used for image compression. Cool .. article http://csbruce.com/cbm/transactor/pdfs/trans_v7_i06.pdf + * + * @note T must not be null! + * + * @template T + */ + class RleEncoder extends Encoder { + /** + * @param {function(Encoder, T):void} writer + */ + constructor (writer) { + super(); + /** + * The writer + */ + this.w = writer; + /** + * Current state + * @type {T|null} + */ + this.s = null; + this.count = 0; + } + + /** + * @param {T} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + if (this.count > 0) { + // flush counter, unless this is the first value (count = 0) + writeVarUint(this, this.count - 1); // since count is always > 0, we can decrement by one. non-standard encoding ftw + } + this.count = 1; + // write first value + this.w(this, v); + this.s = v; + } + } + } + + /** + * @param {UintOptRleEncoder} encoder + */ + const flushUintOptRleEncoder = encoder => { + /* istanbul ignore else */ + if (encoder.count > 0) { + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set sign to positive + // case 2: write several values. set sign to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } + }; + + /** + * Optimized Rle encoder that does not suffer from the mentioned problem of the basic Rle encoder. + * + * Internally uses VarInt encoder to write unsigned integers. If the input occurs multiple times, we write + * write it as a negative number. The UintOptRleDecoder then understands that it needs to read a count. + * + * Encodes [1,2,3,3,3] as [1,2,-3,3] (once 1, once 2, three times 3) + */ + class UintOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.s === v) { + this.count++; + } else { + flushUintOptRleEncoder(this); + this.count = 1; + this.s = v; + } + } + + toUint8Array () { + flushUintOptRleEncoder(this); + return toUint8Array(this.encoder) + } + } + + /** + * @param {IntDiffOptRleEncoder} encoder + */ + const flushIntDiffOptRleEncoder = encoder => { + if (encoder.count > 0) { + // 31 bit making up the diff | wether to write the counter + // const encodedDiff = encoder.diff << 1 | (encoder.count === 1 ? 0 : 1) + const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); + // flush counter, unless this is the first value (count = 0) + // case 1: just a single value. set first bit to positive + // case 2: write several values. set first bit to negative to indicate that there is a length coming + writeVarInt(encoder.encoder, encodedDiff); + if (encoder.count > 1) { + writeVarUint(encoder.encoder, encoder.count - 2); // since count is always > 1, we can decrement by one. non-standard encoding ftw + } + } + }; + + /** + * A combination of the IntDiffEncoder and the UintOptRleEncoder. + * + * The count approach is similar to the UintDiffOptRleEncoder, but instead of using the negative bitflag, it encodes + * in the LSB whether a count is to be read. Therefore this Encoder only supports 31 bit integers! + * + * Encodes [1, 2, 3, 2] as [3, 1, 6, -1] (more specifically [(1 << 1) | 1, (3 << 0) | 0, -1]) + * + * Internally uses variable length encoding. Contrary to normal UintVar encoding, the first byte contains: + * * 1 bit that denotes whether the next value is a count (LSB) + * * 1 bit that denotes whether this value is negative (MSB - 1) + * * 1 bit that denotes whether to continue reading the variable length integer (MSB) + * + * Therefore, only five bits remain to encode diff ranges. + * + * Use this Encoder only when appropriate. In most cases, this is probably a bad idea. + */ + class IntDiffOptRleEncoder { + constructor () { + this.encoder = new Encoder(); + /** + * @type {number} + */ + this.s = 0; + this.count = 0; + this.diff = 0; + } + + /** + * @param {number} v + */ + write (v) { + if (this.diff === v - this.s) { + this.s = v; + this.count++; + } else { + flushIntDiffOptRleEncoder(this); + this.count = 1; + this.diff = v - this.s; + this.s = v; + } + } + + toUint8Array () { + flushIntDiffOptRleEncoder(this); + return toUint8Array(this.encoder) + } + } + + /** + * Optimized String Encoder. + * + * Encoding many small strings in a simple Encoder is not very efficient. The function call to decode a string takes some time and creates references that must be eventually deleted. + * In practice, when decoding several million small strings, the GC will kick in more and more often to collect orphaned string objects (or maybe there is another reason?). + * + * This string encoder solves the above problem. All strings are concatenated and written as a single string using a single encoding call. + * + * The lengths are encoded using a UintOptRleEncoder. + */ + class StringEncoder { + constructor () { + /** + * @type {Array} + */ + this.sarr = []; + this.s = ''; + this.lensE = new UintOptRleEncoder(); + } + + /** + * @param {string} string + */ + write (string) { + this.s += string; + if (this.s.length > 19) { + this.sarr.push(this.s); + this.s = ''; + } + this.lensE.write(string.length); + } + + toUint8Array () { + const encoder = new Encoder(); + this.sarr.push(this.s); + this.s = ''; + writeVarString(encoder, this.sarr.join('')); + writeUint8Array(encoder, this.lensE.toUint8Array()); + return toUint8Array(encoder) + } + } + + /* eslint-env browser */ + const performance = typeof window === 'undefined' ? null : (typeof window.performance !== 'undefined' && window.performance) || null; + + const isoCrypto = typeof crypto === 'undefined' ? null : crypto; + + /** + * @type {function(number):ArrayBuffer} + */ + const cryptoRandomBuffer = isoCrypto !== null + ? len => { + // browser + const buf = new ArrayBuffer(len); + const arr = new Uint8Array(buf); + isoCrypto.getRandomValues(arr); + return buf + } + : len => { + // polyfill + const buf = new ArrayBuffer(len); + const arr = new Uint8Array(buf); + for (let i = 0; i < len; i++) { + arr[i] = Math.ceil((Math.random() * 0xFFFFFFFF) >>> 0); + } + return buf + }; + + const uint32 = () => new Uint32Array(cryptoRandomBuffer(4))[0]; + + // @ts-ignore + const uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11; + const uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c => + (c ^ uint32() & 15 >> c / 4).toString(16) + ); + + /** + * Utility module to convert metric values. + * + * @module metric + */ + + const prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; + const prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y']; + + /** + * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }` + * + * @param {number} n + * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds + * @return {{n:number,prefix:string}} + */ + const prefix = (n, baseMultiplier = 0) => { + const nPow = n === 0 ? 0 : log10(n); + let mult = 0; + while (nPow < mult * 3 && baseMultiplier > -8) { + baseMultiplier--; + mult--; + } + while (nPow >= 3 + mult * 3 && baseMultiplier < 8) { + baseMultiplier++; + mult++; + } + const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier]; + return { + n: round((mult > 0 ? n / exp10(mult * 3) : n * exp10(mult * -3)) * 1e12) / 1e12, + prefix + } + }; + + /** + * Utility module to work with time. + * + * @module time + */ + + /** + * Return current unix time. + * + * @return {number} + */ + const getUnixTime = Date.now; + + /** + * Transform time (in ms) to a human readable format. E.g. 1100 => 1.1s. 60s => 1min. .001 => 10μs. + * + * @param {number} d duration in milliseconds + * @return {string} humanized approximation of time + */ + const humanizeDuration = d => { + if (d < 60000) { + const p = prefix(d, -1); + return round(p.n * 100) / 100 + p.prefix + 's' + } + d = floor(d / 1000); + const seconds = d % 60; + const minutes = floor(d / 60) % 60; + const hours = floor(d / 3600) % 24; + const days = floor(d / 86400); + if (days > 0) { + return days + 'd' + ((hours > 0 || minutes > 30) ? ' ' + (minutes > 30 ? hours + 1 : hours) + 'h' : '') + } + if (hours > 0) { + /* istanbul ignore next */ + return hours + 'h' + ((minutes > 0 || seconds > 30) ? ' ' + (seconds > 30 ? minutes + 1 : minutes) + 'min' : '') + } + return minutes + 'min' + (seconds > 0 ? ' ' + seconds + 's' : '') + }; + + /** + * Utility helpers to work with promises. + * + * @module promise + */ + + /** + * @template T + * @callback PromiseResolve + * @param {T|PromiseLike} [result] + */ + + /** + * @template T + * @param {function(PromiseResolve,function(Error):void):any} f + * @return {Promise} + */ + const create$3 = f => /** @type {Promise} */ (new Promise(f)); + + /** + * @template T + * @param {T|void} res + * @return {Promise} + */ + const resolve = res => Promise.resolve(res); + + /** + * Checks if an object is a promise using ducktyping. + * + * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this + * library has some insane environment where global Promise objects are overwritten. + * + * @param {any} p + * @return {boolean} + */ + const isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally); + + /** + * Utility module to work with EcmaScript Symbols. + * + * @module symbol + */ + + /** + * Return fresh symbol. + * + * @return {Symbol} + */ + const create$2 = Symbol; + + /** + * Working with value pairs. + * + * @module pair + */ + + /** + * @template L,R + */ + class Pair { + /** + * @param {L} left + * @param {R} right + */ + constructor (left, right) { + this.left = left; + this.right = right; + } + } + + /** + * @template L,R + * @param {L} left + * @param {R} right + * @return {Pair} + */ + const create$1 = (left, right) => new Pair(left, right); + + /** + * @template L,R + * @param {Array>} arr + * @param {function(L, R):any} f + */ + const forEach = (arr, f) => arr.forEach(p => f(p.left, p.right)); + + /* eslint-env browser */ + + /* istanbul ignore next */ + /** + * @type {Document} + */ + const doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {}); + + /** + * @param {string} name + * @return {HTMLElement} + */ + /* istanbul ignore next */ + const createElement = name => doc.createElement(name); + + /** + * @return {DocumentFragment} + */ + /* istanbul ignore next */ + const createDocumentFragment = () => doc.createDocumentFragment(); + + /** + * @param {string} text + * @return {Text} + */ + /* istanbul ignore next */ + const createTextNode = text => doc.createTextNode(text); + + /* istanbul ignore next */ + /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null); + + /** + * @param {Element} el + * @param {Array>} attrs Array of key-value pairs + * @return {Element} + */ + /* istanbul ignore next */ + const setAttributes = (el, attrs) => { + forEach(attrs, (key, value) => { + if (value === false) { + el.removeAttribute(key); + } else if (value === true) { + el.setAttribute(key, ''); + } else { + // @ts-ignore + el.setAttribute(key, value); + } + }); + return el + }; + + /** + * @param {Array|HTMLCollection} children + * @return {DocumentFragment} + */ + /* istanbul ignore next */ + const fragment = children => { + const fragment = createDocumentFragment(); + for (let i = 0; i < children.length; i++) { + appendChild(fragment, children[i]); + } + return fragment + }; + + /** + * @param {Element} parent + * @param {Array} nodes + * @return {Element} + */ + /* istanbul ignore next */ + const append = (parent, nodes) => { + appendChild(parent, fragment(nodes)); + return parent + }; + + /** + * @param {EventTarget} el + * @param {string} name + * @param {EventListener} f + */ + /* istanbul ignore next */ + const addEventListener = (el, name, f) => el.addEventListener(name, f); + + /** + * @param {string} name + * @param {Array|pair.Pair>} attrs Array of key-value pairs + * @param {Array} children + * @return {Element} + */ + /* istanbul ignore next */ + const element = (name, attrs = [], children = []) => + append(setAttributes(createElement(name), attrs), children); + + /** + * @param {string} t + * @return {Text} + */ + /* istanbul ignore next */ + const text = createTextNode; + + /** + * @param {Map} m + * @return {string} + */ + /* istanbul ignore next */ + const mapToStyleString = m => map$1(m, (value, key) => `${key}:${value};`).join(''); + + /** + * @param {Node} parent + * @param {Node} child + * @return {Node} + */ + /* istanbul ignore next */ + const appendChild = (parent, child) => parent.appendChild(child); + + doc.ELEMENT_NODE; + doc.TEXT_NODE; + doc.CDATA_SECTION_NODE; + doc.COMMENT_NODE; + doc.DOCUMENT_NODE; + doc.DOCUMENT_TYPE_NODE; + doc.DOCUMENT_FRAGMENT_NODE; + + /** + * JSON utility functions. + * + * @module json + */ + + /** + * Transform JavaScript object to JSON. + * + * @param {any} object + * @return {string} + */ + const stringify = JSON.stringify; + + /* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */ + + /** + * Utility module to work with EcmaScript's event loop. + * + * @module eventloop + */ + + /** + * @type {Array} + */ + let queue$1 = []; + + const _runQueue = () => { + for (let i = 0; i < queue$1.length; i++) { + queue$1[i](); + } + queue$1 = []; + }; + + /** + * @param {function():void} f + */ + const enqueue = f => { + queue$1.push(f); + if (queue$1.length === 1) { + setTimeout(_runQueue, 0); + } + }; + + /** + * Isomorphic logging module with support for colors! + * + * @module logging + */ + + const BOLD = create$2(); + const UNBOLD = create$2(); + const BLUE = create$2(); + const GREY = create$2(); + const GREEN = create$2(); + const RED = create$2(); + const PURPLE = create$2(); + const ORANGE = create$2(); + const UNCOLOR = create$2(); + + /** + * @type {Object>} + */ + const _browserStyleMap = { + [BOLD]: create$1('font-weight', 'bold'), + [UNBOLD]: create$1('font-weight', 'normal'), + [BLUE]: create$1('color', 'blue'), + [GREEN]: create$1('color', 'green'), + [GREY]: create$1('color', 'grey'), + [RED]: create$1('color', 'red'), + [PURPLE]: create$1('color', 'purple'), + [ORANGE]: create$1('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate + [UNCOLOR]: create$1('color', 'black') + }; + + const _nodeStyleMap = { + [BOLD]: '\u001b[1m', + [UNBOLD]: '\u001b[2m', + [BLUE]: '\x1b[34m', + [GREEN]: '\x1b[32m', + [GREY]: '\u001b[37m', + [RED]: '\x1b[31m', + [PURPLE]: '\x1b[35m', + [ORANGE]: '\x1b[38;5;208m', + [UNCOLOR]: '\x1b[0m' + }; + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const computeBrowserLoggingArgs = (args) => { + const strBuilder = []; + const styles = []; + const currentStyle = create$6(); + /** + * @type {Array} + */ + let logArgs = []; + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg.constructor === String || arg.constructor === Number) { + const style = mapToStyleString(currentStyle); + if (i > 0 || style.length > 0) { + strBuilder.push('%c' + arg); + styles.push(style); + } else { + strBuilder.push(arg); + } + } else { + break + } + } + } + + if (i > 0) { + // create logArgs with what we have so far + logArgs = styles; + logArgs.unshift(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs + }; + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const computeNoColorLoggingArgs = args => { + const strBuilder = []; + const logArgs = []; + + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _nodeStyleMap[arg]; + if (style === undefined) { + if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg); + } else { + break + } + } + } + if (i > 0) { + logArgs.push(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + /* istanbul ignore else */ + if (!(arg instanceof Symbol)) { + if (arg.constructor === Object) { + logArgs.push(JSON.stringify(arg)); + } else { + logArgs.push(arg); + } + } + } + return logArgs + }; + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const computeNodeLoggingArgs = (args) => { + const strBuilder = []; + const logArgs = []; + + // try with formatting until we find something unsupported + let i = 0; + + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _nodeStyleMap[arg]; + if (style !== undefined) { + strBuilder.push(style); + } else { + if (arg.constructor === String || arg.constructor === Number) { + strBuilder.push(arg); + } else { + break + } + } + } + if (i > 0) { + // create logArgs with what we have so far + strBuilder.push('\x1b[0m'); + logArgs.push(strBuilder.join('')); + } + // append the rest + for (; i < args.length; i++) { + const arg = args[i]; + /* istanbul ignore else */ + if (!(arg instanceof Symbol)) { + logArgs.push(arg); + } + } + return logArgs + }; + + /* istanbul ignore next */ + const computeLoggingArgs = supportsColor + ? (isNode ? computeNodeLoggingArgs : computeBrowserLoggingArgs) + : computeNoColorLoggingArgs; + + /** + * @param {Array} args + */ + const print = (...args) => { + console.log(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach((vc) => vc.print(args)); + }; + + /* istanbul ignore next */ + /** + * @param {Error} err + */ + const printError = (err) => { + console.error(err); + vconsoles.forEach((vc) => vc.printError(err)); + }; + + /* istanbul ignore next */ + /** + * @param {string} url image location + * @param {number} height height of the image in pixel + */ + const printImg = (url, height) => { + if (isBrowser) { + console.log( + '%c ', + `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})` + ); + // console.log('%c ', `font-size: ${height}x; background: url(${url}) no-repeat;`) + } + vconsoles.forEach((vc) => vc.printImg(url, height)); + }; + + /* istanbul ignore next */ + /** + * @param {string} base64 + * @param {number} height + */ + const printImgBase64 = (base64, height) => + printImg(`data:image/gif;base64,${base64}`, height); + + /** + * @param {Array} args + */ + const group = (...args) => { + console.group(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach((vc) => vc.group(args)); + }; + + /** + * @param {Array} args + */ + const groupCollapsed = (...args) => { + console.groupCollapsed(...computeLoggingArgs(args)); + /* istanbul ignore next */ + vconsoles.forEach((vc) => vc.groupCollapsed(args)); + }; + + const groupEnd = () => { + console.groupEnd(); + /* istanbul ignore next */ + vconsoles.forEach((vc) => vc.groupEnd()); + }; + + const vconsoles = new Set(); + + /* istanbul ignore next */ + /** + * @param {Array} args + * @return {Array} + */ + const _computeLineSpans = (args) => { + const spans = []; + const currentStyle = new Map(); + // try with formatting until we find something unsupported + let i = 0; + for (; i < args.length; i++) { + const arg = args[i]; + // @ts-ignore + const style = _browserStyleMap[arg]; + if (style !== undefined) { + currentStyle.set(style.left, style.right); + } else { + if (arg.constructor === String || arg.constructor === Number) { + // @ts-ignore + const span = element('span', [ + create$1('style', mapToStyleString(currentStyle)) + ], [text(arg.toString())]); + if (span.innerHTML === '') { + span.innerHTML = ' '; + } + spans.push(span); + } else { + break + } + } + } + // append the rest + for (; i < args.length; i++) { + let content = args[i]; + if (!(content instanceof Symbol)) { + if (content.constructor !== String && content.constructor !== Number) { + content = ' ' + stringify(content) + ' '; + } + spans.push( + element('span', [], [text(/** @type {string} */ (content))]) + ); + } + } + return spans + }; + + const lineStyle = + 'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'; + + /* istanbul ignore next */ + class VConsole { + /** + * @param {Element} dom + */ + constructor (dom) { + this.dom = dom; + /** + * @type {Element} + */ + this.ccontainer = this.dom; + this.depth = 0; + vconsoles.add(this); + } + + /** + * @param {Array} args + * @param {boolean} collapsed + */ + group (args, collapsed = false) { + enqueue(() => { + const triangleDown = element('span', [ + create$1('hidden', collapsed), + create$1('style', 'color:grey;font-size:120%;') + ], [text('▼')]); + const triangleRight = element('span', [ + create$1('hidden', !collapsed), + create$1('style', 'color:grey;font-size:125%;') + ], [text('▶')]); + const content = element( + 'div', + [create$1( + 'style', + `${lineStyle};padding-left:${this.depth * 10}px` + )], + [triangleDown, triangleRight, text(' ')].concat( + _computeLineSpans(args) + ) + ); + const nextContainer = element('div', [ + create$1('hidden', collapsed) + ]); + const nextLine = element('div', [], [content, nextContainer]); + append(this.ccontainer, [nextLine]); + this.ccontainer = nextContainer; + this.depth++; + // when header is clicked, collapse/uncollapse container + addEventListener(content, 'click', (_event) => { + nextContainer.toggleAttribute('hidden'); + triangleDown.toggleAttribute('hidden'); + triangleRight.toggleAttribute('hidden'); + }); + }); + } + + /** + * @param {Array} args + */ + groupCollapsed (args) { + this.group(args, true); + } + + groupEnd () { + enqueue(() => { + if (this.depth > 0) { + this.depth--; + // @ts-ignore + this.ccontainer = this.ccontainer.parentElement.parentElement; + } + }); + } + + /** + * @param {Array} args + */ + print (args) { + enqueue(() => { + append(this.ccontainer, [ + element('div', [ + create$1( + 'style', + `${lineStyle};padding-left:${this.depth * 10}px` + ) + ], _computeLineSpans(args)) + ]); + }); + } + + /** + * @param {Error} err + */ + printError (err) { + this.print([RED, BOLD, err.toString()]); + } + + /** + * @param {string} url + * @param {number} height + */ + printImg (url, height) { + enqueue(() => { + append(this.ccontainer, [ + element('img', [ + create$1('src', url), + create$1('height', `${round(height * 1.5)}px`) + ]) + ]); + }); + } + + /** + * @param {Node} node + */ + printDom (node) { + enqueue(() => { + append(this.ccontainer, [node]); + }); + } + + destroy () { + enqueue(() => { + vconsoles.delete(this); + }); + } + } + + /* istanbul ignore next */ + /** + * @param {Element} dom + */ + const createVConsole = (dom) => new VConsole(dom); + + /** + * Utility module to create and manipulate Iterators. + * + * @module iterator + */ + + /** + * @template T + * @param {function():IteratorResult} next + * @return {IterableIterator} + */ + const createIterator = next => ({ + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this + }, + // @ts-ignore + next + }); + + /** + * @template T + * @param {Iterator} iterator + * @param {function(T):boolean} filter + */ + const iteratorFilter = (iterator, filter) => createIterator(() => { + let res; + do { + res = iterator.next(); + } while (!res.done && !filter(res.value)) + return res + }); + + /** + * @template T,M + * @param {Iterator} iterator + * @param {function(T):M} fmap + */ + const iteratorMap = (iterator, fmap) => createIterator(() => { + const { done, value } = iterator.next(); + return { done, value: done ? undefined : fmap(value) } + }); + + /** + * This is an abstract interface that all Connectors should implement to keep them interchangeable. + * + * @note This interface is experimental and it is not advised to actually inherit this class. + * It just serves as typing information. + * + * @extends {Observable} + */ + class AbstractConnector extends Observable { + /** + * @param {Doc} ydoc + * @param {any} awareness + */ + constructor (ydoc, awareness) { + super(); + this.doc = ydoc; + this.awareness = awareness; + } + } + + class DeleteItem { + /** + * @param {number} clock + * @param {number} len + */ + constructor (clock, len) { + /** + * @type {number} + */ + this.clock = clock; + /** + * @type {number} + */ + this.len = len; + } + } + + /** + * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed. + * - When created in a transaction, it must only be accessed after sorting, and merging + * - This DeleteSet is send to other clients + * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore + * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged. + */ + class DeleteSet { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + } + } + + /** + * Iterate over all structs that the DeleteSet gc's. + * + * @param {Transaction} transaction + * @param {DeleteSet} ds + * @param {function(GC|Item):void} f + * + * @function + */ + const iterateDeletedStructs = (transaction, ds, f) => + ds.clients.forEach((deletes, clientid) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid)); + for (let i = 0; i < deletes.length; i++) { + const del = deletes[i]; + iterateStructs(transaction, structs, del.clock, del.len, f); + } + }); + + /** + * @param {Array} dis + * @param {number} clock + * @return {number|null} + * + * @private + * @function + */ + const findIndexDS = (dis, clock) => { + let left = 0; + let right = dis.length - 1; + while (left <= right) { + const midindex = floor((left + right) / 2); + const mid = dis[midindex]; + const midclock = mid.clock; + if (midclock <= clock) { + if (clock < midclock + mid.len) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + } + return null + }; + + /** + * @param {DeleteSet} ds + * @param {ID} id + * @return {boolean} + * + * @private + * @function + */ + const isDeleted = (ds, id) => { + const dis = ds.clients.get(id.client); + return dis !== undefined && findIndexDS(dis, id.clock) !== null + }; + + /** + * @param {DeleteSet} ds + * + * @private + * @function + */ + const sortAndMergeDeleteSet = ds => { + ds.clients.forEach(dels => { + dels.sort((a, b) => a.clock - b.clock); + // merge items without filtering or splicing the array + // i is the current pointer + // j refers to the current insert position for the pointed item + // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i] + let i, j; + for (i = 1, j = 1; i < dels.length; i++) { + const left = dels[j - 1]; + const right = dels[i]; + if (left.clock + left.len >= right.clock) { + left.len = max(left.len, right.clock + right.len - left.clock); + } else { + if (j < i) { + dels[j] = right; + } + j++; + } + } + dels.length = j; + }); + }; + + /** + * @param {Array} dss + * @return {DeleteSet} A fresh DeleteSet + */ + const mergeDeleteSets = dss => { + const merged = new DeleteSet(); + for (let dssI = 0; dssI < dss.length; dssI++) { + dss[dssI].clients.forEach((delsLeft, client) => { + if (!merged.clients.has(client)) { + // Write all missing keys from current ds and all following. + // If merged already contains `client` current ds has already been added. + /** + * @type {Array} + */ + const dels = delsLeft.slice(); + for (let i = dssI + 1; i < dss.length; i++) { + appendTo(dels, dss[i].clients.get(client) || []); + } + merged.clients.set(client, dels); + } + }); + } + sortAndMergeDeleteSet(merged); + return merged + }; + + /** + * @param {DeleteSet} ds + * @param {number} client + * @param {number} clock + * @param {number} length + * + * @private + * @function + */ + const addToDeleteSet = (ds, client, clock, length) => { + setIfUndefined(ds.clients, client, () => []).push(new DeleteItem(clock, length)); + }; + + const createDeleteSet = () => new DeleteSet(); + + /** + * @param {StructStore} ss + * @return {DeleteSet} Merged and sorted DeleteSet + * + * @private + * @function + */ + const createDeleteSetFromStructStore = ss => { + const ds = createDeleteSet(); + ss.clients.forEach((structs, client) => { + /** + * @type {Array} + */ + const dsitems = []; + for (let i = 0; i < structs.length; i++) { + const struct = structs[i]; + if (struct.deleted) { + const clock = struct.id.clock; + let len = struct.length; + if (i + 1 < structs.length) { + for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) { + len += next.length; + } + } + dsitems.push(new DeleteItem(clock, len)); + } + } + if (dsitems.length > 0) { + ds.clients.set(client, dsitems); + } + }); + return ds + }; + + /** + * @param {DSEncoderV1 | DSEncoderV2} encoder + * @param {DeleteSet} ds + * + * @private + * @function + */ + const writeDeleteSet = (encoder, ds) => { + writeVarUint(encoder.restEncoder, ds.clients.size); + ds.clients.forEach((dsitems, client) => { + encoder.resetDsCurVal(); + writeVarUint(encoder.restEncoder, client); + const len = dsitems.length; + writeVarUint(encoder.restEncoder, len); + for (let i = 0; i < len; i++) { + const item = dsitems[i]; + encoder.writeDsClock(item.clock); + encoder.writeDsLen(item.len); + } + }); + }; + + /** + * @param {DSDecoderV1 | DSDecoderV2} decoder + * @return {DeleteSet} + * + * @private + * @function + */ + const readDeleteSet = decoder => { + const ds = new DeleteSet(); + const numClients = readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = readVarUint(decoder.restDecoder); + const numberOfDeletes = readVarUint(decoder.restDecoder); + if (numberOfDeletes > 0) { + const dsField = setIfUndefined(ds.clients, client, () => []); + for (let i = 0; i < numberOfDeletes; i++) { + dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); + } + } + } + return ds + }; + + /** + * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array().. + */ + + /** + * @param {DSDecoderV1 | DSDecoderV2} decoder + * @param {Transaction} transaction + * @param {StructStore} store + * @return {Uint8Array|null} Returns a v2 update containing all deletes that couldn't be applied yet; or null if all deletes were applied successfully. + * + * @private + * @function + */ + const readAndApplyDeleteSet = (decoder, transaction, store) => { + const unappliedDS = new DeleteSet(); + const numClients = readVarUint(decoder.restDecoder); + for (let i = 0; i < numClients; i++) { + decoder.resetDsCurVal(); + const client = readVarUint(decoder.restDecoder); + const numberOfDeletes = readVarUint(decoder.restDecoder); + const structs = store.clients.get(client) || []; + const state = getState(store, client); + for (let i = 0; i < numberOfDeletes; i++) { + const clock = decoder.readDsClock(); + const clockEnd = clock + decoder.readDsLen(); + if (clock < state) { + if (state < clockEnd) { + addToDeleteSet(unappliedDS, client, state, clockEnd - state); + } + let index = findIndexSS(structs, clock); + /** + * We can ignore the case of GC and Delete structs, because we are going to skip them + * @type {Item} + */ + // @ts-ignore + let struct = structs[index]; + // split the first item if necessary + if (!struct.deleted && struct.id.clock < clock) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + index++; // increase we now want to use the next struct + } + while (index < structs.length) { + // @ts-ignore + struct = structs[index++]; + if (struct.id.clock < clockEnd) { + if (!struct.deleted) { + if (clockEnd < struct.id.clock + struct.length) { + structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); + } + struct.delete(transaction); + } + } else { + break + } + } + } else { + addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); + } + } + } + if (unappliedDS.clients.size > 0) { + const ds = new UpdateEncoderV2(); + writeVarUint(ds.restEncoder, 0); // encode 0 structs + writeDeleteSet(ds, unappliedDS); + return ds.toUint8Array() + } + return null + }; + + /** + * @module Y + */ + + const generateNewClientId = uint32; + + /** + * @typedef {Object} DocOpts + * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true) + * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item. + * @property {string} [DocOpts.guid] Define a globally unique identifier for this document + * @property {string | null} [DocOpts.collectionid] Associate this document with a collection. This only plays a role if your provider has a concept of collection. + * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well. + * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically. + * @property {boolean} [DocOpts.shouldLoad] Whether the document should be synced by the provider now. This is toggled to true when you call ydoc.load() + */ + + /** + * A Yjs instance handles the state of shared data. + * @extends Observable + */ + class Doc extends Observable { + /** + * @param {DocOpts} [opts] configuration + */ + constructor ({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) { + super(); + this.gc = gc; + this.gcFilter = gcFilter; + this.clientID = generateNewClientId(); + this.guid = guid; + this.collectionid = collectionid; + /** + * @type {Map>>} + */ + this.share = new Map(); + this.store = new StructStore(); + /** + * @type {Transaction | null} + */ + this._transaction = null; + /** + * @type {Array} + */ + this._transactionCleanups = []; + /** + * @type {Set} + */ + this.subdocs = new Set(); + /** + * If this document is a subdocument - a document integrated into another document - then _item is defined. + * @type {Item?} + */ + this._item = null; + this.shouldLoad = shouldLoad; + this.autoLoad = autoLoad; + this.meta = meta; + this.isLoaded = false; + this.whenLoaded = create$3(resolve => { + this.on('load', () => { + this.isLoaded = true; + resolve(this); + }); + }); + } + + /** + * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). + * + * `load()` might be used in the future to request any provider to load the most current data. + * + * It is safe to call `load()` multiple times. + */ + load () { + const item = this._item; + if (item !== null && !this.shouldLoad) { + transact(/** @type {any} */ (item.parent).doc, transaction => { + transaction.subdocsLoaded.add(this); + }, null, true); + } + this.shouldLoad = true; + } + + getSubdocs () { + return this.subdocs + } + + getSubdocGuids () { + return new Set(Array.from(this.subdocs).map(doc => doc.guid)) + } + + /** + * Changes that happen inside of a transaction are bundled. This means that + * the observer fires _after_ the transaction is finished and that all changes + * that happened inside of the transaction are sent as one message to the + * other peers. + * + * @param {function(Transaction):void} f The function that should be executed as a transaction + * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin + * + * @public + */ + transact (f, origin = null) { + transact(this, f, origin); + } + + /** + * Define a shared data type. + * + * Multiple calls of `y.get(name, TypeConstructor)` yield the same result + * and do not overwrite each other. I.e. + * `y.define(name, Y.Array) === y.define(name, Y.Array)` + * + * After this method is called, the type is also available on `y.share.get(name)`. + * + * *Best Practices:* + * Define all types right after the Yjs instance is created and store them in a separate object. + * Also use the typed methods `getText(name)`, `getArray(name)`, .. + * + * @example + * const y = new Y(..) + * const appState = { + * document: y.getText('document') + * comments: y.getArray('comments') + * } + * + * @param {string} name + * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... + * @return {AbstractType} The created type. Constructed with TypeConstructor + * + * @public + */ + get (name, TypeConstructor = AbstractType) { + const type = setIfUndefined(this.share, name, () => { + // @ts-ignore + const t = new TypeConstructor(); + t._integrate(this, null); + return t + }); + const Constr = type.constructor; + if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { + if (Constr === AbstractType) { + // @ts-ignore + const t = new TypeConstructor(); + t._map = type._map; + type._map.forEach(/** @param {Item?} n */ n => { + for (; n !== null; n = n.left) { + // @ts-ignore + n.parent = t; + } + }); + t._start = type._start; + for (let n = t._start; n !== null; n = n.right) { + n.parent = t; + } + t._length = type._length; + this.share.set(name, t); + t._integrate(this, null); + return t + } else { + throw new Error(`Type with the name ${name} has already been defined with a different constructor`) + } + } + return type + } + + /** + * @template T + * @param {string} [name] + * @return {YArray} + * + * @public + */ + getArray (name = '') { + // @ts-ignore + return this.get(name, YArray) + } + + /** + * @param {string} [name] + * @return {YText} + * + * @public + */ + getText (name = '') { + // @ts-ignore + return this.get(name, YText) + } + + /** + * @template T + * @param {string} [name] + * @return {YMap} + * + * @public + */ + getMap (name = '') { + // @ts-ignore + return this.get(name, YMap) + } + + /** + * @param {string} [name] + * @return {YXmlFragment} + * + * @public + */ + getXmlFragment (name = '') { + // @ts-ignore + return this.get(name, YXmlFragment) + } + + /** + * Converts the entire document into a js object, recursively traversing each yjs type + * Doesn't log types that have not been defined (using ydoc.getType(..)). + * + * @deprecated Do not use this method and rather call toJSON directly on the shared types. + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const doc = {}; + + this.share.forEach((value, key) => { + doc[key] = value.toJSON(); + }); + + return doc + } + + /** + * Emit `destroy` event and unregister all event handlers. + */ + destroy () { + from$1(this.subdocs).forEach(subdoc => subdoc.destroy()); + const item = this._item; + if (item !== null) { + this._item = null; + const content = /** @type {ContentDoc} */ (item.content); + content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false }); + content.doc._item = item; + transact(/** @type {any} */ (item).parent.doc, transaction => { + const doc = content.doc; + if (!item.deleted) { + transaction.subdocsAdded.add(doc); + } + transaction.subdocsRemoved.add(this); + }, null, true); + } + this.emit('destroyed', [true]); + this.emit('destroy', [this]); + super.destroy(); + } + + /** + * @param {string} eventName + * @param {function(...any):any} f + */ + on (eventName, f) { + super.on(eventName, f); + } + + /** + * @param {string} eventName + * @param {function} f + */ + off (eventName, f) { + super.off(eventName, f); + } + } + + class DSDecoderV1 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + this.restDecoder = decoder; + } + + resetDsCurVal () { + // nop + } + + /** + * @return {number} + */ + readDsClock () { + return readVarUint(this.restDecoder) + } + + /** + * @return {number} + */ + readDsLen () { + return readVarUint(this.restDecoder) + } + } + + class UpdateDecoderV1 extends DSDecoderV1 { + /** + * @return {ID} + */ + readLeftID () { + return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)) + } + + /** + * @return {ID} + */ + readRightID () { + return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return readVarUint(this.restDecoder) + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return readUint8(this.restDecoder) + } + + /** + * @return {string} + */ + readString () { + return readVarString(this.restDecoder) + } + + /** + * @return {boolean} isKey + */ + readParentInfo () { + return readVarUint(this.restDecoder) === 1 + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readTypeRef () { + return readVarUint(this.restDecoder) + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} len + */ + readLen () { + return readVarUint(this.restDecoder) + } + + /** + * @return {any} + */ + readAny () { + return readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return copyUint8Array(readVarUint8Array(this.restDecoder)) + } + + /** + * Legacy implementation uses JSON parse. We use any-decoding in v2. + * + * @return {any} + */ + readJSON () { + return JSON.parse(readVarString(this.restDecoder)) + } + + /** + * @return {string} + */ + readKey () { + return readVarString(this.restDecoder) + } + } + + class DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + /** + * @private + */ + this.dsCurrVal = 0; + this.restDecoder = decoder; + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + /** + * @return {number} + */ + readDsClock () { + this.dsCurrVal += readVarUint(this.restDecoder); + return this.dsCurrVal + } + + /** + * @return {number} + */ + readDsLen () { + const diff = readVarUint(this.restDecoder) + 1; + this.dsCurrVal += diff; + return diff + } + } + + class UpdateDecoderV2 extends DSDecoderV2 { + /** + * @param {decoding.Decoder} decoder + */ + constructor (decoder) { + super(decoder); + /** + * List of cached keys. If the keys[id] does not exist, we read a new key + * from stringEncoder and push it to keys. + * + * @type {Array} + */ + this.keys = []; + readVarUint(decoder); // read feature flag - currently unused + this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); + this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); + this.stringDecoder = new StringDecoder$2(readVarUint8Array(decoder)); + this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); + this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); + } + + /** + * @return {ID} + */ + readLeftID () { + return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()) + } + + /** + * @return {ID} + */ + readRightID () { + return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()) + } + + /** + * Read the next client id. + * Use this in favor of readID whenever possible to reduce the number of objects created. + */ + readClient () { + return this.clientDecoder.read() + } + + /** + * @return {number} info An unsigned 8-bit integer + */ + readInfo () { + return /** @type {number} */ (this.infoDecoder.read()) + } + + /** + * @return {string} + */ + readString () { + return this.stringDecoder.read() + } + + /** + * @return {boolean} + */ + readParentInfo () { + return this.parentInfoDecoder.read() === 1 + } + + /** + * @return {number} An unsigned 8-bit integer + */ + readTypeRef () { + return this.typeRefDecoder.read() + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @return {number} + */ + readLen () { + return this.lenDecoder.read() + } + + /** + * @return {any} + */ + readAny () { + return readAny(this.restDecoder) + } + + /** + * @return {Uint8Array} + */ + readBuf () { + return readVarUint8Array(this.restDecoder) + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @return {any} + */ + readJSON () { + return readAny(this.restDecoder) + } + + /** + * @return {string} + */ + readKey () { + const keyClock = this.keyClockDecoder.read(); + if (keyClock < this.keys.length) { + return this.keys[keyClock] + } else { + const key = this.stringDecoder.read(); + this.keys.push(key); + return key + } + } + } + + class DSEncoderV1 { + constructor () { + this.restEncoder = createEncoder(); + } + + toUint8Array () { + return toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + // nop + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + writeVarUint(this.restEncoder, clock); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + writeVarUint(this.restEncoder, len); + } + } + + class UpdateEncoderV1 extends DSEncoderV1 { + /** + * @param {ID} id + */ + writeLeftID (id) { + writeVarUint(this.restEncoder, id.client); + writeVarUint(this.restEncoder, id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + writeVarUint(this.restEncoder, id.client); + writeVarUint(this.restEncoder, id.clock); + } + + /** + * Use writeClient and writeClock instead of writeID if possible. + * @param {number} client + */ + writeClient (client) { + writeVarUint(this.restEncoder, client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + writeUint8(this.restEncoder, info); + } + + /** + * @param {string} s + */ + writeString (s) { + writeVarString(this.restEncoder, s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + writeVarUint(this.restEncoder, isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + writeVarUint(this.restEncoder, info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + writeVarUint(this.restEncoder, len); + } + + /** + * @param {any} any + */ + writeAny (any) { + writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + writeVarUint8Array(this.restEncoder, buf); + } + + /** + * @param {any} embed + */ + writeJSON (embed) { + writeVarString(this.restEncoder, JSON.stringify(embed)); + } + + /** + * @param {string} key + */ + writeKey (key) { + writeVarString(this.restEncoder, key); + } + } + + class DSEncoderV2 { + constructor () { + this.restEncoder = createEncoder(); // encodes all the rest / non-optimized + this.dsCurrVal = 0; + } + + toUint8Array () { + return toUint8Array(this.restEncoder) + } + + resetDsCurVal () { + this.dsCurrVal = 0; + } + + /** + * @param {number} clock + */ + writeDsClock (clock) { + const diff = clock - this.dsCurrVal; + this.dsCurrVal = clock; + writeVarUint(this.restEncoder, diff); + } + + /** + * @param {number} len + */ + writeDsLen (len) { + if (len === 0) { + unexpectedCase(); + } + writeVarUint(this.restEncoder, len - 1); + this.dsCurrVal += len; + } + } + + class UpdateEncoderV2 extends DSEncoderV2 { + constructor () { + super(); + /** + * @type {Map} + */ + this.keyMap = new Map(); + /** + * Refers to the next uniqe key-identifier to me used. + * See writeKey method for more information. + * + * @type {number} + */ + this.keyClock = 0; + this.keyClockEncoder = new IntDiffOptRleEncoder(); + this.clientEncoder = new UintOptRleEncoder(); + this.leftClockEncoder = new IntDiffOptRleEncoder(); + this.rightClockEncoder = new IntDiffOptRleEncoder(); + this.infoEncoder = new RleEncoder(writeUint8); + this.stringEncoder = new StringEncoder(); + this.parentInfoEncoder = new RleEncoder(writeUint8); + this.typeRefEncoder = new UintOptRleEncoder(); + this.lenEncoder = new UintOptRleEncoder(); + } + + toUint8Array () { + const encoder = createEncoder(); + writeVarUint(encoder, 0); // this is a feature flag that we might use in the future + writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); + writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); + writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); + writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); + writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); + writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); + // @note The rest encoder is appended! (note the missing var) + writeUint8Array(encoder, toUint8Array(this.restEncoder)); + return toUint8Array(encoder) + } + + /** + * @param {ID} id + */ + writeLeftID (id) { + this.clientEncoder.write(id.client); + this.leftClockEncoder.write(id.clock); + } + + /** + * @param {ID} id + */ + writeRightID (id) { + this.clientEncoder.write(id.client); + this.rightClockEncoder.write(id.clock); + } + + /** + * @param {number} client + */ + writeClient (client) { + this.clientEncoder.write(client); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeInfo (info) { + this.infoEncoder.write(info); + } + + /** + * @param {string} s + */ + writeString (s) { + this.stringEncoder.write(s); + } + + /** + * @param {boolean} isYKey + */ + writeParentInfo (isYKey) { + this.parentInfoEncoder.write(isYKey ? 1 : 0); + } + + /** + * @param {number} info An unsigned 8-bit integer + */ + writeTypeRef (info) { + this.typeRefEncoder.write(info); + } + + /** + * Write len of a struct - well suited for Opt RLE encoder. + * + * @param {number} len + */ + writeLen (len) { + this.lenEncoder.write(len); + } + + /** + * @param {any} any + */ + writeAny (any) { + writeAny(this.restEncoder, any); + } + + /** + * @param {Uint8Array} buf + */ + writeBuf (buf) { + writeVarUint8Array(this.restEncoder, buf); + } + + /** + * This is mainly here for legacy purposes. + * + * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. + * + * @param {any} embed + */ + writeJSON (embed) { + writeAny(this.restEncoder, embed); + } + + /** + * Property keys are often reused. For example, in y-prosemirror the key `bold` might + * occur very often. For a 3d application, the key `position` might occur very often. + * + * We cache these keys in a Map and refer to them via a unique number. + * + * @param {string} key + */ + writeKey (key) { + const clock = this.keyMap.get(key); + if (clock === undefined) { + /** + * @todo uncomment to introduce this feature finally + * + * Background. The ContentFormat object was always encoded using writeKey, but the decoder used to use readString. + * Furthermore, I forgot to set the keyclock. So everything was working fine. + * + * However, this feature here is basically useless as it is not being used (it actually only consumes extra memory). + * + * I don't know yet how to reintroduce this feature.. + * + * Older clients won't be able to read updates when we reintroduce this feature. So this should probably be done using a flag. + * + */ + // this.keyMap.set(key, this.keyClock) + this.keyClockEncoder.write(this.keyClock++); + this.stringEncoder.write(key); + } else { + this.keyClockEncoder.write(clock); + } + } + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {Array} structs All structs by `client` + * @param {number} client + * @param {number} clock write structs starting with `ID(client,clock)` + * + * @function + */ + const writeStructs = (encoder, structs, client, clock) => { + // write first id + clock = max(clock, structs[0].id.clock); // make sure the first id exists + const startNewStructs = findIndexSS(structs, clock); + // write # encoded structs + writeVarUint(encoder.restEncoder, structs.length - startNewStructs); + encoder.writeClient(client); + writeVarUint(encoder.restEncoder, clock); + const firstStruct = structs[startNewStructs]; + // write first struct with an offset + firstStruct.write(encoder, clock - firstStruct.id.clock); + for (let i = startNewStructs + 1; i < structs.length; i++) { + structs[i].write(encoder, 0); + } + }; + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {StructStore} store + * @param {Map} _sm + * + * @private + * @function + */ + const writeClientsStructs = (encoder, store, _sm) => { + // we filter all valid _sm entries into sm + const sm = new Map(); + _sm.forEach((clock, client) => { + // only write if new structs are available + if (getState(store, client) > clock) { + sm.set(client, clock); + } + }); + getStateVector(store).forEach((clock, client) => { + if (!_sm.has(client)) { + sm.set(client, 0); + } + }); + // write # states that were updated + writeVarUint(encoder.restEncoder, sm.size); + // Write items with higher client ids first + // This heavily improves the conflict algorithm. + Array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { + // @ts-ignore + writeStructs(encoder, store.clients.get(client), client, clock); + }); + }; + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder The decoder object to read data from. + * @param {Doc} doc + * @return {Map }>} + * + * @private + * @function + */ + const readClientsStructRefs = (decoder, doc) => { + /** + * @type {Map }>} + */ + const clientRefs = create$6(); + const numOfStateUpdates = readVarUint(decoder.restDecoder); + for (let i = 0; i < numOfStateUpdates; i++) { + const numberOfStructs = readVarUint(decoder.restDecoder); + /** + * @type {Array} + */ + const refs = new Array(numberOfStructs); + const client = decoder.readClient(); + let clock = readVarUint(decoder.restDecoder); + // const start = performance.now() + clientRefs.set(client, { i: 0, refs }); + for (let i = 0; i < numberOfStructs; i++) { + const info = decoder.readInfo(); + switch (BITS5 & info) { + case 0: { // GC + const len = decoder.readLen(); + refs[i] = new GC(createID(client, clock), len); + clock += len; + break + } + case 10: { // Skip Struct (nothing to apply) + // @todo we could reduce the amount of checks by adding Skip struct to clientRefs so we know that something is missing. + const len = readVarUint(decoder.restDecoder); + refs[i] = new Skip(createID(client, clock), len); + clock += len; + break + } + default: { // Item with content + /** + * The optimized implementation doesn't use any variables because inlining variables is faster. + * Below a non-optimized version is shown that implements the basic algorithm with + * a few comments + */ + const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const struct = new Item$1( + createID(client, clock), + null, // leftd + (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin + null, // right + (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin + cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent + cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ); + /* A non-optimized implementation of the above algorithm: + + // The item that was originally to the left of this item. + const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null + // The item that was originally to the right of this item. + const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null + const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0 + const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null + + const struct = new Item( + createID(client, clock), + null, // leftd + origin, // origin + null, // right + rightOrigin, // right origin + cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent + cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ) + */ + refs[i] = struct; + clock += struct.length; + } + } + } + // console.log('time to read: ', performance.now() - start) // @todo remove + } + return clientRefs + }; + + /** + * Resume computing structs generated by struct readers. + * + * While there is something to do, we integrate structs in this order + * 1. top element on stack, if stack is not empty + * 2. next element from current struct reader (if empty, use next struct reader) + * + * If struct causally depends on another struct (ref.missing), we put next reader of + * `ref.id.client` on top of stack. + * + * At some point we find a struct that has no causal dependencies, + * then we start emptying the stack. + * + * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2) + * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`. + * + * This method is implemented in a way so that we can resume computation if this update + * causally depends on another update. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @param {Map} clientsStructRefs + * @return { null | { update: Uint8Array, missing: Map } } + * + * @private + * @function + */ + const integrateStructs = (transaction, store, clientsStructRefs) => { + /** + * @type {Array} + */ + const stack = []; + // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user. + let clientsStructRefsIds = Array.from(clientsStructRefs.keys()).sort((a, b) => a - b); + if (clientsStructRefsIds.length === 0) { + return null + } + const getNextStructTarget = () => { + if (clientsStructRefsIds.length === 0) { + return null + } + let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + while (nextStructsTarget.refs.length === nextStructsTarget.i) { + clientsStructRefsIds.pop(); + if (clientsStructRefsIds.length > 0) { + nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])); + } else { + return null + } + } + return nextStructsTarget + }; + let curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null && stack.length === 0) { + return null + } + + /** + * @type {StructStore} + */ + const restStructs = new StructStore(); + const missingSV = new Map(); + /** + * @param {number} client + * @param {number} clock + */ + const updateMissingSv = (client, clock) => { + const mclock = missingSV.get(client); + if (mclock == null || mclock > clock) { + missingSV.set(client, clock); + } + }; + /** + * @type {GC|Item} + */ + let stackHead = /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++]; + // caching the state because it is used very often + const state = new Map(); + + const addStackToRestSS = () => { + for (const item of stack) { + const client = item.id.client; + const unapplicableItems = clientsStructRefs.get(client); + if (unapplicableItems) { + // decrement because we weren't able to apply previous operation + unapplicableItems.i--; + restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i)); + clientsStructRefs.delete(client); + unapplicableItems.i = 0; + unapplicableItems.refs = []; + } else { + // item was the last item on clientsStructRefs and the field was already cleared. Add item to restStructs and continue + restStructs.clients.set(client, [item]); + } + // remove client from clientsStructRefsIds to prevent users from applying the same update again + clientsStructRefsIds = clientsStructRefsIds.filter(c => c !== client); + } + stack.length = 0; + }; + + // iterate over all struct readers until we are done + while (true) { + if (stackHead.constructor !== Skip) { + const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client)); + const offset = localClock - stackHead.id.clock; + if (offset < 0) { + // update from the same client is missing + stack.push(stackHead); + updateMissingSv(stackHead.id.client, stackHead.id.clock - 1); + // hid a dead wall, add all items from stack to restSS + addStackToRestSS(); + } else { + const missing = stackHead.getMissing(transaction, store); + if (missing !== null) { + stack.push(stackHead); + // get the struct reader that has the missing struct + /** + * @type {{ refs: Array, i: number }} + */ + const structRefs = clientsStructRefs.get(/** @type {number} */ (missing)) || { refs: [], i: 0 }; + if (structRefs.refs.length === structRefs.i) { + // This update message causally depends on another update message that doesn't exist yet + updateMissingSv(/** @type {number} */ (missing), getState(store, missing)); + addStackToRestSS(); + } else { + stackHead = structRefs.refs[structRefs.i++]; + continue + } + } else if (offset === 0 || offset < stackHead.length) { + // all fine, apply the stackhead + stackHead.integrate(transaction, offset); + state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); + } + } + } + // iterate to next stackHead + if (stack.length > 0) { + stackHead = /** @type {GC|Item} */ (stack.pop()); + } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } else { + curStructsTarget = getNextStructTarget(); + if (curStructsTarget === null) { + // we are done! + break + } else { + stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]); + } + } + } + if (restStructs.clients.size > 0) { + const encoder = new UpdateEncoderV2(); + writeClientsStructs(encoder, restStructs, new Map()); + // write empty deleteset + // writeDeleteSet(encoder, new DeleteSet()) + writeVarUint(encoder.restEncoder, 0); // => no need for an extra function call, just write 0 deletes + return { missing: missingSV, update: encoder.toUint8Array() } + } + return null + }; + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {Transaction} transaction + * + * @private + * @function + */ + const writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); + + /** + * Read and apply a document update. + * + * This function has the same effect as `applyUpdate` but accepts an decoder. + * + * @param {decoding.Decoder} decoder + * @param {Doc} ydoc + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {UpdateDecoderV1 | UpdateDecoderV2} [structDecoder] + * + * @function + */ + const readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => + transact(ydoc, transaction => { + // force that transaction.local is set to non-local + transaction.local = false; + let retry = false; + const doc = transaction.doc; + const store = doc.store; + // let start = performance.now() + const ss = readClientsStructRefs(structDecoder, doc); + // console.log('time to read structs: ', performance.now() - start) // @todo remove + // start = performance.now() + // console.log('time to merge: ', performance.now() - start) // @todo remove + // start = performance.now() + const restStructs = integrateStructs(transaction, store, ss); + const pending = store.pendingStructs; + if (pending) { + // check if we can apply something + for (const [client, clock] of pending.missing) { + if (clock < getState(store, client)) { + retry = true; + break + } + } + if (restStructs) { + // merge restStructs into store.pending + for (const [client, clock] of restStructs.missing) { + const mclock = pending.missing.get(client); + if (mclock == null || mclock > clock) { + pending.missing.set(client, clock); + } + } + pending.update = mergeUpdatesV2([pending.update, restStructs.update]); + } + } else { + store.pendingStructs = restStructs; + } + // console.log('time to integrate: ', performance.now() - start) // @todo remove + // start = performance.now() + const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store); + if (store.pendingDs) { + // @todo we could make a lower-bound state-vector check as we do above + const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store.pendingDs)); + readVarUint(pendingDSUpdate.restDecoder); // read 0 structs, because we only encode deletes in pendingdsupdate + const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store); + if (dsRest && dsRest2) { + // case 1: ds1 != null && ds2 != null + store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]); + } else { + // case 2: ds1 != null + // case 3: ds2 != null + // case 4: ds1 == null && ds2 == null + store.pendingDs = dsRest || dsRest2; + } + } else { + // Either dsRest == null && pendingDs == null OR dsRest != null + store.pendingDs = dsRest; + } + // console.log('time to cleanup: ', performance.now() - start) // @todo remove + // start = performance.now() + + // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove + // start = performance.now() + if (retry) { + const update = /** @type {{update: Uint8Array}} */ (store.pendingStructs).update; + store.pendingStructs = null; + applyUpdateV2(transaction.doc, update); + } + }, transactionOrigin, false); + + /** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder] + * + * @function + */ + const applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { + const decoder = createDecoder(update); + readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); + }; + + /** + * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`. + * + * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder. + * + * @param {Doc} ydoc + * @param {Uint8Array} update + * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))` + * + * @function + */ + const applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1); + + /** + * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will + * only write the operations that are missing. + * + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {Doc} doc + * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * + * @function + */ + const writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => { + writeClientsStructs(encoder, doc.store, targetStateVector); + writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store)); + }; + + /** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @param {UpdateEncoderV1 | UpdateEncoderV2} [encoder] + * @return {Uint8Array} + * + * @function + */ + const encodeStateAsUpdateV2 = (doc, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => { + const targetStateVector = decodeStateVector$1(encodedTargetStateVector); + writeStateAsUpdate(encoder, doc, targetStateVector); + const updates = [encoder.toUint8Array()]; + // also add the pending updates (if there are any) + if (doc.store.pendingDs) { + updates.push(doc.store.pendingDs); + } + if (doc.store.pendingStructs) { + updates.push(diffUpdateV2(doc.store.pendingStructs.update, encodedTargetStateVector)); + } + if (updates.length > 1) { + if (encoder.constructor === UpdateEncoderV1) { + return mergeUpdates$1(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update))) + } else if (encoder.constructor === UpdateEncoderV2) { + return mergeUpdatesV2(updates) + } + } + return updates[0] + }; + + /** + * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will + * only write the operations that are missing. + * + * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder + * + * @param {Doc} doc + * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs + * @return {Uint8Array} + * + * @function + */ + const encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new UpdateEncoderV1()); + + /** + * Read state vector from Decoder and return as Map + * + * @param {DSDecoderV1 | DSDecoderV2} decoder + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const readStateVector$2 = decoder => { + const ss = new Map(); + const ssLength = readVarUint(decoder.restDecoder); + for (let i = 0; i < ssLength; i++) { + const client = readVarUint(decoder.restDecoder); + const clock = readVarUint(decoder.restDecoder); + ss.set(client, clock); + } + return ss + }; + + /** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + // export const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState))) + + /** + * Read decodedState and return State as Map. + * + * @param {Uint8Array} decodedState + * @return {Map} Maps `client` to the number next expected `clock` from that client. + * + * @function + */ + const decodeStateVector$1 = decodedState => readStateVector$2(new DSDecoderV1(createDecoder(decodedState))); + + /** + * @param {DSEncoderV1 | DSEncoderV2} encoder + * @param {Map} sv + * @function + */ + const writeStateVector$1 = (encoder, sv) => { + writeVarUint(encoder.restEncoder, sv.size); + Array.from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { + writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping + writeVarUint(encoder.restEncoder, clock); + }); + return encoder + }; + + /** + * @param {DSEncoderV1 | DSEncoderV2} encoder + * @param {Doc} doc + * + * @function + */ + const writeDocumentStateVector = (encoder, doc) => writeStateVector$1(encoder, getStateVector(doc.store)); + + /** + * Encode State as Uint8Array. + * + * @param {Doc|Map} doc + * @param {DSEncoderV1 | DSEncoderV2} [encoder] + * @return {Uint8Array} + * + * @function + */ + const encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => { + if (doc instanceof Map) { + writeStateVector$1(encoder, doc); + } else { + writeDocumentStateVector(encoder, doc); + } + return encoder.toUint8Array() + }; + + /** + * Encode State as Uint8Array. + * + * @param {Doc|Map} doc + * @return {Uint8Array} + * + * @function + */ + const encodeStateVector = doc => encodeStateVectorV2(doc, new DSEncoderV1()); + + /** + * General event handler implementation. + * + * @template ARG0, ARG1 + * + * @private + */ + class EventHandler { + constructor () { + /** + * @type {Array} + */ + this.l = []; + } + } + + /** + * @template ARG0,ARG1 + * @returns {EventHandler} + * + * @private + * @function + */ + const createEventHandler = () => new EventHandler(); + + /** + * Adds an event listener that is called when + * {@link EventHandler#callEventListeners} is called. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler. + * + * @private + * @function + */ + const addEventHandlerListener = (eventHandler, f) => + eventHandler.l.push(f); + + /** + * Removes an event listener. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {function(ARG0,ARG1):void} f The event handler that was added with + * {@link EventHandler#addEventListener} + * + * @private + * @function + */ + const removeEventHandlerListener = (eventHandler, f) => { + const l = eventHandler.l; + const len = l.length; + eventHandler.l = l.filter(g => f !== g); + if (len === eventHandler.l.length) { + console.error('[yjs] Tried to remove event handler that doesn\'t exist.'); + } + }; + + /** + * Call all event listeners that were added via + * {@link EventHandler#addEventListener}. + * + * @template ARG0,ARG1 + * @param {EventHandler} eventHandler + * @param {ARG0} arg0 + * @param {ARG1} arg1 + * + * @private + * @function + */ + const callEventHandlerListeners = (eventHandler, arg0, arg1) => + callAll(eventHandler.l, [arg0, arg1]); + + class ID { + /** + * @param {number} client client id + * @param {number} clock unique per client id, continuous number + */ + constructor (client, clock) { + /** + * Client id + * @type {number} + */ + this.client = client; + /** + * unique per client id, continuous number + * @type {number} + */ + this.clock = clock; + } + } + + /** + * @param {ID | null} a + * @param {ID | null} b + * @return {boolean} + * + * @function + */ + const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock); + + /** + * @param {number} client + * @param {number} clock + * + * @private + * @function + */ + const createID = (client, clock) => new ID(client, clock); + + /** + * The top types are mapped from y.share.get(keyname) => type. + * `type` does not store any information about the `keyname`. + * This function finds the correct `keyname` for `type` and throws otherwise. + * + * @param {AbstractType} type + * @return {string} + * + * @private + * @function + */ + const findRootTypeKey = type => { + // @ts-ignore _y must be defined, otherwise unexpected case + for (const [key, value] of type.doc.share.entries()) { + if (value === type) { + return key + } + } + throw unexpectedCase() + }; + + /** + * Check if `parent` is a parent of `child`. + * + * @param {AbstractType} parent + * @param {Item|null} child + * @return {Boolean} Whether `parent` is a parent of `child`. + * + * @private + * @function + */ + const isParentOf = (parent, child) => { + while (child !== null) { + if (child.parent === parent) { + return true + } + child = /** @type {AbstractType} */ (child.parent)._item; + } + return false + }; + + class Snapshot { + /** + * @param {DeleteSet} ds + * @param {Map} sv state map + */ + constructor (ds, sv) { + /** + * @type {DeleteSet} + */ + this.ds = ds; + /** + * State Map + * @type {Map} + */ + this.sv = sv; + } + } + + /** + * @param {DeleteSet} ds + * @param {Map} sm + * @return {Snapshot} + */ + const createSnapshot = (ds, sm) => new Snapshot(ds, sm); + + createSnapshot(createDeleteSet(), new Map()); + + /** + * @param {Item} item + * @param {Snapshot|undefined} snapshot + * + * @protected + * @function + */ + const isVisible = (item, snapshot) => snapshot === undefined + ? !item.deleted + : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id); + + /** + * @param {Transaction} transaction + * @param {Snapshot} snapshot + */ + const splitSnapshotAffectedStructs = (transaction, snapshot) => { + const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create$5); + const store = transaction.doc.store; + // check if we already split for this snapshot + if (!meta.has(snapshot)) { + snapshot.sv.forEach((clock, client) => { + if (clock < getState(store, client)) { + getItemCleanStart(transaction, createID(client, clock)); + } + }); + iterateDeletedStructs(transaction, snapshot.ds, item => {}); + meta.add(snapshot); + } + }; + + class StructStore { + constructor () { + /** + * @type {Map>} + */ + this.clients = new Map(); + /** + * @type {null | { missing: Map, update: Uint8Array }} + */ + this.pendingStructs = null; + /** + * @type {null | Uint8Array} + */ + this.pendingDs = null; + } + } + + /** + * Return the states as a Map. + * Note that clock refers to the next expected clock id. + * + * @param {StructStore} store + * @return {Map} + * + * @public + * @function + */ + const getStateVector = store => { + const sm = new Map(); + store.clients.forEach((structs, client) => { + const struct = structs[structs.length - 1]; + sm.set(client, struct.id.clock + struct.length); + }); + return sm + }; + + /** + * @param {StructStore} store + * @param {number} client + * @return {number} + * + * @public + * @function + */ + const getState = (store, client) => { + const structs = store.clients.get(client); + if (structs === undefined) { + return 0 + } + const lastStruct = structs[structs.length - 1]; + return lastStruct.id.clock + lastStruct.length + }; + + /** + * @param {StructStore} store + * @param {GC|Item} struct + * + * @private + * @function + */ + const addStruct = (store, struct) => { + let structs = store.clients.get(struct.id.client); + if (structs === undefined) { + structs = []; + store.clients.set(struct.id.client, structs); + } else { + const lastStruct = structs[structs.length - 1]; + if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { + throw unexpectedCase() + } + } + structs.push(struct); + }; + + /** + * Perform a binary search on a sorted array + * @param {Array} structs + * @param {number} clock + * @return {number} + * + * @private + * @function + */ + const findIndexSS = (structs, clock) => { + let left = 0; + let right = structs.length - 1; + let mid = structs[right]; + let midclock = mid.id.clock; + if (midclock === clock) { + return right + } + // @todo does it even make sense to pivot the search? + // If a good split misses, it might actually increase the time to find the correct item. + // Currently, the only advantage is that search with pivoting might find the item on the first try. + let midindex = floor((clock / (midclock + mid.length - 1)) * right); // pivoting the search + while (left <= right) { + mid = structs[midindex]; + midclock = mid.id.clock; + if (midclock <= clock) { + if (clock < midclock + mid.length) { + return midindex + } + left = midindex + 1; + } else { + right = midindex - 1; + } + midindex = floor((left + right) / 2); + } + // Always check state before looking for a struct in StructStore + // Therefore the case of not finding a struct is unexpected + throw unexpectedCase() + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {StructStore} store + * @param {ID} id + * @return {GC|Item} + * + * @private + * @function + */ + const find = (store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + return structs[findIndexSS(structs, id.clock)] + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * @private + * @function + */ + const getItem = /** @type {function(StructStore,ID):Item} */ (find); + + /** + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clock + */ + const findIndexCleanStart = (transaction, structs, clock) => { + const index = findIndexSS(structs, clock); + const struct = structs[index]; + if (struct.id.clock < clock && struct instanceof Item$1) { + structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); + return index + 1 + } + return index + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ + const getItemCleanStart = (transaction, id) => { + const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client)); + return structs[findIndexCleanStart(transaction, structs, id.clock)] + }; + + /** + * Expects that id is actually in store. This function throws or is an infinite loop otherwise. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @param {ID} id + * @return {Item} + * + * @private + * @function + */ + const getItemCleanEnd = (transaction, store, id) => { + /** + * @type {Array} + */ + // @ts-ignore + const structs = store.clients.get(id.client); + const index = findIndexSS(structs, id.clock); + const struct = structs[index]; + if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { + structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1)); + } + return struct + }; + + /** + * Replace `item` with `newitem` in store + * @param {StructStore} store + * @param {GC|Item} struct + * @param {GC|Item} newStruct + * + * @private + * @function + */ + const replaceStruct = (store, struct, newStruct) => { + const structs = /** @type {Array} */ (store.clients.get(struct.id.client)); + structs[findIndexSS(structs, struct.id.clock)] = newStruct; + }; + + /** + * Iterate over a range of structs + * + * @param {Transaction} transaction + * @param {Array} structs + * @param {number} clockStart Inclusive start + * @param {number} len + * @param {function(GC|Item):void} f + * + * @function + */ + const iterateStructs = (transaction, structs, clockStart, len, f) => { + if (len === 0) { + return + } + const clockEnd = clockStart + len; + let index = findIndexCleanStart(transaction, structs, clockStart); + let struct; + do { + struct = structs[index++]; + if (clockEnd < struct.id.clock + struct.length) { + findIndexCleanStart(transaction, structs, clockEnd); + } + f(struct); + } while (index < structs.length && structs[index].id.clock < clockEnd) + }; + + /** + * A transaction is created for every change on the Yjs model. It is possible + * to bundle changes on the Yjs model in a single transaction to + * minimize the number on messages sent and the number of observer calls. + * If possible the user of this library should bundle as many changes as + * possible. Here is an example to illustrate the advantages of bundling: + * + * @example + * const map = y.define('map', YMap) + * // Log content when change is triggered + * map.observe(() => { + * console.log('change triggered') + * }) + * // Each change on the map type triggers a log message: + * map.set('a', 0) // => "change triggered" + * map.set('b', 0) // => "change triggered" + * // When put in a transaction, it will trigger the log after the transaction: + * y.transact(() => { + * map.set('a', 1) + * map.set('b', 1) + * }) // => "change triggered" + * + * @public + */ + class Transaction { + /** + * @param {Doc} doc + * @param {any} origin + * @param {boolean} local + */ + constructor (doc, origin, local) { + /** + * The Yjs instance. + * @type {Doc} + */ + this.doc = doc; + /** + * Describes the set of deleted items by ids + * @type {DeleteSet} + */ + this.deleteSet = new DeleteSet(); + /** + * Holds the state before the transaction started. + * @type {Map} + */ + this.beforeState = getStateVector(doc.store); + /** + * Holds the state after the transaction. + * @type {Map} + */ + this.afterState = new Map(); + /** + * All types that were directly modified (property added or child + * inserted/deleted). New types are not included in this Set. + * Maps from type to parentSubs (`item.parentSub = null` for YArray) + * @type {Map>,Set>} + */ + this.changed = new Map(); + /** + * Stores the events for the types that observe also child elements. + * It is mainly used by `observeDeep`. + * @type {Map>,Array>>} + */ + this.changedParentTypes = new Map(); + /** + * @type {Array} + */ + this._mergeStructs = []; + /** + * @type {any} + */ + this.origin = origin; + /** + * Stores meta information on the transaction + * @type {Map} + */ + this.meta = new Map(); + /** + * Whether this change originates from this doc. + * @type {boolean} + */ + this.local = local; + /** + * @type {Set} + */ + this.subdocsAdded = new Set(); + /** + * @type {Set} + */ + this.subdocsRemoved = new Set(); + /** + * @type {Set} + */ + this.subdocsLoaded = new Set(); + } + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {Transaction} transaction + * @return {boolean} Whether data was written. + */ + const writeUpdateMessageFromTransaction = (encoder, transaction) => { + if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { + return false + } + sortAndMergeDeleteSet(transaction.deleteSet); + writeStructsFromTransaction(encoder, transaction); + writeDeleteSet(encoder, transaction.deleteSet); + return true + }; + + /** + * If `type.parent` was added in current transaction, `type` technically + * did not change, it was just added and we should not fire events for `type`. + * + * @param {Transaction} transaction + * @param {AbstractType>} type + * @param {string|null} parentSub + */ + const addChangedTypeToTransaction = (transaction, type, parentSub) => { + const item = type._item; + if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) { + setIfUndefined(transaction.changed, type, create$5).add(parentSub); + } + }; + + /** + * @param {Array} structs + * @param {number} pos + */ + const tryToMergeWithLeft = (structs, pos) => { + const left = structs[pos - 1]; + const right = structs[pos]; + if (left.deleted === right.deleted && left.constructor === right.constructor) { + if (left.mergeWith(right)) { + structs.splice(pos, 1); + if (right instanceof Item$1 && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) { + /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left)); + } + } + } + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + * @param {function(Item):boolean} gcFilter + */ + const tryGcDeleteSet = (ds, store, gcFilter) => { + for (const [client, deleteItems] of ds.clients.entries()) { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + const endDeleteItemClock = deleteItem.clock + deleteItem.len; + for ( + let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; + si < structs.length && struct.id.clock < endDeleteItemClock; + struct = structs[++si] + ) { + const struct = structs[si]; + if (deleteItem.clock + deleteItem.len <= struct.id.clock) { + break + } + if (struct instanceof Item$1 && struct.deleted && !struct.keep && gcFilter(struct)) { + struct.gc(store, false); + } + } + } + } + }; + + /** + * @param {DeleteSet} ds + * @param {StructStore} store + */ + const tryMergeDeleteSet = (ds, store) => { + // try to merge deleted / gc'd items + // merge from right to left for better efficiecy and so we don't miss any merge targets + ds.clients.forEach((deleteItems, client) => { + const structs = /** @type {Array} */ (store.clients.get(client)); + for (let di = deleteItems.length - 1; di >= 0; di--) { + const deleteItem = deleteItems[di]; + // start with merging the item next to the last deleted item + const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); + for ( + let si = mostRightIndexToCheck, struct = structs[si]; + si > 0 && struct.id.clock >= deleteItem.clock; + struct = structs[--si] + ) { + tryToMergeWithLeft(structs, si); + } + } + }); + }; + + /** + * @param {Array} transactionCleanups + * @param {number} i + */ + const cleanupTransactions = (transactionCleanups, i) => { + if (i < transactionCleanups.length) { + const transaction = transactionCleanups[i]; + const doc = transaction.doc; + const store = doc.store; + const ds = transaction.deleteSet; + const mergeStructs = transaction._mergeStructs; + try { + sortAndMergeDeleteSet(ds); + transaction.afterState = getStateVector(transaction.doc.store); + doc.emit('beforeObserverCalls', [transaction, doc]); + /** + * An array of event callbacks. + * + * Each callback is called even if the other ones throw errors. + * + * @type {Array} + */ + const fs = []; + // observe events on changed types + transaction.changed.forEach((subs, itemtype) => + fs.push(() => { + if (itemtype._item === null || !itemtype._item.deleted) { + itemtype._callObserver(transaction, subs); + } + }) + ); + fs.push(() => { + // deep observe events + transaction.changedParentTypes.forEach((events, type) => + fs.push(() => { + // We need to think about the possibility that the user transforms the + // Y.Doc in the event. + if (type._item === null || !type._item.deleted) { + events = events + .filter(event => + event.target._item === null || !event.target._item.deleted + ); + events + .forEach(event => { + event.currentTarget = type; + }); + // sort events by path length so that top-level events are fired first. + events + .sort((event1, event2) => event1.path.length - event2.path.length); + // We don't need to check for events.length + // because we know it has at least one element + callEventHandlerListeners(type._dEH, events, transaction); + } + }) + ); + fs.push(() => doc.emit('afterTransaction', [transaction, doc])); + }); + callAll(fs, []); + } finally { + // Replace deleted items with ItemDeleted / GC. + // This is where content is actually remove from the Yjs Doc. + if (doc.gc) { + tryGcDeleteSet(ds, store, doc.gcFilter); + } + tryMergeDeleteSet(ds, store); + + // on all affected store.clients props, try to merge + transaction.afterState.forEach((clock, client) => { + const beforeClock = transaction.beforeState.get(client) || 0; + if (beforeClock !== clock) { + const structs = /** @type {Array} */ (store.clients.get(client)); + // we iterate from right to left so we can safely remove entries + const firstChangePos = max(findIndexSS(structs, beforeClock), 1); + for (let i = structs.length - 1; i >= firstChangePos; i--) { + tryToMergeWithLeft(structs, i); + } + } + }); + // try to merge mergeStructs + // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left + // but at the moment DS does not handle duplicates + for (let i = 0; i < mergeStructs.length; i++) { + const { client, clock } = mergeStructs[i].id; + const structs = /** @type {Array} */ (store.clients.get(client)); + const replacedStructPos = findIndexSS(structs, clock); + if (replacedStructPos + 1 < structs.length) { + tryToMergeWithLeft(structs, replacedStructPos + 1); + } + if (replacedStructPos > 0) { + tryToMergeWithLeft(structs, replacedStructPos); + } + } + if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) { + print(ORANGE, BOLD, '[yjs] ', UNBOLD, RED, 'Changed the client-id because another client seems to be using it.'); + doc.clientID = generateNewClientId(); + } + // @todo Merge all the transactions into one and provide send the data as a single update message + doc.emit('afterTransactionCleanup', [transaction, doc]); + if (doc._observers.has('update')) { + const encoder = new UpdateEncoderV1(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc, transaction]); + } + } + if (doc._observers.has('updateV2')) { + const encoder = new UpdateEncoderV2(); + const hasContent = writeUpdateMessageFromTransaction(encoder, transaction); + if (hasContent) { + doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc, transaction]); + } + } + const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction; + if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) { + subdocsAdded.forEach(subdoc => { + subdoc.clientID = doc.clientID; + if (subdoc.collectionid == null) { + subdoc.collectionid = doc.collectionid; + } + doc.subdocs.add(subdoc); + }); + subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc)); + doc.emit('subdocs', [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc, transaction]); + subdocsRemoved.forEach(subdoc => subdoc.destroy()); + } + + if (transactionCleanups.length <= i + 1) { + doc._transactionCleanups = []; + doc.emit('afterAllTransactions', [doc, transactionCleanups]); + } else { + cleanupTransactions(transactionCleanups, i + 1); + } + } + } + }; + + /** + * Implements the functionality of `y.transact(()=>{..})` + * + * @param {Doc} doc + * @param {function(Transaction):void} f + * @param {any} [origin=true] + * + * @function + */ + const transact = (doc, f, origin = null, local = true) => { + const transactionCleanups = doc._transactionCleanups; + let initialCall = false; + if (doc._transaction === null) { + initialCall = true; + doc._transaction = new Transaction(doc, origin, local); + transactionCleanups.push(doc._transaction); + if (transactionCleanups.length === 1) { + doc.emit('beforeAllTransactions', [doc]); + } + doc.emit('beforeTransaction', [doc._transaction, doc]); + } + try { + f(doc._transaction); + } finally { + if (initialCall) { + const finishCleanup = doc._transaction === transactionCleanups[0]; + doc._transaction = null; + if (finishCleanup) { + // The first transaction ended, now process observer calls. + // Observer call may create new transactions for which we need to call the observers and do cleanup. + // We don't want to nest these calls, so we execute these calls one after + // another. + // Also we need to ensure that all cleanups are called, even if the + // observes throw errors. + // This file is full of hacky try {} finally {} blocks to ensure that an + // event can throw errors and also that the cleanup is called. + cleanupTransactions(transactionCleanups, 0); + } + } + } + }; + + class StackItem { + /** + * @param {DeleteSet} deletions + * @param {DeleteSet} insertions + */ + constructor (deletions, insertions) { + this.insertions = insertions; + this.deletions = deletions; + /** + * Use this to save and restore metadata like selection range + */ + this.meta = new Map(); + } + } + /** + * @param {Transaction} tr + * @param {UndoManager} um + * @param {StackItem} stackItem + */ + const clearUndoManagerStackItem = (tr, um, stackItem) => { + iterateDeletedStructs(tr, stackItem.deletions, item => { + if (item instanceof Item$1 && um.scope.some(type => isParentOf(type, item))) { + keepItem(item, false); + } + }); + }; + + /** + * @param {UndoManager} undoManager + * @param {Array} stack + * @param {string} eventType + * @return {StackItem?} + */ + const popStackItem = (undoManager, stack, eventType) => { + /** + * Whether a change happened + * @type {StackItem?} + */ + let result = null; + /** + * Keep a reference to the transaction so we can fire the event with the changedParentTypes + * @type {any} + */ + let _tr = null; + const doc = undoManager.doc; + const scope = undoManager.scope; + transact(doc, transaction => { + while (stack.length > 0 && result === null) { + const store = doc.store; + const stackItem = /** @type {StackItem} */ (stack.pop()); + /** + * @type {Set} + */ + const itemsToRedo = new Set(); + /** + * @type {Array} + */ + const itemsToDelete = []; + let performedChange = false; + iterateDeletedStructs(transaction, stackItem.insertions, struct => { + if (struct instanceof Item$1) { + if (struct.redone !== null) { + let { item, diff } = followRedone(store, struct.id); + if (diff > 0) { + item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); + } + struct = item; + } + if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) { + itemsToDelete.push(struct); + } + } + }); + iterateDeletedStructs(transaction, stackItem.deletions, struct => { + if ( + struct instanceof Item$1 && + scope.some(type => isParentOf(type, struct)) && + // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval. + !isDeleted(stackItem.insertions, struct.id) + ) { + itemsToRedo.add(struct); + } + }); + itemsToRedo.forEach(struct => { + performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges) !== null || performedChange; + }); + // We want to delete in reverse order so that children are deleted before + // parents, so we have more information available when items are filtered. + for (let i = itemsToDelete.length - 1; i >= 0; i--) { + const item = itemsToDelete[i]; + if (undoManager.deleteFilter(item)) { + item.delete(transaction); + performedChange = true; + } + } + result = performedChange ? stackItem : null; + } + transaction.changed.forEach((subProps, type) => { + // destroy search marker if necessary + if (subProps.has(null) && type._searchMarker) { + type._searchMarker.length = 0; + } + }); + _tr = transaction; + }, undoManager); + if (result != null) { + const changedParentTypes = _tr.changedParentTypes; + undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType, changedParentTypes }, undoManager]); + } + return result + }; + + /** + * @typedef {Object} UndoManagerOptions + * @property {number} [UndoManagerOptions.captureTimeout=500] + * @property {function(Transaction):boolean} [UndoManagerOptions.captureTransaction] Do not capture changes of a Transaction if result false. + * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes + * it is necessary to filter what an Undo/Redo operation can delete. If this + * filter returns false, the type/item won't be deleted even it is in the + * undo/redo scope. + * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])] + * @property {boolean} [ignoreRemoteMapChanges] Experimental. By default, the UndoManager will never overwrite remote changes. Enable this property to enable overwriting remote changes on key-value changes (Y.Map, properties on Y.Xml, etc..). + * @property {Doc} [doc] The document that this UndoManager operates on. Only needed if typeScope is empty. + */ + + /** + * Fires 'stack-item-added' event when a stack item was added to either the undo- or + * the redo-stack. You may store additional stack information via the + * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties). + * Fires 'stack-item-popped' event when a stack item was popped from either the + * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`. + * + * @extends {Observable<'stack-item-added'|'stack-item-popped'|'stack-cleared'|'stack-item-updated'>} + */ + class UndoManager extends Observable { + /** + * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types + * @param {UndoManagerOptions} options + */ + constructor (typeScope, { + captureTimeout = 500, + captureTransaction = tr => true, + deleteFilter = () => true, + trackedOrigins = new Set([null]), + ignoreRemoteMapChanges = false, + doc = /** @type {Doc} */ (isArray$1(typeScope) ? typeScope[0].doc : typeScope.doc) + } = {}) { + super(); + /** + * @type {Array>} + */ + this.scope = []; + this.addToScope(typeScope); + this.deleteFilter = deleteFilter; + trackedOrigins.add(this); + this.trackedOrigins = trackedOrigins; + this.captureTransaction = captureTransaction; + /** + * @type {Array} + */ + this.undoStack = []; + /** + * @type {Array} + */ + this.redoStack = []; + /** + * Whether the client is currently undoing (calling UndoManager.undo) + * + * @type {boolean} + */ + this.undoing = false; + this.redoing = false; + this.doc = doc; + this.lastChange = 0; + this.ignoreRemoteMapChanges = ignoreRemoteMapChanges; + this.captureTimeout = captureTimeout; + /** + * @param {Transaction} transaction + */ + this.afterTransactionHandler = transaction => { + // Only track certain transactions + if ( + !this.captureTransaction(transaction) || + !this.scope.some(type => transaction.changedParentTypes.has(type)) || + (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) + ) { + return + } + const undoing = this.undoing; + const redoing = this.redoing; + const stack = undoing ? this.redoStack : this.undoStack; + if (undoing) { + this.stopCapturing(); // next undo should not be appended to last stack item + } else if (!redoing) { + // neither undoing nor redoing: delete redoStack + this.clear(false, true); + } + const insertions = new DeleteSet(); + transaction.afterState.forEach((endClock, client) => { + const startClock = transaction.beforeState.get(client) || 0; + const len = endClock - startClock; + if (len > 0) { + addToDeleteSet(insertions, client, startClock, len); + } + }); + const now = getUnixTime(); + let didAdd = false; + if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) { + // append change to last stack op + const lastOp = stack[stack.length - 1]; + lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]); + lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]); + } else { + // create a new stack op + stack.push(new StackItem(transaction.deleteSet, insertions)); + didAdd = true; + } + if (!undoing && !redoing) { + this.lastChange = now; + } + // make sure that deleted structs are not gc'd + iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => { + if (item instanceof Item$1 && this.scope.some(type => isParentOf(type, item))) { + keepItem(item, true); + } + }); + const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo', changedParentTypes: transaction.changedParentTypes }, this]; + if (didAdd) { + this.emit('stack-item-added', changeEvent); + } else { + this.emit('stack-item-updated', changeEvent); + } + }; + this.doc.on('afterTransaction', this.afterTransactionHandler); + this.doc.on('destroy', () => { + this.destroy(); + }); + } + + /** + * @param {Array> | AbstractType} ytypes + */ + addToScope (ytypes) { + ytypes = isArray$1(ytypes) ? ytypes : [ytypes]; + ytypes.forEach(ytype => { + if (this.scope.every(yt => yt !== ytype)) { + this.scope.push(ytype); + } + }); + } + + /** + * @param {any} origin + */ + addTrackedOrigin (origin) { + this.trackedOrigins.add(origin); + } + + /** + * @param {any} origin + */ + removeTrackedOrigin (origin) { + this.trackedOrigins.delete(origin); + } + + clear (clearUndoStack = true, clearRedoStack = true) { + if ((clearUndoStack && this.canUndo()) || (clearRedoStack && this.canRedo())) { + this.doc.transact(tr => { + if (clearUndoStack) { + this.undoStack.forEach(item => clearUndoManagerStackItem(tr, this, item)); + this.undoStack = []; + } + if (clearRedoStack) { + this.redoStack.forEach(item => clearUndoManagerStackItem(tr, this, item)); + this.redoStack = []; + } + this.emit('stack-cleared', [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]); + }); + } + } + + /** + * UndoManager merges Undo-StackItem if they are created within time-gap + * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next + * StackItem won't be merged. + * + * + * @example + * // without stopCapturing + * ytext.insert(0, 'a') + * ytext.insert(1, 'b') + * um.undo() + * ytext.toString() // => '' (note that 'ab' was removed) + * // with stopCapturing + * ytext.insert(0, 'a') + * um.stopCapturing() + * ytext.insert(0, 'b') + * um.undo() + * ytext.toString() // => 'a' (note that only 'b' was removed) + * + */ + stopCapturing () { + this.lastChange = 0; + } + + /** + * Undo last changes on type. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + undo () { + this.undoing = true; + let res; + try { + res = popStackItem(this, this.undoStack, 'undo'); + } finally { + this.undoing = false; + } + return res + } + + /** + * Redo last undo operation. + * + * @return {StackItem?} Returns StackItem if a change was applied + */ + redo () { + this.redoing = true; + let res; + try { + res = popStackItem(this, this.redoStack, 'redo'); + } finally { + this.redoing = false; + } + return res + } + + /** + * Are undo steps available? + * + * @return {boolean} `true` if undo is possible + */ + canUndo () { + return this.undoStack.length > 0 + } + + /** + * Are redo steps available? + * + * @return {boolean} `true` if redo is possible + */ + canRedo () { + return this.redoStack.length > 0 + } + + destroy () { + this.trackedOrigins.delete(this); + this.doc.off('afterTransaction', this.afterTransactionHandler); + super.destroy(); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + */ + function * lazyStructReaderGenerator (decoder) { + const numOfStateUpdates = readVarUint(decoder.restDecoder); + for (let i = 0; i < numOfStateUpdates; i++) { + const numberOfStructs = readVarUint(decoder.restDecoder); + const client = decoder.readClient(); + let clock = readVarUint(decoder.restDecoder); + for (let i = 0; i < numberOfStructs; i++) { + const info = decoder.readInfo(); + // @todo use switch instead of ifs + if (info === 10) { + const len = readVarUint(decoder.restDecoder); + yield new Skip(createID(client, clock), len); + clock += len; + } else if ((BITS5 & info) !== 0) { + const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; + // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y` + // and we read the next string as parentYKey. + // It indicates how we store/retrieve parent from `y.share` + // @type {string|null} + const struct = new Item$1( + createID(client, clock), + null, // left + (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin + null, // right + (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin + // @ts-ignore Force writing a string here. + cantCopyParentInfo ? (decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID()) : null, // parent + cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub + readItemContent(decoder, info) // item content + ); + yield struct; + clock += struct.length; + } else { + const len = decoder.readLen(); + yield new GC(createID(client, clock), len); + clock += len; + } + } + } + } + + class LazyStructReader { + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @param {boolean} filterSkips + */ + constructor (decoder, filterSkips) { + this.gen = lazyStructReaderGenerator(decoder); + /** + * @type {null | Item | Skip | GC} + */ + this.curr = null; + this.done = false; + this.filterSkips = filterSkips; + this.next(); + } + + /** + * @return {Item | GC | Skip |null} + */ + next () { + // ignore "Skip" structs + do { + this.curr = this.gen.next().value || null; + } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip) + return this.curr + } + } + + class LazyStructWriter { + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + */ + constructor (encoder) { + this.currClient = 0; + this.startClock = 0; + this.written = 0; + this.encoder = encoder; + /** + * We want to write operations lazily, but also we need to know beforehand how many operations we want to write for each client. + * + * This kind of meta-information (#clients, #structs-per-client-written) is written to the restEncoder. + * + * We fragment the restEncoder and store a slice of it per-client until we know how many clients there are. + * When we flush (toUint8Array) we write the restEncoder using the fragments and the meta-information. + * + * @type {Array<{ written: number, restEncoder: Uint8Array }>} + */ + this.clientStructs = []; + } + } + + /** + * @param {Array} updates + * @return {Uint8Array} + */ + const mergeUpdates$1 = updates => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1); + + /** + * This method is intended to slice any kind of struct and retrieve the right part. + * It does not handle side-effects, so it should only be used by the lazy-encoder. + * + * @param {Item | GC | Skip} left + * @param {number} diff + * @return {Item | GC} + */ + const sliceStruct = (left, diff) => { + if (left.constructor === GC) { + const { client, clock } = left.id; + return new GC(createID(client, clock + diff), left.length - diff) + } else if (left.constructor === Skip) { + const { client, clock } = left.id; + return new Skip(createID(client, clock + diff), left.length - diff) + } else { + const leftItem = /** @type {Item} */ (left); + const { client, clock } = leftItem.id; + return new Item$1( + createID(client, clock + diff), + null, + createID(client, clock + diff - 1), + null, + leftItem.rightOrigin, + leftItem.parent, + leftItem.parentSub, + leftItem.content.splice(diff) + ) + } + }; + + /** + * + * This function works similarly to `readUpdateV2`. + * + * @param {Array} updates + * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder] + * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder] + * @return {Uint8Array} + */ + const mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { + if (updates.length === 1) { + return updates[0] + } + const updateDecoders = updates.map(update => new YDecoder(createDecoder(update))); + let lazyStructDecoders = updateDecoders.map(decoder => new LazyStructReader(decoder, true)); + + /** + * @todo we don't need offset because we always slice before + * @type {null | { struct: Item | GC | Skip, offset: number }} + */ + let currWrite = null; + + const updateEncoder = new YEncoder(); + // write structs lazily + const lazyStructEncoder = new LazyStructWriter(updateEncoder); + + // Note: We need to ensure that all lazyStructDecoders are fully consumed + // Note: Should merge document updates whenever possible - even from different updates + // Note: Should handle that some operations cannot be applied yet () + + while (true) { + // Write higher clients first ⇒ sort by clientID & clock and remove decoders without content + lazyStructDecoders = lazyStructDecoders.filter(dec => dec.curr !== null); + lazyStructDecoders.sort( + /** @type {function(any,any):number} */ (dec1, dec2) => { + if (dec1.curr.id.client === dec2.curr.id.client) { + const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock; + if (clockDiff === 0) { + // @todo remove references to skip since the structDecoders must filter Skips. + return dec1.curr.constructor === dec2.curr.constructor + ? 0 + : dec1.curr.constructor === Skip ? 1 : -1 // we are filtering skips anyway. + } else { + return clockDiff + } + } else { + return dec2.curr.id.client - dec1.curr.id.client + } + } + ); + if (lazyStructDecoders.length === 0) { + break + } + const currDecoder = lazyStructDecoders[0]; + // write from currDecoder until the next operation is from another client or if filler-struct + // then we need to reorder the decoders and find the next operation to write + const firstClient = /** @type {Item | GC} */ (currDecoder.curr).id.client; + + if (currWrite !== null) { + let curr = /** @type {Item | GC | null} */ (currDecoder.curr); + let iterated = false; + + // iterate until we find something that we haven't written already + // remember: first the high client-ids are written + while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) { + curr = currDecoder.next(); + iterated = true; + } + if ( + curr === null || // current decoder is empty + curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient` + (iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) // the above while loop was used and we are potentially missing updates + ) { + continue + } + + if (firstClient !== currWrite.struct.id.client) { + writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); + currWrite = { struct: curr, offset: 0 }; + currDecoder.next(); + } else { + if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) { + // @todo write currStruct & set currStruct = Skip(clock = currStruct.id.clock + currStruct.length, length = curr.id.clock - self.clock) + if (currWrite.struct.constructor === Skip) { + // extend existing skip + currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock; + } else { + writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); + const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length; + /** + * @type {Skip} + */ + const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff); + currWrite = { struct, offset: 0 }; + } + } else { // if (currWrite.struct.id.clock + currWrite.struct.length >= curr.id.clock) { + const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock; + if (diff > 0) { + if (currWrite.struct.constructor === Skip) { + // prefer to slice Skip because the other struct might contain more information + currWrite.struct.length -= diff; + } else { + curr = sliceStruct(curr, diff); + } + } + if (!currWrite.struct.mergeWith(/** @type {any} */ (curr))) { + writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); + currWrite = { struct: curr, offset: 0 }; + currDecoder.next(); + } + } + } + } else { + currWrite = { struct: /** @type {Item | GC} */ (currDecoder.curr), offset: 0 }; + currDecoder.next(); + } + for ( + let next = currDecoder.curr; + next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip; + next = currDecoder.next() + ) { + writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); + currWrite = { struct: next, offset: 0 }; + } + } + if (currWrite !== null) { + writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); + currWrite = null; + } + finishLazyStructWriting(lazyStructEncoder); + + const dss = updateDecoders.map(decoder => readDeleteSet(decoder)); + const ds = mergeDeleteSets(dss); + writeDeleteSet(updateEncoder, ds); + return updateEncoder.toUint8Array() + }; + + /** + * @param {Uint8Array} update + * @param {Uint8Array} sv + * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder] + * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder] + */ + const diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { + const state = decodeStateVector$1(sv); + const encoder = new YEncoder(); + const lazyStructWriter = new LazyStructWriter(encoder); + const decoder = new YDecoder(createDecoder(update)); + const reader = new LazyStructReader(decoder, false); + while (reader.curr) { + const curr = reader.curr; + const currClient = curr.id.client; + const svClock = state.get(currClient) || 0; + if (reader.curr.constructor === Skip) { + // the first written struct shouldn't be a skip + reader.next(); + continue + } + if (curr.id.clock + curr.length > svClock) { + writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0)); + reader.next(); + while (reader.curr && reader.curr.id.client === currClient) { + writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0); + reader.next(); + } + } else { + // read until something new comes up + while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) { + reader.next(); + } + } + } + finishLazyStructWriting(lazyStructWriter); + // write ds + const ds = readDeleteSet(decoder); + writeDeleteSet(encoder, ds); + return encoder.toUint8Array() + }; + + /** + * @param {LazyStructWriter} lazyWriter + */ + const flushLazyStructWriter = lazyWriter => { + if (lazyWriter.written > 0) { + lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) }); + lazyWriter.encoder.restEncoder = createEncoder(); + lazyWriter.written = 0; + } + }; + + /** + * @param {LazyStructWriter} lazyWriter + * @param {Item | GC} struct + * @param {number} offset + */ + const writeStructToLazyStructWriter = (lazyWriter, struct, offset) => { + // flush curr if we start another client + if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) { + flushLazyStructWriter(lazyWriter); + } + if (lazyWriter.written === 0) { + lazyWriter.currClient = struct.id.client; + // write next client + lazyWriter.encoder.writeClient(struct.id.client); + // write startClock + writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset); + } + struct.write(lazyWriter.encoder, offset); + lazyWriter.written++; + }; + /** + * Call this function when we collected all parts and want to + * put all the parts together. After calling this method, + * you can continue using the UpdateEncoder. + * + * @param {LazyStructWriter} lazyWriter + */ + const finishLazyStructWriting = (lazyWriter) => { + flushLazyStructWriter(lazyWriter); + + // this is a fresh encoder because we called flushCurr + const restEncoder = lazyWriter.encoder.restEncoder; + + /** + * Now we put all the fragments together. + * This works similarly to `writeClientsStructs` + */ + + // write # states that were updated - i.e. the clients + writeVarUint(restEncoder, lazyWriter.clientStructs.length); + + for (let i = 0; i < lazyWriter.clientStructs.length; i++) { + const partStructs = lazyWriter.clientStructs[i]; + /** + * Works similarly to `writeStructs` + */ + // write # encoded structs + writeVarUint(restEncoder, partStructs.written); + // write the rest of the fragment + writeUint8Array(restEncoder, partStructs.restEncoder); + } + }; + + /** + * @param {Uint8Array} update + * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} YDecoder + * @param {typeof UpdateEncoderV2 | typeof UpdateEncoderV1 } YEncoder + */ + const convertUpdateFormat = (update, YDecoder, YEncoder) => { + const updateDecoder = new YDecoder(createDecoder(update)); + const lazyDecoder = new LazyStructReader(updateDecoder, false); + const updateEncoder = new YEncoder(); + const lazyWriter = new LazyStructWriter(updateEncoder); + + for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { + writeStructToLazyStructWriter(lazyWriter, curr, 0); + } + finishLazyStructWriting(lazyWriter); + const ds = readDeleteSet(updateDecoder); + writeDeleteSet(updateEncoder, ds); + return updateEncoder.toUint8Array() + }; + + /** + * @param {Uint8Array} update + */ + const convertUpdateFormatV2ToV1 = update => convertUpdateFormat(update, UpdateDecoderV2, UpdateEncoderV1); + + /** + * @template {AbstractType} T + * YEvent describes the changes on a YType. + */ + class YEvent { + /** + * @param {T} target The changed type. + * @param {Transaction} transaction + */ + constructor (target, transaction) { + /** + * The type on which this event was created on. + * @type {T} + */ + this.target = target; + /** + * The current target on which the observe callback is called. + * @type {AbstractType} + */ + this.currentTarget = target; + /** + * The transaction that triggered this event. + * @type {Transaction} + */ + this.transaction = transaction; + /** + * @type {Object|null} + */ + this._changes = null; + /** + * @type {null | Map} + */ + this._keys = null; + /** + * @type {null | Array<{ insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object }>} + */ + this._delta = null; + } + + /** + * Computes the path from `y` to the changed type. + * + * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with. + * + * The following property holds: + * @example + * let type = y + * event.path.forEach(dir => { + * type = type.get(dir) + * }) + * type === event.target // => true + */ + get path () { + // @ts-ignore _item is defined because target is integrated + return getPathTo(this.currentTarget, this.target) + } + + /** + * Check if a struct is deleted by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + deletes (struct) { + return isDeleted(this.transaction.deleteSet, struct.id) + } + + /** + * @type {Map} + */ + get keys () { + if (this._keys === null) { + const keys = new Map(); + const target = this.target; + const changed = /** @type Set */ (this.transaction.changed.get(target)); + changed.forEach(key => { + if (key !== null) { + const item = /** @type {Item} */ (target._map.get(key)); + /** + * @type {'delete' | 'add' | 'update'} + */ + let action; + let oldValue; + if (this.adds(item)) { + let prev = item.left; + while (prev !== null && this.adds(prev)) { + prev = prev.left; + } + if (this.deletes(item)) { + if (prev !== null && this.deletes(prev)) { + action = 'delete'; + oldValue = last(prev.content.getContent()); + } else { + return + } + } else { + if (prev !== null && this.deletes(prev)) { + action = 'update'; + oldValue = last(prev.content.getContent()); + } else { + action = 'add'; + oldValue = undefined; + } + } + } else { + if (this.deletes(item)) { + action = 'delete'; + oldValue = last(/** @type {Item} */ item.content.getContent()); + } else { + return // nop + } + } + keys.set(key, { action, oldValue }); + } + }); + this._keys = keys; + } + return this._keys + } + + /** + * @type {Array<{insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object}>} + */ + get delta () { + return this.changes.delta + } + + /** + * Check if a struct is added by this event. + * + * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. + * + * @param {AbstractStruct} struct + * @return {boolean} + */ + adds (struct) { + return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0) + } + + /** + * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}} + */ + get changes () { + let changes = this._changes; + if (changes === null) { + const target = this.target; + const added = create$5(); + const deleted = create$5(); + /** + * @type {Array<{insert:Array}|{delete:number}|{retain:number}>} + */ + const delta = []; + changes = { + added, + deleted, + delta, + keys: this.keys + }; + const changed = /** @type Set */ (this.transaction.changed.get(target)); + if (changed.has(null)) { + /** + * @type {any} + */ + let lastOp = null; + const packOp = () => { + if (lastOp) { + delta.push(lastOp); + } + }; + for (let item = target._start; item !== null; item = item.right) { + if (item.deleted) { + if (this.deletes(item) && !this.adds(item)) { + if (lastOp === null || lastOp.delete === undefined) { + packOp(); + lastOp = { delete: 0 }; + } + lastOp.delete += item.length; + deleted.add(item); + } // else nop + } else { + if (this.adds(item)) { + if (lastOp === null || lastOp.insert === undefined) { + packOp(); + lastOp = { insert: [] }; + } + lastOp.insert = lastOp.insert.concat(item.content.getContent()); + added.add(item); + } else { + if (lastOp === null || lastOp.retain === undefined) { + packOp(); + lastOp = { retain: 0 }; + } + lastOp.retain += item.length; + } + } + } + if (lastOp !== null && lastOp.retain === undefined) { + packOp(); + } + } + this._changes = changes; + } + return /** @type {any} */ (changes) + } + } + + /** + * Compute the path from this type to the specified target. + * + * @example + * // `child` should be accessible via `type.get(path[0]).get(path[1])..` + * const path = type.getPathTo(child) + * // assuming `type instanceof YArray` + * console.log(path) // might look like => [2, 'key1'] + * child === type.get(path[0]).get(path[1]) + * + * @param {AbstractType} parent + * @param {AbstractType} child target + * @return {Array} Path to the target + * + * @private + * @function + */ + const getPathTo = (parent, child) => { + const path = []; + while (child._item !== null && child !== parent) { + if (child._item.parentSub !== null) { + // parent is map-ish + path.unshift(child._item.parentSub); + } else { + // parent is array-ish + let i = 0; + let c = /** @type {AbstractType} */ (child._item.parent)._start; + while (c !== child._item && c !== null) { + if (!c.deleted) { + i++; + } + c = c.right; + } + path.unshift(i); + } + child = /** @type {AbstractType} */ (child._item.parent); + } + return path + }; + + const maxSearchMarker = 80; + + /** + * A unique timestamp that identifies each marker. + * + * Time is relative,.. this is more like an ever-increasing clock. + * + * @type {number} + */ + let globalSearchMarkerTimestamp = 0; + + class ArraySearchMarker { + /** + * @param {Item} p + * @param {number} index + */ + constructor (p, index) { + p.marker = true; + this.p = p; + this.index = index; + this.timestamp = globalSearchMarkerTimestamp++; + } + } + + /** + * @param {ArraySearchMarker} marker + */ + const refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++; }; + + /** + * This is rather complex so this function is the only thing that should overwrite a marker + * + * @param {ArraySearchMarker} marker + * @param {Item} p + * @param {number} index + */ + const overwriteMarker = (marker, p, index) => { + marker.p.marker = false; + marker.p = p; + p.marker = true; + marker.index = index; + marker.timestamp = globalSearchMarkerTimestamp++; + }; + + /** + * @param {Array} searchMarker + * @param {Item} p + * @param {number} index + */ + const markPosition = (searchMarker, p, index) => { + if (searchMarker.length >= maxSearchMarker) { + // override oldest marker (we don't want to create more objects) + const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b); + overwriteMarker(marker, p, index); + return marker + } else { + // create new marker + const pm = new ArraySearchMarker(p, index); + searchMarker.push(pm); + return pm + } + }; + + /** + * Search marker help us to find positions in the associative array faster. + * + * They speed up the process of finding a position without much bookkeeping. + * + * A maximum of `maxSearchMarker` objects are created. + * + * This function always returns a refreshed marker (updated timestamp) + * + * @param {AbstractType} yarray + * @param {number} index + */ + const findMarker = (yarray, index) => { + if (yarray._start === null || index === 0 || yarray._searchMarker === null) { + return null + } + const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b); + let p = yarray._start; + let pindex = 0; + if (marker !== null) { + p = marker.p; + pindex = marker.index; + refreshMarkerTimestamp(marker); // we used it, we might need to use it again + } + // iterate to right if possible + while (p.right !== null && pindex < index) { + if (!p.deleted && p.countable) { + if (index < pindex + p.length) { + break + } + pindex += p.length; + } + p = p.right; + } + // iterate to left if necessary (might be that pindex > index) + while (p.left !== null && pindex > index) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + // we want to make sure that p can't be merged with left, because that would screw up everything + // in that cas just return what we have (it is most likely the best marker anyway) + // iterate to left until p can't be merged with left + while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) { + p = p.left; + if (!p.deleted && p.countable) { + pindex -= p.length; + } + } + + // @todo remove! + // assure position + // { + // let start = yarray._start + // let pos = 0 + // while (start !== p) { + // if (!start.deleted && start.countable) { + // pos += start.length + // } + // start = /** @type {Item} */ (start.right) + // } + // if (pos !== pindex) { + // debugger + // throw new Error('Gotcha position fail!') + // } + // } + // if (marker) { + // if (window.lengthes == null) { + // window.lengthes = [] + // window.getLengthes = () => window.lengthes.sort((a, b) => a - b) + // } + // window.lengthes.push(marker.index - pindex) + // console.log('distance', marker.index - pindex, 'len', p && p.parent.length) + // } + if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) { + // adjust existing marker + overwriteMarker(marker, p, pindex); + return marker + } else { + // create new marker + return markPosition(yarray._searchMarker, p, pindex) + } + }; + + /** + * Update markers when a change happened. + * + * This should be called before doing a deletion! + * + * @param {Array} searchMarker + * @param {number} index + * @param {number} len If insertion, len is positive. If deletion, len is negative. + */ + const updateMarkerChanges = (searchMarker, index, len) => { + for (let i = searchMarker.length - 1; i >= 0; i--) { + const m = searchMarker[i]; + if (len > 0) { + /** + * @type {Item|null} + */ + let p = m.p; + p.marker = false; + // Ideally we just want to do a simple position comparison, but this will only work if + // search markers don't point to deleted items for formats. + // Iterate marker to prev undeleted countable position so we know what to do when updating a position + while (p && (p.deleted || !p.countable)) { + p = p.left; + if (p && !p.deleted && p.countable) { + // adjust position. the loop should break now + m.index -= p.length; + } + } + if (p === null || p.marker === true) { + // remove search marker if updated position is null or if position is already marked + searchMarker.splice(i, 1); + continue + } + m.p = p; + p.marker = true; + } + if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice + m.index = max(index, m.index + len); + } + } + }; + + /** + * Call event listeners with an event. This will also add an event to all + * parents (for `.observeDeep` handlers). + * + * @template EventType + * @param {AbstractType} type + * @param {Transaction} transaction + * @param {EventType} event + */ + const callTypeObservers = (type, transaction, event) => { + const changedType = type; + const changedParentTypes = transaction.changedParentTypes; + while (true) { + // @ts-ignore + setIfUndefined(changedParentTypes, type, () => []).push(event); + if (type._item === null) { + break + } + type = /** @type {AbstractType} */ (type._item.parent); + } + callEventHandlerListeners(changedType._eH, event, transaction); + }; + + /** + * @template EventType + * Abstract Yjs Type class + */ + class AbstractType { + constructor () { + /** + * @type {Item|null} + */ + this._item = null; + /** + * @type {Map} + */ + this._map = new Map(); + /** + * @type {Item|null} + */ + this._start = null; + /** + * @type {Doc|null} + */ + this.doc = null; + this._length = 0; + /** + * Event handlers + * @type {EventHandler} + */ + this._eH = createEventHandler(); + /** + * Deep event handlers + * @type {EventHandler>,Transaction>} + */ + this._dEH = createEventHandler(); + /** + * @type {null | Array} + */ + this._searchMarker = null; + } + + /** + * @return {AbstractType|null} + */ + get parent () { + return this._item ? /** @type {AbstractType} */ (this._item.parent) : null + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item|null} item + */ + _integrate (y, item) { + this.doc = y; + this._item = item; + } + + /** + * @return {AbstractType} + */ + _copy () { + throw methodUnimplemented() + } + + /** + * @return {AbstractType} + */ + clone () { + throw methodUnimplemented() + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + */ + _write (encoder) { } + + /** + * The first non-deleted item + */ + get _first () { + let n = this._start; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Creates YEvent and calls all type observers. + * Must be implemented by each type. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + if (!transaction.local && this._searchMarker) { + this._searchMarker.length = 0; + } + } + + /** + * Observe all events that are created on this type. + * + * @param {function(EventType, Transaction):void} f Observer function + */ + observe (f) { + addEventHandlerListener(this._eH, f); + } + + /** + * Observe all events that are created by this type and its children. + * + * @param {function(Array>,Transaction):void} f Observer function + */ + observeDeep (f) { + addEventHandlerListener(this._dEH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(EventType,Transaction):void} f Observer function + */ + unobserve (f) { + removeEventHandlerListener(this._eH, f); + } + + /** + * Unregister an observer function. + * + * @param {function(Array>,Transaction):void} f Observer function + */ + unobserveDeep (f) { + removeEventHandlerListener(this._dEH, f); + } + + /** + * @abstract + * @return {any} + */ + toJSON () {} + } + + /** + * @param {AbstractType} type + * @param {number} start + * @param {number} end + * @return {Array} + * + * @private + * @function + */ + const typeListSlice = (type, start, end) => { + if (start < 0) { + start = type._length + start; + } + if (end < 0) { + end = type._length + end; + } + let len = end - start; + const cs = []; + let n = type._start; + while (n !== null && len > 0) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + if (c.length <= start) { + start -= c.length; + } else { + for (let i = start; i < c.length && len > 0; i++) { + cs.push(c[i]); + len--; + } + start = 0; + } + } + n = n.right; + } + return cs + }; + + /** + * @param {AbstractType} type + * @return {Array} + * + * @private + * @function + */ + const typeListToArray = type => { + const cs = []; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + cs.push(c[i]); + } + } + n = n.right; + } + return cs + }; + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {AbstractType} type + * @param {function(any,number,any):void} f A function to execute on every element of this YArray. + * + * @private + * @function + */ + const typeListForEach = (type, f) => { + let index = 0; + let n = type._start; + while (n !== null) { + if (n.countable && !n.deleted) { + const c = n.content.getContent(); + for (let i = 0; i < c.length; i++) { + f(c[i], index++, type); + } + } + n = n.right; + } + }; + + /** + * @template C,R + * @param {AbstractType} type + * @param {function(C,number,AbstractType):R} f + * @return {Array} + * + * @private + * @function + */ + const typeListMap = (type, f) => { + /** + * @type {Array} + */ + const result = []; + typeListForEach(type, (c, i) => { + result.push(f(c, i, type)); + }); + return result + }; + + /** + * @param {AbstractType} type + * @return {IterableIterator} + * + * @private + * @function + */ + const typeListCreateIterator = type => { + let n = type._start; + /** + * @type {Array|null} + */ + let currentContent = null; + let currentContentIndex = 0; + return { + [Symbol.iterator] () { + return this + }, + next: () => { + // find some content + if (currentContent === null) { + while (n !== null && n.deleted) { + n = n.right; + } + // check if we reached the end, no need to check currentContent, because it does not exist + if (n === null) { + return { + done: true, + value: undefined + } + } + // we found n, so we can set currentContent + currentContent = n.content.getContent(); + currentContentIndex = 0; + n = n.right; // we used the content of n, now iterate to next + } + const value = currentContent[currentContentIndex++]; + // check if we need to empty currentContent + if (currentContent.length <= currentContentIndex) { + currentContent = null; + } + return { + done: false, + value + } + } + } + }; + + /** + * @param {AbstractType} type + * @param {number} index + * @return {any} + * + * @private + * @function + */ + const typeListGet = (type, index) => { + const marker = findMarker(type, index); + let n = type._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + return n.content.getContent()[index] + } + index -= n.length; + } + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {Item?} referenceItem + * @param {Array|Array|boolean|number|null|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => { + let left = referenceItem; + const doc = transaction.doc; + const ownClientId = doc.clientID; + const store = doc.store; + const right = referenceItem === null ? parent._start : referenceItem.right; + /** + * @type {Array|number|null>} + */ + let jsonContent = []; + const packJsonContent = () => { + if (jsonContent.length > 0) { + left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); + left.integrate(transaction, 0); + jsonContent = []; + } + }; + content.forEach(c => { + if (c === null) { + jsonContent.push(c); + } else { + switch (c.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + jsonContent.push(c); + break + default: + packJsonContent(); + switch (c.constructor) { + case Uint8Array: + case ArrayBuffer: + left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c)))); + left.integrate(transaction, 0); + break + case Doc: + left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c))); + left.integrate(transaction, 0); + break + default: + if (c instanceof AbstractType) { + left = new Item$1(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c)); + left.integrate(transaction, 0); + } else { + throw new Error('Unexpected content type in insert operation') + } + } + } + } + }); + packJsonContent(); + }; + + const lengthExceeded = create$4('Length exceeded!'); + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {Array|Array|number|null|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListInsertGenerics = (transaction, parent, index, content) => { + if (index > parent._length) { + throw lengthExceeded + } + if (index === 0) { + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, index, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, null, content) + } + const startIndex = index; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + // we need to iterate one to the left so that the algorithm works + if (index === 0) { + // @todo refactor this as it actually doesn't consider formats + n = n.prev; // important! get the left undeleted item so that we can actually decrease index + index += (n && n.countable && !n.deleted) ? n.length : 0; + } + } + for (; n !== null; n = n.right) { + if (!n.deleted && n.countable) { + if (index <= n.length) { + if (index < n.length) { + // insert in-between + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + break + } + index -= n.length; + } + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, content.length); + } + return typeListInsertGenericsAfter(transaction, parent, n, content) + }; + + /** + * Pushing content is special as we generally want to push after the last item. So we don't have to update + * the serach marker. + * + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {Array|Array|number|null|string|Uint8Array>} content + * + * @private + * @function + */ + const typeListPushGenerics = (transaction, parent, content) => { + // Use the marker with the highest index and iterate to the right. + const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start }); + let n = marker.p; + if (n) { + while (n.right) { + n = n.right; + } + } + return typeListInsertGenericsAfter(transaction, parent, n, content) + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @param {number} length + * + * @private + * @function + */ + const typeListDelete = (transaction, parent, index, length) => { + if (length === 0) { return } + const startIndex = index; + const startLength = length; + const marker = findMarker(parent, index); + let n = parent._start; + if (marker !== null) { + n = marker.p; + index -= marker.index; + } + // compute the first item to be deleted + for (; n !== null && index > 0; n = n.right) { + if (!n.deleted && n.countable) { + if (index < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); + } + index -= n.length; + } + } + // delete all items until done + while (length > 0 && n !== null) { + if (!n.deleted) { + if (length < n.length) { + getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length)); + } + n.delete(transaction); + length -= n.length; + } + n = n.right; + } + if (length > 0) { + throw lengthExceeded + } + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * + * @private + * @function + */ + const typeMapDelete = (transaction, parent, key) => { + const c = parent._map.get(key); + if (c !== undefined) { + c.delete(transaction); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {string} key + * @param {Object|number|null|Array|string|Uint8Array|AbstractType} value + * + * @private + * @function + */ + const typeMapSet = (transaction, parent, key, value) => { + const left = parent._map.get(key) || null; + const doc = transaction.doc; + const ownClientId = doc.clientID; + let content; + if (value == null) { + content = new ContentAny([value]); + } else { + switch (value.constructor) { + case Number: + case Object: + case Boolean: + case Array: + case String: + content = new ContentAny([value]); + break + case Uint8Array: + content = new ContentBinary(/** @type {Uint8Array} */ (value)); + break + case Doc: + content = new ContentDoc(/** @type {Doc} */ (value)); + break + default: + if (value instanceof AbstractType) { + content = new ContentType(value); + } else { + throw new Error('Unexpected content type') + } + } + } + new Item$1(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0); + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined} + * + * @private + * @function + */ + const typeMapGet = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined + }; + + /** + * @param {AbstractType} parent + * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>} + * + * @private + * @function + */ + const typeMapGetAll = (parent) => { + /** + * @type {Object} + */ + const res = {}; + parent._map.forEach((value, key) => { + if (!value.deleted) { + res[key] = value.content.getContent()[value.length - 1]; + } + }); + return res + }; + + /** + * @param {AbstractType} parent + * @param {string} key + * @return {boolean} + * + * @private + * @function + */ + const typeMapHas = (parent, key) => { + const val = parent._map.get(key); + return val !== undefined && !val.deleted + }; + + /** + * @param {Map} map + * @return {IterableIterator>} + * + * @private + * @function + */ + const createMapIterator = map => iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted); + + /** + * @module YArray + */ + + /** + * Event that describes the changes on a YArray + * @template T + * @extends YEvent> + */ + class YArrayEvent extends YEvent { + /** + * @param {YArray} yarray The changed type + * @param {Transaction} transaction The transaction object + */ + constructor (yarray, transaction) { + super(yarray, transaction); + this._transaction = transaction; + } + } + + /** + * A shared Array implementation. + * @template T + * @extends AbstractType> + * @implements {Iterable} + */ + class YArray extends AbstractType { + constructor () { + super(); + /** + * @type {Array?} + * @private + */ + this._prelimContent = []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Construct a new YArray containing the specified items. + * @template T + * @param {Array} items + * @return {YArray} + */ + static from (items) { + const a = new YArray(); + a.push(items); + return a + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YArray() + } + + /** + * @return {YArray} + */ + clone () { + const arr = new YArray(); + arr.insert(0, this.toArray().map(el => + el instanceof AbstractType ? el.clone() : el + )); + return arr + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Creates YArrayEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); + } + + /** + * Inserts new content at an index. + * + * Important: This function expects an array of content. Not just a content + * object. The reason for this "weirdness" is that inserting several elements + * is very efficient when it is done as a single operation. + * + * @example + * // Insert character 'a' at position 0 + * yarray.insert(0, ['a']) + * // Insert numbers 1, 2 at position 1 + * yarray.insert(1, [1, 2]) + * + * @param {number} index The index to insert content at. + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content); + } + } + + /** + * Appends content to this YArray. + * + * @param {Array} content Array of content to append. + * + * @todo Use the following implementation in all types. + */ + push (content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListPushGenerics(transaction, this, content); + }); + } else { + /** @type {Array} */ (this._prelimContent).push(...content); + } + } + + /** + * Preppends content to this YArray. + * + * @param {Array} content Array of content to preppend. + */ + unshift (content) { + this.insert(0, content); + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} length The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + /** @type {Array} */ (this._prelimContent).splice(index, length); + } + } + + /** + * Returns the i-th element from a YArray. + * + * @param {number} index The index of the element to return from the YArray + * @return {T} + */ + get (index) { + return typeListGet(this, index) + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @param {number} [start] + * @param {number} [end] + * @return {Array} + */ + slice (start = 0, end = this.length) { + return typeListSlice(this, start, end) + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Array} + */ + toJSON () { + return this.map(c => c instanceof AbstractType ? c.toJSON() : c) + } + + /** + * Returns an Array with the result of calling a provided function on every + * element of this YArray. + * + * @template M + * @param {function(T,number,YArray):M} f Function that produces an element of the new Array + * @return {Array} A new array with each element being the result of the + * callback function + */ + map (f) { + return typeListMap(this, /** @type {any} */ (f)) + } + + /** + * Executes a provided function on once on overy element of this YArray. + * + * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + typeListForEach(this, f); + } + + /** + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return typeListCreateIterator(this) + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YArrayRefID); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * + * @private + * @function + */ + const readYArray = decoder => new YArray(); + + /** + * @template T + * @extends YEvent> + * Event that describes the changes on a YMap. + */ + class YMapEvent extends YEvent { + /** + * @param {YMap} ymap The YArray that changed. + * @param {Transaction} transaction + * @param {Set} subs The keys that changed. + */ + constructor (ymap, transaction, subs) { + super(ymap, transaction); + this.keysChanged = subs; + } + } + + /** + * @template MapType + * A shared Map implementation. + * + * @extends AbstractType> + * @implements {Iterable} + */ + class YMap extends AbstractType { + /** + * + * @param {Iterable=} entries - an optional iterable to initialize the YMap + */ + constructor (entries) { + super(); + /** + * @type {Map?} + * @private + */ + this._prelimContent = null; + + if (entries === undefined) { + this._prelimContent = new Map(); + } else { + this._prelimContent = new Map(entries); + } + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => { + this.set(key, value); + }); + this._prelimContent = null; + } + + _copy () { + return new YMap() + } + + /** + * @return {YMap} + */ + clone () { + const map = new YMap(); + this.forEach((value, key) => { + map.set(key, value instanceof AbstractType ? value.clone() : value); + }); + return map + } + + /** + * Creates YMapEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); + } + + /** + * Transforms this Shared Type to a JSON object. + * + * @return {Object} + */ + toJSON () { + /** + * @type {Object} + */ + const map = {}; + this._map.forEach((item, key) => { + if (!item.deleted) { + const v = item.content.getContent()[item.length - 1]; + map[key] = v instanceof AbstractType ? v.toJSON() : v; + } + }); + return map + } + + /** + * Returns the size of the YMap (count of key/value pairs) + * + * @return {number} + */ + get size () { + return [...createMapIterator(this._map)].length + } + + /** + * Returns the keys for each element in the YMap Type. + * + * @return {IterableIterator} + */ + keys () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0]) + } + + /** + * Returns the values for each element in the YMap Type. + * + * @return {IterableIterator} + */ + values () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1]) + } + + /** + * Returns an Iterator of [key, value] pairs + * + * @return {IterableIterator} + */ + entries () { + return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]]) + } + + /** + * Executes a provided function on once on every key-value pair. + * + * @param {function(MapType,string,YMap):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + this._map.forEach((item, key) => { + if (!item.deleted) { + f(item.content.getContent()[item.length - 1], key, this); + } + }); + } + + /** + * Returns an Iterator of [key, value] pairs + * + * @return {IterableIterator} + */ + [Symbol.iterator] () { + return this.entries() + } + + /** + * Remove a specified element from this YMap. + * + * @param {string} key The key of the element to remove. + */ + delete (key) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, key); + }); + } else { + /** @type {Map} */ (this._prelimContent).delete(key); + } + } + + /** + * Adds or updates an element with a specified key and value. + * + * @param {string} key The key of the element to add to this YMap + * @param {MapType} value The value of the element to add + */ + set (key, value) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, key, value); + }); + } else { + /** @type {Map} */ (this._prelimContent).set(key, value); + } + return value + } + + /** + * Returns a specified element from this YMap. + * + * @param {string} key + * @return {MapType|undefined} + */ + get (key) { + return /** @type {any} */ (typeMapGet(this, key)) + } + + /** + * Returns a boolean indicating whether the specified key exists or not. + * + * @param {string} key The key to test. + * @return {boolean} + */ + has (key) { + return typeMapHas(this, key) + } + + /** + * Removes all elements from this YMap. + */ + clear () { + if (this.doc !== null) { + transact(this.doc, transaction => { + this.forEach(function (value, key, map) { + typeMapDelete(transaction, map, key); + }); + }); + } else { + /** @type {Map} */ (this._prelimContent).clear(); + } + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YMapRefID); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * + * @private + * @function + */ + const readYMap = decoder => new YMap(); + + /** + * @param {any} a + * @param {any} b + * @return {boolean} + */ + const equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && equalFlat(a, b)); + + class ItemTextListPosition { + /** + * @param {Item|null} left + * @param {Item|null} right + * @param {number} index + * @param {Map} currentAttributes + */ + constructor (left, right, index, currentAttributes) { + this.left = left; + this.right = right; + this.index = index; + this.currentAttributes = currentAttributes; + } + + /** + * Only call this if you know that this.right is defined + */ + forward () { + if (this.right === null) { + unexpectedCase(); + } + switch (this.right.content.constructor) { + case ContentFormat: + if (!this.right.deleted) { + updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content)); + } + break + default: + if (!this.right.deleted) { + this.index += this.right.length; + } + break + } + this.left = this.right; + this.right = this.right.right; + } + } + + /** + * @param {Transaction} transaction + * @param {ItemTextListPosition} pos + * @param {number} count steps to move forward + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const findNextPosition = (transaction, pos, count) => { + while (pos.right !== null && count > 0) { + switch (pos.right.content.constructor) { + case ContentFormat: + if (!pos.right.deleted) { + updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content)); + } + break + default: + if (!pos.right.deleted) { + if (count < pos.right.length) { + // split right + getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count)); + } + pos.index += pos.right.length; + count -= pos.right.length; + } + break + } + pos.left = pos.right; + pos.right = pos.right.right; + // pos.forward() - we don't forward because that would halve the performance because we already do the checks above + } + return pos + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {number} index + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const findPosition = (transaction, parent, index) => { + const currentAttributes = new Map(); + const marker = findMarker(parent, index); + if (marker) { + const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); + return findNextPosition(transaction, pos, index - marker.index) + } else { + const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); + return findNextPosition(transaction, pos, index) + } + }; + + /** + * Negate applied formats + * + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Map} negatedAttributes + * + * @private + * @function + */ + const insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { + // check if we really need to remove attributes + while ( + currPos.right !== null && ( + currPos.right.deleted === true || ( + currPos.right.content.constructor === ContentFormat && + equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value) + ) + ) + ) { + if (!currPos.right.deleted) { + negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key); + } + currPos.forward(); + } + const doc = transaction.doc; + const ownClientId = doc.clientID; + negatedAttributes.forEach((val, key) => { + const left = currPos.left; + const right = currPos.right; + const nextFormat = new Item$1(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + nextFormat.integrate(transaction, 0); + currPos.right = nextFormat; + currPos.forward(); + }); + }; + + /** + * @param {Map} currentAttributes + * @param {ContentFormat} format + * + * @private + * @function + */ + const updateCurrentAttributes = (currentAttributes, format) => { + const { key, value } = format; + if (value === null) { + currentAttributes.delete(key); + } else { + currentAttributes.set(key, value); + } + }; + + /** + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * + * @private + * @function + */ + const minimizeAttributeChanges = (currPos, attributes) => { + // go right while attributes[right.key] === right.value (or right is deleted) + while (true) { + if (currPos.right === null) { + break + } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] || null, /** @type {ContentFormat} */ (currPos.right.content).value))) ; else { + break + } + currPos.forward(); + } + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {Object} attributes + * @return {Map} + * + * @private + * @function + **/ + const insertAttributes = (transaction, parent, currPos, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + const negatedAttributes = new Map(); + // insert format-start items + for (const key in attributes) { + const val = attributes[key]; + const currentVal = currPos.currentAttributes.get(key) || null; + if (!equalAttrs(currentVal, val)) { + // save negated attribute (set null if currentVal undefined) + negatedAttributes.set(key, currentVal); + const { left, right } = currPos; + currPos.right = new Item$1(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + } + return negatedAttributes + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {string|object|AbstractType} text + * @param {Object} attributes + * + * @private + * @function + **/ + const insertText = (transaction, parent, currPos, text, attributes) => { + currPos.currentAttributes.forEach((val, key) => { + if (attributes[key] === undefined) { + attributes[key] = null; + } + }); + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // insert content + const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : (text instanceof AbstractType ? new ContentType(text) : new ContentEmbed(text)); + let { left, right, index } = currPos; + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength()); + } + right = new Item$1(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content); + right.integrate(transaction, 0); + currPos.right = right; + currPos.index = index; + currPos.forward(); + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); + }; + + /** + * @param {Transaction} transaction + * @param {AbstractType} parent + * @param {ItemTextListPosition} currPos + * @param {number} length + * @param {Object} attributes + * + * @private + * @function + */ + const formatText = (transaction, parent, currPos, length, attributes) => { + const doc = transaction.doc; + const ownClientId = doc.clientID; + minimizeAttributeChanges(currPos, attributes); + const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); + // iterate until first non-format or null is found + // delete all formats with attributes[format.key] != null + // also check the attributes after the first non-format as we do not want to insert redundant negated attributes there + // eslint-disable-next-line no-labels + iterationLoop: while ( + currPos.right !== null && + (length > 0 || + ( + negatedAttributes.size > 0 && + (currPos.right.deleted || currPos.right.content.constructor === ContentFormat) + ) + ) + ) { + if (!currPos.right.deleted) { + switch (currPos.right.content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (currPos.right.content); + const attr = attributes[key]; + if (attr !== undefined) { + if (equalAttrs(attr, value)) { + negatedAttributes.delete(key); + } else { + if (length === 0) { + // no need to further extend negatedAttributes + // eslint-disable-next-line no-labels + break iterationLoop + } + negatedAttributes.set(key, value); + } + currPos.right.delete(transaction); + } else { + currPos.currentAttributes.set(key, value); + } + break + } + default: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + break + } + } + currPos.forward(); + } + // Quill just assumes that the editor starts with a newline and that it always + // ends with a newline. We only insert that newline when a new newline is + // inserted - i.e when length is bigger than type.length + if (length > 0) { + let newlines = ''; + for (; length > 0; length--) { + newlines += '\n'; + } + currPos.right = new Item$1(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines)); + currPos.right.integrate(transaction, 0); + currPos.forward(); + } + insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); + }; + + /** + * Call this function after string content has been deleted in order to + * clean up formatting Items. + * + * @param {Transaction} transaction + * @param {Item} start + * @param {Item|null} curr exclusive end, automatically iterates to the next Content Item + * @param {Map} startAttributes + * @param {Map} currAttributes + * @return {number} The amount of formatting Items deleted. + * + * @function + */ + const cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => { + let end = curr; + const endAttributes = copy(currAttributes); + while (end && (!end.countable || end.deleted)) { + if (!end.deleted && end.content.constructor === ContentFormat) { + updateCurrentAttributes(endAttributes, /** @type {ContentFormat} */ (end.content)); + } + end = end.right; + } + let cleanups = 0; + let reachedEndOfCurr = false; + while (start !== end) { + if (curr === start) { + reachedEndOfCurr = true; + } + if (!start.deleted) { + const content = start.content; + switch (content.constructor) { + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (content); + if ((endAttributes.get(key) || null) !== value || (startAttributes.get(key) || null) === value) { + // Either this format is overwritten or it is not necessary because the attribute already existed. + start.delete(transaction); + cleanups++; + if (!reachedEndOfCurr && (currAttributes.get(key) || null) === value && (startAttributes.get(key) || null) !== value) { + currAttributes.delete(key); + } + } + break + } + } + } + start = /** @type {Item} */ (start.right); + } + return cleanups + }; + + /** + * @param {Transaction} transaction + * @param {Item | null} item + */ + const cleanupContextlessFormattingGap = (transaction, item) => { + // iterate until item.right is null or content + while (item && item.right && (item.right.deleted || !item.right.countable)) { + item = item.right; + } + const attrs = new Set(); + // iterate back until a content item is found + while (item && (item.deleted || !item.countable)) { + if (!item.deleted && item.content.constructor === ContentFormat) { + const key = /** @type {ContentFormat} */ (item.content).key; + if (attrs.has(key)) { + item.delete(transaction); + } else { + attrs.add(key); + } + } + item = item.left; + } + }; + + /** + * This function is experimental and subject to change / be removed. + * + * Ideally, we don't need this function at all. Formatting attributes should be cleaned up + * automatically after each change. This function iterates twice over the complete YText type + * and removes unnecessary formatting attributes. This is also helpful for testing. + * + * This function won't be exported anymore as soon as there is confidence that the YText type works as intended. + * + * @param {YText} type + * @return {number} How many formatting attributes have been cleaned up. + */ + const cleanupYTextFormatting = type => { + let res = 0; + transact(/** @type {Doc} */ (type.doc), transaction => { + let start = /** @type {Item} */ (type._start); + let end = type._start; + let startAttributes = create$6(); + const currentAttributes = copy(startAttributes); + while (end) { + if (end.deleted === false) { + switch (end.content.constructor) { + case ContentFormat: + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content)); + break + default: + res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); + startAttributes = copy(currentAttributes); + start = end; + break + } + } + end = end.right; + } + }); + return res + }; + + /** + * @param {Transaction} transaction + * @param {ItemTextListPosition} currPos + * @param {number} length + * @return {ItemTextListPosition} + * + * @private + * @function + */ + const deleteText = (transaction, currPos, length) => { + const startLength = length; + const startAttrs = copy(currPos.currentAttributes); + const start = currPos.right; + while (length > 0 && currPos.right !== null) { + if (currPos.right.deleted === false) { + switch (currPos.right.content.constructor) { + case ContentType: + case ContentEmbed: + case ContentString: + if (length < currPos.right.length) { + getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length)); + } + length -= currPos.right.length; + currPos.right.delete(transaction); + break + } + } + currPos.forward(); + } + if (start) { + cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes); + } + const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent); + if (parent._searchMarker) { + updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length); + } + return currPos + }; + + /** + * The Quill Delta format represents changes on a text document with + * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta} + * + * @example + * { + * ops: [ + * { insert: 'Gandalf', attributes: { bold: true } }, + * { insert: ' the ' }, + * { insert: 'Grey', attributes: { color: '#cccccc' } } + * ] + * } + * + */ + + /** + * Attributes that can be assigned to a selection of text. + * + * @example + * { + * bold: true, + * font-size: '40px' + * } + * + * @typedef {Object} TextAttributes + */ + + /** + * @extends YEvent + * Event that describes the changes on a YText type. + */ + class YTextEvent extends YEvent { + /** + * @param {YText} ytext + * @param {Transaction} transaction + * @param {Set} subs The keys that changed + */ + constructor (ytext, transaction, subs) { + super(ytext, transaction); + /** + * Whether the children changed. + * @type {Boolean} + * @private + */ + this.childListChanged = false; + /** + * Set of all changed attributes. + * @type {Set} + */ + this.keysChanged = new Set(); + subs.forEach((sub) => { + if (sub === null) { + this.childListChanged = true; + } else { + this.keysChanged.add(sub); + } + }); + } + + /** + * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}} + */ + get changes () { + if (this._changes === null) { + /** + * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string|AbstractType|object, delete?:number, retain?:number}>}} + */ + const changes = { + keys: this.keys, + delta: this.delta, + added: new Set(), + deleted: new Set() + }; + this._changes = changes; + } + return /** @type {any} */ (this._changes) + } + + /** + * Compute the changes in the delta format. + * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. + * + * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>} + * + * @public + */ + get delta () { + if (this._delta === null) { + const y = /** @type {Doc} */ (this.target.doc); + /** + * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>} + */ + const delta = []; + transact(y, transaction => { + const currentAttributes = new Map(); // saves all current attributes for insert + const oldAttributes = new Map(); + let item = this.target._start; + /** + * @type {string?} + */ + let action = null; + /** + * @type {Object} + */ + const attributes = {}; // counts added or removed new attributes for retain + /** + * @type {string|object} + */ + let insert = ''; + let retain = 0; + let deleteLen = 0; + const addOp = () => { + if (action !== null) { + /** + * @type {any} + */ + let op; + switch (action) { + case 'delete': + op = { delete: deleteLen }; + deleteLen = 0; + break + case 'insert': + op = { insert }; + if (currentAttributes.size > 0) { + op.attributes = {}; + currentAttributes.forEach((value, key) => { + if (value !== null) { + op.attributes[key] = value; + } + }); + } + insert = ''; + break + case 'retain': + op = { retain }; + if (Object.keys(attributes).length > 0) { + op.attributes = {}; + for (const key in attributes) { + op.attributes[key] = attributes[key]; + } + } + retain = 0; + break + } + delta.push(op); + action = null; + } + }; + while (item !== null) { + switch (item.content.constructor) { + case ContentType: + case ContentEmbed: + if (this.adds(item)) { + if (!this.deletes(item)) { + addOp(); + action = 'insert'; + insert = item.content.getContent()[0]; + addOp(); + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += 1; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += 1; + } + break + case ContentString: + if (this.adds(item)) { + if (!this.deletes(item)) { + if (action !== 'insert') { + addOp(); + action = 'insert'; + } + insert += /** @type {ContentString} */ (item.content).str; + } + } else if (this.deletes(item)) { + if (action !== 'delete') { + addOp(); + action = 'delete'; + } + deleteLen += item.length; + } else if (!item.deleted) { + if (action !== 'retain') { + addOp(); + action = 'retain'; + } + retain += item.length; + } + break + case ContentFormat: { + const { key, value } = /** @type {ContentFormat} */ (item.content); + if (this.adds(item)) { + if (!this.deletes(item)) { + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + if (equalAttrs(value, (oldAttributes.get(key) || null))) { + delete attributes[key]; + } else { + attributes[key] = value; + } + } else if (value !== null) { + item.delete(transaction); + } + } + } else if (this.deletes(item)) { + oldAttributes.set(key, value); + const curVal = currentAttributes.get(key) || null; + if (!equalAttrs(curVal, value)) { + if (action === 'retain') { + addOp(); + } + attributes[key] = curVal; + } + } else if (!item.deleted) { + oldAttributes.set(key, value); + const attr = attributes[key]; + if (attr !== undefined) { + if (!equalAttrs(attr, value)) { + if (action === 'retain') { + addOp(); + } + if (value === null) { + delete attributes[key]; + } else { + attributes[key] = value; + } + } else if (attr !== null) { // this will be cleaned up automatically by the contextless cleanup function + item.delete(transaction); + } + } + } + if (!item.deleted) { + if (action === 'insert') { + addOp(); + } + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content)); + } + break + } + } + item = item.right; + } + addOp(); + while (delta.length > 0) { + const lastOp = delta[delta.length - 1]; + if (lastOp.retain !== undefined && lastOp.attributes === undefined) { + // retain delta's if they don't assign attributes + delta.pop(); + } else { + break + } + } + }); + this._delta = delta; + } + return /** @type {any} */ (this._delta) + } + } + + /** + * Type that represents text with formatting information. + * + * This type replaces y-richtext as this implementation is able to handle + * block formats (format information on a paragraph), embeds (complex elements + * like pictures and videos), and text formats (**bold**, *italic*). + * + * @extends AbstractType + */ + class YText extends AbstractType { + /** + * @param {String} [string] The initial value of the YText. + */ + constructor (string) { + super(); + /** + * Array of pending operations on this type + * @type {Array?} + */ + this._pending = string !== undefined ? [() => this.insert(0, string)] : []; + /** + * @type {Array} + */ + this._searchMarker = []; + } + + /** + * Number of characters of this text type. + * + * @type {number} + */ + get length () { + return this._length + } + + /** + * @param {Doc} y + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + try { + /** @type {Array} */ (this._pending).forEach(f => f()); + } catch (e) { + console.error(e); + } + this._pending = null; + } + + _copy () { + return new YText() + } + + /** + * @return {YText} + */ + clone () { + const text = new YText(); + text.applyDelta(this.toDelta()); + return text + } + + /** + * Creates YTextEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + super._callObserver(transaction, parentSubs); + const event = new YTextEvent(this, transaction, parentSubs); + const doc = transaction.doc; + callTypeObservers(this, transaction, event); + // If a remote change happened, we try to cleanup potential formatting duplicates. + if (!transaction.local) { + // check if another formatting item was inserted + let foundFormattingItem = false; + for (const [client, afterClock] of transaction.afterState.entries()) { + const clock = transaction.beforeState.get(client) || 0; + if (afterClock === clock) { + continue + } + iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => { + if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + if (foundFormattingItem) { + break + } + } + if (!foundFormattingItem) { + iterateDeletedStructs(transaction, transaction.deleteSet, item => { + if (item instanceof GC || foundFormattingItem) { + return + } + if (item.parent === this && item.content.constructor === ContentFormat) { + foundFormattingItem = true; + } + }); + } + transact(doc, (t) => { + if (foundFormattingItem) { + // If a formatting item was inserted, we simply clean the whole type. + // We need to compute currentAttributes for the current position anyway. + cleanupYTextFormatting(this); + } else { + // If no formatting attribute was inserted, we can make due with contextless + // formatting cleanups. + // Contextless: it is not necessary to compute currentAttributes for the affected position. + iterateDeletedStructs(t, t.deleteSet, item => { + if (item instanceof GC) { + return + } + if (item.parent === this) { + cleanupContextlessFormattingGap(t, item); + } + }); + } + }); + } + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @public + */ + toString () { + let str = ''; + /** + * @type {Item|null} + */ + let n = this._start; + while (n !== null) { + if (!n.deleted && n.countable && n.content.constructor === ContentString) { + str += /** @type {ContentString} */ (n.content).str; + } + n = n.right; + } + return str + } + + /** + * Returns the unformatted string representation of this YText type. + * + * @return {string} + * @public + */ + toJSON () { + return this.toString() + } + + /** + * Apply a {@link Delta} on this shared YText type. + * + * @param {any} delta The changes to apply on this element. + * @param {object} [opts] + * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. + * + * + * @public + */ + applyDelta (delta, { sanitize = true } = {}) { + if (this.doc !== null) { + transact(this.doc, transaction => { + const currPos = new ItemTextListPosition(null, this._start, 0, new Map()); + for (let i = 0; i < delta.length; i++) { + const op = delta[i]; + if (op.insert !== undefined) { + // Quill assumes that the content starts with an empty paragraph. + // Yjs/Y.Text assumes that it starts empty. We always hide that + // there is a newline at the end of the content. + // If we omit this step, clients will see a different number of + // paragraphs, but nothing bad will happen. + const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\n') ? op.insert.slice(0, -1) : op.insert; + if (typeof ins !== 'string' || ins.length > 0) { + insertText(transaction, this, currPos, ins, op.attributes || {}); + } + } else if (op.retain !== undefined) { + formatText(transaction, this, currPos, op.retain, op.attributes || {}); + } else if (op.delete !== undefined) { + deleteText(transaction, currPos, op.delete); + } + } + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta)); + } + } + + /** + * Returns the Delta representation of this YText type. + * + * @param {Snapshot} [snapshot] + * @param {Snapshot} [prevSnapshot] + * @param {function('removed' | 'added', ID):any} [computeYChange] + * @return {any} The Delta representation of this type. + * + * @public + */ + toDelta (snapshot, prevSnapshot, computeYChange) { + /** + * @type{Array} + */ + const ops = []; + const currentAttributes = new Map(); + const doc = /** @type {Doc} */ (this.doc); + let str = ''; + let n = this._start; + function packStr () { + if (str.length > 0) { + // pack str with attributes to ops + /** + * @type {Object} + */ + const attributes = {}; + let addAttributes = false; + currentAttributes.forEach((value, key) => { + addAttributes = true; + attributes[key] = value; + }); + /** + * @type {Object} + */ + const op = { insert: str }; + if (addAttributes) { + op.attributes = attributes; + } + ops.push(op); + str = ''; + } + } + // snapshots are merged again after the transaction, so we need to keep the + // transalive until we are done + transact(doc, transaction => { + if (snapshot) { + splitSnapshotAffectedStructs(transaction, snapshot); + } + if (prevSnapshot) { + splitSnapshotAffectedStructs(transaction, prevSnapshot); + } + while (n !== null) { + if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) { + switch (n.content.constructor) { + case ContentString: { + const cur = currentAttributes.get('ychange'); + if (snapshot !== undefined && !isVisible(n, snapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.type !== 'removed') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' }); + } + } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) { + if (cur === undefined || cur.user !== n.id.client || cur.type !== 'added') { + packStr(); + currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' }); + } + } else if (cur !== undefined) { + packStr(); + currentAttributes.delete('ychange'); + } + str += /** @type {ContentString} */ (n.content).str; + break + } + case ContentType: + case ContentEmbed: { + packStr(); + /** + * @type {Object} + */ + const op = { + insert: n.content.getContent()[0] + }; + if (currentAttributes.size > 0) { + const attrs = /** @type {Object} */ ({}); + op.attributes = attrs; + currentAttributes.forEach((value, key) => { + attrs[key] = value; + }); + } + ops.push(op); + break + } + case ContentFormat: + if (isVisible(n, snapshot)) { + packStr(); + updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content)); + } + break + } + } + n = n.right; + } + packStr(); + }, 'cleanup'); + return ops + } + + /** + * Insert text at a given index. + * + * @param {number} index The index at which to start inserting. + * @param {String} text The text to insert at the specified position. + * @param {TextAttributes} [attributes] Optionally define some formatting + * information to apply on the inserted + * Text. + * @public + */ + insert (index, text, attributes) { + if (text.length <= 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (!attributes) { + attributes = {}; + // @ts-ignore + pos.currentAttributes.forEach((v, k) => { attributes[k] = v; }); + } + insertText(transaction, this, pos, text, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes)); + } + } + + /** + * Inserts an embed at a index. + * + * @param {number} index The index to insert the embed at. + * @param {Object | AbstractType} embed The Object that represents the embed. + * @param {TextAttributes} attributes Attribute information to apply on the + * embed + * + * @public + */ + insertEmbed (index, embed, attributes = {}) { + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + insertText(transaction, this, pos, embed, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes)); + } + } + + /** + * Deletes text starting from an index. + * + * @param {number} index Index at which to start deleting. + * @param {number} length The number of characters to remove. Defaults to 1. + * + * @public + */ + delete (index, length) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + deleteText(transaction, findPosition(transaction, this, index), length); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.delete(index, length)); + } + } + + /** + * Assigns properties to a range of text. + * + * @param {number} index The position where to start formatting. + * @param {number} length The amount of characters to assign properties to. + * @param {TextAttributes} attributes Attribute information to apply on the + * text. + * + * @public + */ + format (index, length, attributes) { + if (length === 0) { + return + } + const y = this.doc; + if (y !== null) { + transact(y, transaction => { + const pos = findPosition(transaction, this, index); + if (pos.right === null) { + return + } + formatText(transaction, this, pos, length, attributes); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes)); + } + } + + /** + * Removes an attribute. + * + * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. + * + * @param {String} attributeName The attribute name that is to be removed. + * + * @public + */ + removeAttribute (attributeName) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, attributeName); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.removeAttribute(attributeName)); + } + } + + /** + * Sets or updates an attribute. + * + * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. + * + * @param {String} attributeName The attribute name that is to be set. + * @param {any} attributeValue The attribute value that is to be set. + * + * @public + */ + setAttribute (attributeName, attributeValue) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, attributeName, attributeValue); + }); + } else { + /** @type {Array} */ (this._pending).push(() => this.setAttribute(attributeName, attributeValue)); + } + } + + /** + * Returns an attribute value that belongs to the attribute name. + * + * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. + * + * @param {String} attributeName The attribute name that identifies the + * queried value. + * @return {any} The queried attribute value. + * + * @public + */ + getAttribute (attributeName) { + return /** @type {any} */ (typeMapGet(this, attributeName)) + } + + /** + * Returns all attribute name/value pairs in a JSON Object. + * + * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. + * + * @param {Snapshot} [snapshot] + * @return {Object} A JSON Object that describes the attributes. + * + * @public + */ + getAttributes (snapshot) { + return typeMapGetAll(this) + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YTextRefID); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {YText} + * + * @private + * @function + */ + const readYText = decoder => new YText(); + + /** + * @module YXml + */ + + /** + * Define the elements to which a set of CSS queries apply. + * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors} + * + * @example + * query = '.classSelector' + * query = 'nodeSelector' + * query = '#idSelector' + * + * @typedef {string} CSS_Selector + */ + + /** + * Dom filter function. + * + * @callback domFilter + * @param {string} nodeName The nodeName of the element + * @param {Map} attributes The map of attributes. + * @return {boolean} Whether to include the Dom node in the YXmlElement. + */ + + /** + * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a + * position within them. + * + * Can be created with {@link YXmlFragment#createTreeWalker} + * + * @public + * @implements {Iterable} + */ + class YXmlTreeWalker { + /** + * @param {YXmlFragment | YXmlElement} root + * @param {function(AbstractType):boolean} [f] + */ + constructor (root, f = () => true) { + this._filter = f; + this._root = root; + /** + * @type {Item} + */ + this._currentNode = /** @type {Item} */ (root._start); + this._firstCall = true; + } + + [Symbol.iterator] () { + return this + } + + /** + * Get the next node. + * + * @return {IteratorResult} The next node. + * + * @public + */ + next () { + /** + * @type {Item|null} + */ + let n = this._currentNode; + let type = n && n.content && /** @type {any} */ (n.content).type; + if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item + do { + type = /** @type {any} */ (n.content).type; + if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { + // walk down in the tree + n = type._start; + } else { + // walk right or up in the tree + while (n !== null) { + if (n.right !== null) { + n = n.right; + break + } else if (n.parent === this._root) { + n = null; + } else { + n = /** @type {AbstractType} */ (n.parent)._item; + } + } + } + } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type))) + } + this._firstCall = false; + if (n === null) { + // @ts-ignore + return { value: undefined, done: true } + } + this._currentNode = n; + return { value: /** @type {any} */ (n.content).type, done: false } + } + } + + /** + * Represents a list of {@link YXmlElement}.and {@link YXmlText} types. + * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a + * nodeName and it does not have attributes. Though it can be bound to a DOM + * element - in this case the attributes and the nodeName are not shared. + * + * @public + * @extends AbstractType + */ + class YXmlFragment extends AbstractType { + constructor () { + super(); + /** + * @type {Array|null} + */ + this._prelimContent = []; + } + + /** + * @type {YXmlElement|YXmlText|null} + */ + get firstChild () { + const first = this._first; + return first ? first.content.getContent()[0] : null + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item); + this.insert(0, /** @type {Array} */ (this._prelimContent)); + this._prelimContent = null; + } + + _copy () { + return new YXmlFragment() + } + + /** + * @return {YXmlFragment} + */ + clone () { + const el = new YXmlFragment(); + // @ts-ignore + el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item)); + return el + } + + get length () { + return this._prelimContent === null ? this._length : this._prelimContent.length + } + + /** + * Create a subtree of childNodes. + * + * @example + * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') + * for (let node in walker) { + * // `node` is a div node + * nop(node) + * } + * + * @param {function(AbstractType):boolean} filter Function that is called on each child element and + * returns a Boolean indicating whether the child + * is to be included in the subtree. + * @return {YXmlTreeWalker} A subtree and a position within it. + * + * @public + */ + createTreeWalker (filter) { + return new YXmlTreeWalker(this, filter) + } + + /** + * Returns the first YXmlElement that matches the query. + * Similar to DOM's {@link querySelector}. + * + * Query support: + * - tagname + * TODO: + * - id + * - attribute + * + * @param {CSS_Selector} query The query on the children. + * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. + * + * @public + */ + querySelector (query) { + query = query.toUpperCase(); + // @ts-ignore + const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query); + const next = iterator.next(); + if (next.done) { + return null + } else { + return next.value + } + } + + /** + * Returns all YXmlElements that match the query. + * Similar to Dom's {@link querySelectorAll}. + * + * @todo Does not yet support all queries. Currently only query by tagName. + * + * @param {CSS_Selector} query The query on the children + * @return {Array} The elements that match this query. + * + * @public + */ + querySelectorAll (query) { + query = query.toUpperCase(); + // @ts-ignore + return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)) + } + + /** + * Creates YXmlEvent and calls observers. + * + * @param {Transaction} transaction + * @param {Set} parentSubs Keys changed on this type. `null` if list was modified. + */ + _callObserver (transaction, parentSubs) { + callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); + } + + /** + * Get the string representation of all the children of this YXmlFragment. + * + * @return {string} The string representation of all children. + */ + toString () { + return typeListMap(this, xml => xml.toString()).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const fragment = _document.createDocumentFragment(); + if (binding !== undefined) { + binding._createAssociation(fragment, this); + } + typeListForEach(this, xmlType => { + fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); + }); + return fragment + } + + /** + * Inserts new content at an index. + * + * @example + * // Insert character 'a' at position 0 + * xml.insert(0, [new Y.XmlText('text')]) + * + * @param {number} index The index to insert content at + * @param {Array} content The array of content + */ + insert (index, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListInsertGenerics(transaction, this, index, content); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, 0, ...content); + } + } + + /** + * Inserts new content at an index. + * + * @example + * // Insert character 'a' at position 0 + * xml.insert(0, [new Y.XmlText('text')]) + * + * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at + * @param {Array} content The array of content + */ + insertAfter (ref, content) { + if (this.doc !== null) { + transact(this.doc, transaction => { + const refItem = (ref && ref instanceof AbstractType) ? ref._item : ref; + typeListInsertGenericsAfter(transaction, this, refItem, content); + }); + } else { + const pc = /** @type {Array} */ (this._prelimContent); + const index = ref === null ? 0 : pc.findIndex(el => el === ref) + 1; + if (index === 0 && ref !== null) { + throw create$4('Reference item not found') + } + pc.splice(index, 0, ...content); + } + } + + /** + * Deletes elements starting from an index. + * + * @param {number} index Index at which to start deleting elements + * @param {number} [length=1] The number of elements to remove. Defaults to 1. + */ + delete (index, length = 1) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeListDelete(transaction, this, index, length); + }); + } else { + // @ts-ignore _prelimContent is defined because this is not yet integrated + this._prelimContent.splice(index, length); + } + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @return {Array} + */ + toArray () { + return typeListToArray(this) + } + + /** + * Appends content to this YArray. + * + * @param {Array} content Array of content to append. + */ + push (content) { + this.insert(this.length, content); + } + + /** + * Preppends content to this YArray. + * + * @param {Array} content Array of content to preppend. + */ + unshift (content) { + this.insert(0, content); + } + + /** + * Returns the i-th element from a YArray. + * + * @param {number} index The index of the element to return from the YArray + * @return {YXmlElement|YXmlText} + */ + get (index) { + return typeListGet(this, index) + } + + /** + * Transforms this YArray to a JavaScript Array. + * + * @param {number} [start] + * @param {number} [end] + * @return {Array} + */ + slice (start = 0, end = this.length) { + return typeListSlice(this, start, end) + } + + /** + * Executes a provided function on once on overy child element. + * + * @param {function(YXmlElement|YXmlText,number, typeof this):void} f A function to execute on every element of this YArray. + */ + forEach (f) { + typeListForEach(this, f); + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlFragmentRefID); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {YXmlFragment} + * + * @private + * @function + */ + const readYXmlFragment = decoder => new YXmlFragment(); + + /** + * An YXmlElement imitates the behavior of a + * {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}. + * + * * An YXmlElement has attributes (key value pairs) + * * An YXmlElement has childElements that must inherit from YXmlElement + */ + class YXmlElement extends YXmlFragment { + constructor (nodeName = 'UNDEFINED') { + super(); + this.nodeName = nodeName; + /** + * @type {Map|null} + */ + this._prelimAttrs = new Map(); + } + + /** + * @type {YXmlElement|YXmlText|null} + */ + get nextSibling () { + const n = this._item ? this._item.next : null; + return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null + } + + /** + * @type {YXmlElement|YXmlText|null} + */ + get prevSibling () { + const n = this._item ? this._item.prev : null; + return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null + } + + /** + * Integrate this type into the Yjs instance. + * + * * Save this struct in the os + * * This type is sent to other client + * * Observer functions are fired + * + * @param {Doc} y The Yjs instance + * @param {Item} item + */ + _integrate (y, item) { + super._integrate(y, item) + ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => { + this.setAttribute(key, value); + }); + this._prelimAttrs = null; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + * + * @return {YXmlElement} + */ + _copy () { + return new YXmlElement(this.nodeName) + } + + /** + * @return {YXmlElement} + */ + clone () { + const el = new YXmlElement(this.nodeName); + const attrs = this.getAttributes(); + for (const key in attrs) { + el.setAttribute(key, attrs[key]); + } + // @ts-ignore + el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item)); + return el + } + + /** + * Returns the XML serialization of this YXmlElement. + * The attributes are ordered by attribute-name, so you can easily use this + * method to compare YXmlElements + * + * @return {string} The string representation of this type. + * + * @public + */ + toString () { + const attrs = this.getAttributes(); + const stringBuilder = []; + const keys = []; + for (const key in attrs) { + keys.push(key); + } + keys.sort(); + const keysLen = keys.length; + for (let i = 0; i < keysLen; i++) { + const key = keys[i]; + stringBuilder.push(key + '="' + attrs[key] + '"'); + } + const nodeName = this.nodeName.toLocaleLowerCase(); + const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''; + return `<${nodeName}${attrsString}>${super.toString()}` + } + + /** + * Removes an attribute from this YXmlElement. + * + * @param {String} attributeName The attribute name that is to be removed. + * + * @public + */ + removeAttribute (attributeName) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapDelete(transaction, this, attributeName); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).delete(attributeName); + } + } + + /** + * Sets or updates an attribute. + * + * @param {String} attributeName The attribute name that is to be set. + * @param {String} attributeValue The attribute value that is to be set. + * + * @public + */ + setAttribute (attributeName, attributeValue) { + if (this.doc !== null) { + transact(this.doc, transaction => { + typeMapSet(transaction, this, attributeName, attributeValue); + }); + } else { + /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue); + } + } + + /** + * Returns an attribute value that belongs to the attribute name. + * + * @param {String} attributeName The attribute name that identifies the + * queried value. + * @return {String} The queried attribute value. + * + * @public + */ + getAttribute (attributeName) { + return /** @type {any} */ (typeMapGet(this, attributeName)) + } + + /** + * Returns whether an attribute exists + * + * @param {String} attributeName The attribute name to check for existence. + * @return {boolean} whether the attribute exists. + * + * @public + */ + hasAttribute (attributeName) { + return /** @type {any} */ (typeMapHas(this, attributeName)) + } + + /** + * Returns all attribute name/value pairs in a JSON Object. + * + * @return {Object} A JSON Object that describes the attributes. + * + * @public + */ + getAttributes () { + return typeMapGetAll(this) + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks={}] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const dom = _document.createElement(this.nodeName); + const attrs = this.getAttributes(); + for (const key in attrs) { + dom.setAttribute(key, attrs[key]); + } + typeListForEach(this, yxml => { + dom.appendChild(yxml.toDOM(_document, hooks, binding)); + }); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlElementRefID); + encoder.writeKey(this.nodeName); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {YXmlElement} + * + * @function + */ + const readYXmlElement = decoder => new YXmlElement(decoder.readKey()); + + /** + * @extends YEvent + * An Event that describes changes on a YXml Element or Yxml Fragment + */ + class YXmlEvent extends YEvent { + /** + * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created. + * @param {Set} subs The set of changed attributes. `null` is included if the + * child list changed. + * @param {Transaction} transaction The transaction instance with wich the + * change was created. + */ + constructor (target, subs, transaction) { + super(target, transaction); + /** + * Whether the children changed. + * @type {Boolean} + * @private + */ + this.childListChanged = false; + /** + * Set of all changed attributes. + * @type {Set} + */ + this.attributesChanged = new Set(); + subs.forEach((sub) => { + if (sub === null) { + this.childListChanged = true; + } else { + this.attributesChanged.add(sub); + } + }); + } + } + + /** + * You can manage binding to a custom type with YXmlHook. + * + * @extends {YMap} + */ + class YXmlHook extends YMap { + /** + * @param {string} hookName nodeName of the Dom Node. + */ + constructor (hookName) { + super(); + /** + * @type {string} + */ + this.hookName = hookName; + } + + /** + * Creates an Item with the same effect as this Item (without position effect) + */ + _copy () { + return new YXmlHook(this.hookName) + } + + /** + * @return {YXmlHook} + */ + clone () { + const el = new YXmlHook(this.hookName); + this.forEach((value, key) => { + el.set(key, value); + }); + return el + } + + /** + * Creates a Dom Element that mirrors this YXmlElement. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object.} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type + * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks = {}, binding) { + const hook = hooks[this.hookName]; + let dom; + if (hook !== undefined) { + dom = hook.createDom(this); + } else { + dom = document.createElement(this.hookName); + } + dom.setAttribute('data-yjs-hook', this.hookName); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. + */ + _write (encoder) { + encoder.writeTypeRef(YXmlHookRefID); + encoder.writeKey(this.hookName); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {YXmlHook} + * + * @private + * @function + */ + const readYXmlHook = decoder => + new YXmlHook(decoder.readKey()); + + /** + * Represents text in a Dom Element. In the future this type will also handle + * simple formatting information like bold and italic. + */ + class YXmlText extends YText { + /** + * @type {YXmlElement|YXmlText|null} + */ + get nextSibling () { + const n = this._item ? this._item.next : null; + return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null + } + + /** + * @type {YXmlElement|YXmlText|null} + */ + get prevSibling () { + const n = this._item ? this._item.prev : null; + return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null + } + + _copy () { + return new YXmlText() + } + + /** + * @return {YXmlText} + */ + clone () { + const text = new YXmlText(); + text.applyDelta(this.toDelta()); + return text + } + + /** + * Creates a Dom Element that mirrors this YXmlText. + * + * @param {Document} [_document=document] The document object (you must define + * this when calling this method in + * nodejs) + * @param {Object} [hooks] Optional property to customize how hooks + * are presented in the DOM + * @param {any} [binding] You should not set this property. This is + * used if DomBinding wants to create a + * association to the created DOM type. + * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} + * + * @public + */ + toDOM (_document = document, hooks, binding) { + const dom = _document.createTextNode(this.toString()); + if (binding !== undefined) { + binding._createAssociation(dom, this); + } + return dom + } + + toString () { + // @ts-ignore + return this.toDelta().map(delta => { + const nestedNodes = []; + for (const nodeName in delta.attributes) { + const attrs = []; + for (const key in delta.attributes[nodeName]) { + attrs.push({ key, value: delta.attributes[nodeName][key] }); + } + // sort attributes to get a unique order + attrs.sort((a, b) => a.key < b.key ? -1 : 1); + nestedNodes.push({ nodeName, attrs }); + } + // sort node order to get a unique order + nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); + // now convert to dom string + let str = ''; + for (let i = 0; i < nestedNodes.length; i++) { + const node = nestedNodes[i]; + str += `<${node.nodeName}`; + for (let j = 0; j < node.attrs.length; j++) { + const attr = node.attrs[j]; + str += ` ${attr.key}="${attr.value}"`; + } + str += '>'; + } + str += delta.insert; + for (let i = nestedNodes.length - 1; i >= 0; i--) { + str += ``; + } + return str + }).join('') + } + + /** + * @return {string} + */ + toJSON () { + return this.toString() + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + */ + _write (encoder) { + encoder.writeTypeRef(YXmlTextRefID); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {YXmlText} + * + * @private + * @function + */ + const readYXmlText = decoder => new YXmlText(); + + class AbstractStruct { + /** + * @param {ID} id + * @param {number} length + */ + constructor (id, length) { + this.id = id; + this.length = length; + } + + /** + * @type {boolean} + */ + get deleted () { + throw methodUnimplemented() + } + + /** + * Merge this struct with the item to the right. + * This method is already assuming that `this.id.clock + this.length === this.id.clock`. + * Also this method does *not* remove right from StructStore! + * @param {AbstractStruct} right + * @return {boolean} wether this merged with right + */ + mergeWith (right) { + return false + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. + * @param {number} offset + * @param {number} encodingRef + */ + write (encoder, offset, encodingRef) { + throw methodUnimplemented() + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + throw methodUnimplemented() + } + } + + const structGCRefNumber = 0; + + /** + * @private + */ + class GC extends AbstractStruct { + get deleted () { + return true + } + + delete () {} + + /** + * @param {GC} right + * @return {boolean} + */ + mergeWith (right) { + if (this.constructor !== right.constructor) { + return false + } + this.length += right.length; + return true + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.length -= offset; + } + addStruct(transaction.doc.store, this); + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeInfo(structGCRefNumber); + encoder.writeLen(this.length - offset); + } + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + return null + } + } + + class ContentBinary { + /** + * @param {Uint8Array} content + */ + constructor (content) { + this.content = content; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.content] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentBinary} + */ + copy () { + return new ContentBinary(this.content) + } + + /** + * @param {number} offset + * @return {ContentBinary} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentBinary} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeBuf(this.content); + } + + /** + * @return {number} + */ + getRef () { + return 3 + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder + * @return {ContentBinary} + */ + const readContentBinary = decoder => new ContentBinary(decoder.readBuf()); + + class ContentDeleted { + /** + * @param {number} len + */ + constructor (len) { + this.len = len; + } + + /** + * @return {number} + */ + getLength () { + return this.len + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentDeleted} + */ + copy () { + return new ContentDeleted(this.len) + } + + /** + * @param {number} offset + * @return {ContentDeleted} + */ + splice (offset) { + const right = new ContentDeleted(this.len - offset); + this.len = offset; + return right + } + + /** + * @param {ContentDeleted} right + * @return {boolean} + */ + mergeWith (right) { + this.len += right.len; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); + item.markDeleted(); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeLen(this.len - offset); + } + + /** + * @return {number} + */ + getRef () { + return 1 + } + } + + /** + * @private + * + * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder + * @return {ContentDeleted} + */ + const readContentDeleted = decoder => new ContentDeleted(decoder.readLen()); + + /** + * @param {string} guid + * @param {Object} opts + */ + const createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false }); + + /** + * @private + */ + class ContentDoc { + /** + * @param {Doc} doc + */ + constructor (doc) { + if (doc._item) { + console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.'); + } + /** + * @type {Doc} + */ + this.doc = doc; + /** + * @type {any} + */ + const opts = {}; + this.opts = opts; + if (!doc.gc) { + opts.gc = false; + } + if (doc.autoLoad) { + opts.autoLoad = true; + } + if (doc.meta !== null) { + opts.meta = doc.meta; + } + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.doc] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentDoc} + */ + copy () { + return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts)) + } + + /** + * @param {number} offset + * @return {ContentDoc} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentDoc} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // this needs to be reflected in doc.destroy as well + this.doc._item = item; + transaction.subdocsAdded.add(this.doc); + if (this.doc.shouldLoad) { + transaction.subdocsLoaded.add(this.doc); + } + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + if (transaction.subdocsAdded.has(this.doc)) { + transaction.subdocsAdded.delete(this.doc); + } else { + transaction.subdocsRemoved.add(this.doc); + } + } + + /** + * @param {StructStore} store + */ + gc (store) { } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(this.doc.guid); + encoder.writeAny(this.opts); + } + + /** + * @return {number} + */ + getRef () { + return 9 + } + } + + /** + * @private + * + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentDoc} + */ + const readContentDoc = decoder => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny())); + + /** + * @private + */ + class ContentEmbed { + /** + * @param {Object} embed + */ + constructor (embed) { + this.embed = embed; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.embed] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentEmbed} + */ + copy () { + return new ContentEmbed(this.embed) + } + + /** + * @param {number} offset + * @return {ContentEmbed} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentEmbed} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeJSON(this.embed); + } + + /** + * @return {number} + */ + getRef () { + return 5 + } + } + + /** + * @private + * + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentEmbed} + */ + const readContentEmbed = decoder => new ContentEmbed(decoder.readJSON()); + + /** + * @private + */ + class ContentFormat { + /** + * @param {string} key + * @param {Object} value + */ + constructor (key, value) { + this.key = key; + this.value = value; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [] + } + + /** + * @return {boolean} + */ + isCountable () { + return false + } + + /** + * @return {ContentFormat} + */ + copy () { + return new ContentFormat(this.key, this.value) + } + + /** + * @param {number} offset + * @return {ContentFormat} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentFormat} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + // @todo searchmarker are currently unsupported for rich text documents + /** @type {AbstractType} */ (item.parent)._searchMarker = null; + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeKey(this.key); + encoder.writeJSON(this.value); + } + + /** + * @return {number} + */ + getRef () { + return 6 + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentFormat} + */ + const readContentFormat = decoder => new ContentFormat(decoder.readKey(), decoder.readJSON()); + + /** + * @private + */ + class ContentJSON { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentJSON} + */ + copy () { + return new ContentJSON(this.arr) + } + + /** + * @param {number} offset + * @return {ContentJSON} + */ + splice (offset) { + const right = new ContentJSON(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentJSON} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c)); + } + } + + /** + * @return {number} + */ + getRef () { + return 2 + } + } + + /** + * @private + * + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentJSON} + */ + const readContentJSON = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + const c = decoder.readString(); + if (c === 'undefined') { + cs.push(undefined); + } else { + cs.push(JSON.parse(c)); + } + } + return new ContentJSON(cs) + }; + + class ContentAny { + /** + * @param {Array} arr + */ + constructor (arr) { + /** + * @type {Array} + */ + this.arr = arr; + } + + /** + * @return {number} + */ + getLength () { + return this.arr.length + } + + /** + * @return {Array} + */ + getContent () { + return this.arr + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentAny} + */ + copy () { + return new ContentAny(this.arr) + } + + /** + * @param {number} offset + * @return {ContentAny} + */ + splice (offset) { + const right = new ContentAny(this.arr.slice(offset)); + this.arr = this.arr.slice(0, offset); + return right + } + + /** + * @param {ContentAny} right + * @return {boolean} + */ + mergeWith (right) { + this.arr = this.arr.concat(right.arr); + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + const len = this.arr.length; + encoder.writeLen(len - offset); + for (let i = offset; i < len; i++) { + const c = this.arr[i]; + encoder.writeAny(c); + } + } + + /** + * @return {number} + */ + getRef () { + return 8 + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentAny} + */ + const readContentAny = decoder => { + const len = decoder.readLen(); + const cs = []; + for (let i = 0; i < len; i++) { + cs.push(decoder.readAny()); + } + return new ContentAny(cs) + }; + + /** + * @private + */ + class ContentString { + /** + * @param {string} str + */ + constructor (str) { + /** + * @type {string} + */ + this.str = str; + } + + /** + * @return {number} + */ + getLength () { + return this.str.length + } + + /** + * @return {Array} + */ + getContent () { + return this.str.split('') + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentString} + */ + copy () { + return new ContentString(this.str) + } + + /** + * @param {number} offset + * @return {ContentString} + */ + splice (offset) { + const right = new ContentString(this.str.slice(offset)); + this.str = this.str.slice(0, offset); + + // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248 + const firstCharCode = this.str.charCodeAt(offset - 1); + if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) { + // Last character of the left split is the start of a surrogate utf16/ucs2 pair. + // We don't support splitting of surrogate pairs because this may lead to invalid documents. + // Replace the invalid character with a unicode replacement character (� / U+FFFD) + this.str = this.str.slice(0, offset - 1) + '�'; + // replace right as well + right.str = '�' + right.str.slice(1); + } + return right + } + + /** + * @param {ContentString} right + * @return {boolean} + */ + mergeWith (right) { + this.str += right.str; + return true + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) {} + /** + * @param {Transaction} transaction + */ + delete (transaction) {} + /** + * @param {StructStore} store + */ + gc (store) {} + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeString(offset === 0 ? this.str : this.str.slice(offset)); + } + + /** + * @return {number} + */ + getRef () { + return 4 + } + } + + /** + * @private + * + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentString} + */ + const readContentString = decoder => new ContentString(decoder.readString()); + + /** + * @type {Array>} + * @private + */ + const typeRefs = [ + readYArray, + readYMap, + readYText, + readYXmlElement, + readYXmlFragment, + readYXmlHook, + readYXmlText + ]; + + const YArrayRefID = 0; + const YMapRefID = 1; + const YTextRefID = 2; + const YXmlElementRefID = 3; + const YXmlFragmentRefID = 4; + const YXmlHookRefID = 5; + const YXmlTextRefID = 6; + + /** + * @private + */ + class ContentType { + /** + * @param {AbstractType} type + */ + constructor (type) { + /** + * @type {AbstractType} + */ + this.type = type; + } + + /** + * @return {number} + */ + getLength () { + return 1 + } + + /** + * @return {Array} + */ + getContent () { + return [this.type] + } + + /** + * @return {boolean} + */ + isCountable () { + return true + } + + /** + * @return {ContentType} + */ + copy () { + return new ContentType(this.type._copy()) + } + + /** + * @param {number} offset + * @return {ContentType} + */ + splice (offset) { + throw methodUnimplemented() + } + + /** + * @param {ContentType} right + * @return {boolean} + */ + mergeWith (right) { + return false + } + + /** + * @param {Transaction} transaction + * @param {Item} item + */ + integrate (transaction, item) { + this.type._integrate(transaction.doc, item); + } + + /** + * @param {Transaction} transaction + */ + delete (transaction) { + let item = this.type._start; + while (item !== null) { + if (!item.deleted) { + item.delete(transaction); + } else { + // This will be gc'd later and we want to merge it if possible + // We try to merge all deleted items after each transaction, + // but we have no knowledge about that this needs to be merged + // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs + transaction._mergeStructs.push(item); + } + item = item.right; + } + this.type._map.forEach(item => { + if (!item.deleted) { + item.delete(transaction); + } else { + // same as above + transaction._mergeStructs.push(item); + } + }); + transaction.changed.delete(this.type); + } + + /** + * @param {StructStore} store + */ + gc (store) { + let item = this.type._start; + while (item !== null) { + item.gc(store, true); + item = item.right; + } + this.type._start = null; + this.type._map.forEach(/** @param {Item | null} item */ (item) => { + while (item !== null) { + item.gc(store, true); + item = item.left; + } + }); + this.type._map = new Map(); + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + this.type._write(encoder); + } + + /** + * @return {number} + */ + getRef () { + return 7 + } + } + + /** + * @private + * + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @return {ContentType} + */ + const readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); + + /** + * @todo This should return several items + * + * @param {StructStore} store + * @param {ID} id + * @return {{item:Item, diff:number}} + */ + const followRedone = (store, id) => { + /** + * @type {ID|null} + */ + let nextID = id; + let diff = 0; + let item; + do { + if (diff > 0) { + nextID = createID(nextID.client, nextID.clock + diff); + } + item = getItem(store, nextID); + diff = nextID.clock - item.id.clock; + nextID = item.redone; + } while (nextID !== null && item instanceof Item$1) + return { + item, diff + } + }; + + /** + * Make sure that neither item nor any of its parents is ever deleted. + * + * This property does not persist when storing it into a database or when + * sending it to other peers + * + * @param {Item|null} item + * @param {boolean} keep + */ + const keepItem = (item, keep) => { + while (item !== null && item.keep !== keep) { + item.keep = keep; + item = /** @type {AbstractType} */ (item.parent)._item; + } + }; + + /** + * Split leftItem into two items + * @param {Transaction} transaction + * @param {Item} leftItem + * @param {number} diff + * @return {Item} + * + * @function + * @private + */ + const splitItem = (transaction, leftItem, diff) => { + // create rightItem + const { client, clock } = leftItem.id; + const rightItem = new Item$1( + createID(client, clock + diff), + leftItem, + createID(client, clock + diff - 1), + leftItem.right, + leftItem.rightOrigin, + leftItem.parent, + leftItem.parentSub, + leftItem.content.splice(diff) + ); + if (leftItem.deleted) { + rightItem.markDeleted(); + } + if (leftItem.keep) { + rightItem.keep = true; + } + if (leftItem.redone !== null) { + rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); + } + // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing) + leftItem.right = rightItem; + // update right + if (rightItem.right !== null) { + rightItem.right.left = rightItem; + } + // right is more specific. + transaction._mergeStructs.push(rightItem); + // update parent._map + if (rightItem.parentSub !== null && rightItem.right === null) { + /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem); + } + leftItem.length = diff; + return rightItem + }; + + /** + * Redoes the effect of this operation. + * + * @param {Transaction} transaction The Yjs instance. + * @param {Item} item + * @param {Set} redoitems + * @param {DeleteSet} itemsToDelete + * @param {boolean} ignoreRemoteMapChanges + * + * @return {Item|null} + * + * @private + */ + const redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges) => { + const doc = transaction.doc; + const store = doc.store; + const ownClientID = doc.clientID; + const redone = item.redone; + if (redone !== null) { + return getItemCleanStart(transaction, redone) + } + let parentItem = /** @type {AbstractType} */ (item.parent)._item; + /** + * @type {Item|null} + */ + let left = null; + /** + * @type {Item|null} + */ + let right; + // make sure that parent is redone + if (parentItem !== null && parentItem.deleted === true) { + // try to undo parent if it will be undone anyway + if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges) === null)) { + return null + } + while (parentItem.redone !== null) { + parentItem = getItemCleanStart(transaction, parentItem.redone); + } + } + const parentType = parentItem === null ? /** @type {AbstractType} */ (item.parent) : /** @type {ContentType} */ (parentItem.content).type; + + if (item.parentSub === null) { + // Is an array item. Insert at the old position + left = item.left; + right = item; + // find next cloned_redo items + while (left !== null) { + /** + * @type {Item|null} + */ + let leftTrace = left; + // trace redone until parent matches + while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) { + leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); + } + if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) { + left = leftTrace; + break + } + left = left.left; + } + while (right !== null) { + /** + * @type {Item|null} + */ + let rightTrace = right; + // trace redone until parent matches + while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) { + rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); + } + if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) { + right = rightTrace; + break + } + right = right.right; + } + } else { + right = null; + if (item.right && !ignoreRemoteMapChanges) { + left = item; + // Iterate right while right is in itemsToDelete + // If it is intended to delete right while item is redone, we can expect that item should replace right. + while (left !== null && left.right !== null && isDeleted(itemsToDelete, left.right.id)) { + left = left.right; + } + // follow redone + // trace redone until parent matches + while (left !== null && left.redone !== null) { + left = getItemCleanStart(transaction, left.redone); + } + if (left && left.right !== null) { + // It is not possible to redo this item because it conflicts with a + // change from another client + return null + } + } else { + left = parentType._map.get(item.parentSub) || null; + } + } + const nextClock = getState(store, ownClientID); + const nextId = createID(ownClientID, nextClock); + const redoneItem = new Item$1( + nextId, + left, left && left.lastId, + right, right && right.id, + parentType, + item.parentSub, + item.content.copy() + ); + item.redone = nextId; + keepItem(redoneItem, true); + redoneItem.integrate(transaction, 0); + return redoneItem + }; + + /** + * Abstract class that represents any content. + */ + class Item$1 extends AbstractStruct { + /** + * @param {ID} id + * @param {Item | null} left + * @param {ID | null} origin + * @param {Item | null} right + * @param {ID | null} rightOrigin + * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. + * @param {string | null} parentSub + * @param {AbstractContent} content + */ + constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) { + super(id, content.getLength()); + /** + * The item that was originally to the left of this item. + * @type {ID | null} + */ + this.origin = origin; + /** + * The item that is currently to the left of this item. + * @type {Item | null} + */ + this.left = left; + /** + * The item that is currently to the right of this item. + * @type {Item | null} + */ + this.right = right; + /** + * The item that was originally to the right of this item. + * @type {ID | null} + */ + this.rightOrigin = rightOrigin; + /** + * @type {AbstractType|ID|null} + */ + this.parent = parent; + /** + * If the parent refers to this item with some kind of key (e.g. YMap, the + * key is specified here. The key is then used to refer to the list in which + * to insert this item. If `parentSub = null` type._start is the list in + * which to insert to. Otherwise it is `parent._map`. + * @type {String | null} + */ + this.parentSub = parentSub; + /** + * If this type's effect is redone this type refers to the type that undid + * this operation. + * @type {ID | null} + */ + this.redone = null; + /** + * @type {AbstractContent} + */ + this.content = content; + /** + * bit1: keep + * bit2: countable + * bit3: deleted + * bit4: mark - mark node as fast-search-marker + * @type {number} byte + */ + this.info = this.content.isCountable() ? BIT2 : 0; + } + + /** + * This is used to mark the item as an indexed fast-search marker + * + * @type {boolean} + */ + set marker (isMarked) { + if (((this.info & BIT4) > 0) !== isMarked) { + this.info ^= BIT4; + } + } + + get marker () { + return (this.info & BIT4) > 0 + } + + /** + * If true, do not garbage collect this Item. + */ + get keep () { + return (this.info & BIT1) > 0 + } + + set keep (doKeep) { + if (this.keep !== doKeep) { + this.info ^= BIT1; + } + } + + get countable () { + return (this.info & BIT2) > 0 + } + + /** + * Whether this item was deleted or not. + * @type {Boolean} + */ + get deleted () { + return (this.info & BIT3) > 0 + } + + set deleted (doDelete) { + if (this.deleted !== doDelete) { + this.info ^= BIT3; + } + } + + markDeleted () { + this.info |= BIT3; + } + + /** + * Return the creator clientID of the missing op or define missing items and return null. + * + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) { + return this.origin.client + } + if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) { + return this.rightOrigin.client + } + if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) { + return this.parent.client + } + + // We have all missing ids, now find the items + + if (this.origin) { + this.left = getItemCleanEnd(transaction, store, this.origin); + this.origin = this.left.lastId; + } + if (this.rightOrigin) { + this.right = getItemCleanStart(transaction, this.rightOrigin); + this.rightOrigin = this.right.id; + } + if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) { + this.parent = null; + } + // only set parent if this shouldn't be garbage collected + if (!this.parent) { + if (this.left && this.left.constructor === Item$1) { + this.parent = this.left.parent; + this.parentSub = this.left.parentSub; + } + if (this.right && this.right.constructor === Item$1) { + this.parent = this.right.parent; + this.parentSub = this.right.parentSub; + } + } else if (this.parent.constructor === ID) { + const parentItem = getItem(store, this.parent); + if (parentItem.constructor === GC) { + this.parent = null; + } else { + this.parent = /** @type {ContentType} */ (parentItem.content).type; + } + } + return null + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + if (offset > 0) { + this.id.clock += offset; + this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); + this.origin = this.left.lastId; + this.content = this.content.splice(offset); + this.length -= offset; + } + + if (this.parent) { + if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) { + /** + * @type {Item|null} + */ + let left = this.left; + + /** + * @type {Item|null} + */ + let o; + // set o to the first conflicting item + if (left !== null) { + o = left.right; + } else if (this.parentSub !== null) { + o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (o !== null && o.left !== null) { + o = o.left; + } + } else { + o = /** @type {AbstractType} */ (this.parent)._start; + } + // TODO: use something like DeleteSet here (a tree implementation would be best) + // @todo use global set definitions + /** + * @type {Set} + */ + const conflictingItems = new Set(); + /** + * @type {Set} + */ + const itemsBeforeOrigin = new Set(); + // Let c in conflictingItems, b in itemsBeforeOrigin + // ***{origin}bbbb{this}{c,b}{c,b}{o}*** + // Note that conflictingItems is a subset of itemsBeforeOrigin + while (o !== null && o !== this.right) { + itemsBeforeOrigin.add(o); + conflictingItems.add(o); + if (compareIDs(this.origin, o.origin)) { + // case 1 + if (o.id.client < this.id.client) { + left = o; + conflictingItems.clear(); + } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { + // this and o are conflicting and point to the same integration points. The id decides which item comes first. + // Since this is to the left of o, we can break here + break + } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations + } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items. + // case 2 + if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { + left = o; + conflictingItems.clear(); + } + } else { + break + } + o = o.right; + } + this.left = left; + } + // reconnect left/right + update parent map/start if necessary + if (this.left !== null) { + const right = this.left.right; + this.right = right; + this.left.right = this; + } else { + let r; + if (this.parentSub !== null) { + r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null; + while (r !== null && r.left !== null) { + r = r.left; + } + } else { + r = /** @type {AbstractType} */ (this.parent)._start + ;/** @type {AbstractType} */ (this.parent)._start = this; + } + this.right = r; + } + if (this.right !== null) { + this.right.left = this; + } else if (this.parentSub !== null) { + // set as current parent value if right === null and this is parentSub + /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this); + if (this.left !== null) { + // this is the current attribute value of parent. delete right + this.left.delete(transaction); + } + } + // adjust length of parent + if (this.parentSub === null && this.countable && !this.deleted) { + /** @type {AbstractType} */ (this.parent)._length += this.length; + } + addStruct(transaction.doc.store, this); + this.content.integrate(transaction, this); + // add parent to transaction.changed + addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub); + if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) { + // delete if parent is deleted or if this is not the current attribute value of parent + this.delete(transaction); + } + } else { + // parent is not defined. Integrate GC struct instead + new GC(this.id, this.length).integrate(transaction, 0); + } + } + + /** + * Returns the next non-deleted item + */ + get next () { + let n = this.right; + while (n !== null && n.deleted) { + n = n.right; + } + return n + } + + /** + * Returns the previous non-deleted item + */ + get prev () { + let n = this.left; + while (n !== null && n.deleted) { + n = n.left; + } + return n + } + + /** + * Computes the last content address of this Item. + */ + get lastId () { + // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible + return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1) + } + + /** + * Try to merge two items + * + * @param {Item} right + * @return {boolean} + */ + mergeWith (right) { + if ( + this.constructor === right.constructor && + compareIDs(right.origin, this.lastId) && + this.right === right && + compareIDs(this.rightOrigin, right.rightOrigin) && + this.id.client === right.id.client && + this.id.clock + this.length === right.id.clock && + this.deleted === right.deleted && + this.redone === null && + right.redone === null && + this.content.constructor === right.content.constructor && + this.content.mergeWith(right.content) + ) { + const searchMarker = /** @type {AbstractType} */ (this.parent)._searchMarker; + if (searchMarker) { + searchMarker.forEach(marker => { + if (marker.p === right) { + // right is going to be "forgotten" so we need to update the marker + marker.p = this; + // adjust marker index + if (!this.deleted && this.countable) { + marker.index -= this.length; + } + } + }); + } + if (right.keep) { + this.keep = true; + } + this.right = right.right; + if (this.right !== null) { + this.right.left = this; + } + this.length += right.length; + return true + } + return false + } + + /** + * Mark this Item as deleted. + * + * @param {Transaction} transaction + */ + delete (transaction) { + if (!this.deleted) { + const parent = /** @type {AbstractType} */ (this.parent); + // adjust the length of parent + if (this.countable && this.parentSub === null) { + parent._length -= this.length; + } + this.markDeleted(); + addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); + addChangedTypeToTransaction(transaction, parent, this.parentSub); + this.content.delete(transaction); + } + } + + /** + * @param {StructStore} store + * @param {boolean} parentGCd + */ + gc (store, parentGCd) { + if (!this.deleted) { + throw unexpectedCase() + } + this.content.gc(store); + if (parentGCd) { + replaceStruct(store, this, new GC(this.id, this.length)); + } else { + this.content = new ContentDeleted(this.length); + } + } + + /** + * Transform the properties of this type to binary and write it to an + * BinaryEncoder. + * + * This is called when this Item is sent to a remote peer. + * + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. + * @param {number} offset + */ + write (encoder, offset) { + const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; + const rightOrigin = this.rightOrigin; + const parentSub = this.parentSub; + const info = (this.content.getRef() & BITS5) | + (origin === null ? 0 : BIT8) | // origin is defined + (rightOrigin === null ? 0 : BIT7) | // right origin is defined + (parentSub === null ? 0 : BIT6); // parentSub is non-null + encoder.writeInfo(info); + if (origin !== null) { + encoder.writeLeftID(origin); + } + if (rightOrigin !== null) { + encoder.writeRightID(rightOrigin); + } + if (origin === null && rightOrigin === null) { + const parent = /** @type {AbstractType} */ (this.parent); + if (parent._item !== undefined) { + const parentItem = parent._item; + if (parentItem === null) { + // parent type on y._map + // find the correct key + const ykey = findRootTypeKey(parent); + encoder.writeParentInfo(true); // write parentYKey + encoder.writeString(ykey); + } else { + encoder.writeParentInfo(false); // write parent id + encoder.writeLeftID(parentItem.id); + } + } else if (parent.constructor === String) { // this edge case was added by differential updates + encoder.writeParentInfo(true); // write parentYKey + encoder.writeString(parent); + } else if (parent.constructor === ID) { + encoder.writeParentInfo(false); // write parent id + encoder.writeLeftID(parent); + } else { + unexpectedCase(); + } + if (parentSub !== null) { + encoder.writeString(parentSub); + } + } + this.content.write(encoder, offset); + } + } + + /** + * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder + * @param {number} info + */ + const readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder); + + /** + * A lookup map for reading Item content. + * + * @type {Array} + */ + const contentRefs = [ + () => { unexpectedCase(); }, // GC is not ItemContent + readContentDeleted, // 1 + readContentJSON, // 2 + readContentBinary, // 3 + readContentString, // 4 + readContentEmbed, // 5 + readContentFormat, // 6 + readContentType, // 7 + readContentAny, // 8 + readContentDoc, // 9 + () => { unexpectedCase(); } // 10 - Skip is not ItemContent + ]; + + const structSkipRefNumber = 10; + + /** + * @private + */ + class Skip extends AbstractStruct { + get deleted () { + return true + } + + delete () {} + + /** + * @param {Skip} right + * @return {boolean} + */ + mergeWith (right) { + if (this.constructor !== right.constructor) { + return false + } + this.length += right.length; + return true + } + + /** + * @param {Transaction} transaction + * @param {number} offset + */ + integrate (transaction, offset) { + // skip structs cannot be integrated + unexpectedCase(); + } + + /** + * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder + * @param {number} offset + */ + write (encoder, offset) { + encoder.writeInfo(structSkipRefNumber); + // write as VarUint because Skips can't make use of predictable length-encoding + writeVarUint(encoder.restEncoder, this.length - offset); + } + + /** + * @param {Transaction} transaction + * @param {StructStore} store + * @return {null | number} + */ + getMissing (transaction, store) { + return null + } + } + + /** eslint-env browser */ + + const glo = /** @type {any} */ (typeof globalThis !== 'undefined' + ? globalThis + : typeof window !== 'undefined' + ? window + // @ts-ignore + : typeof global !== 'undefined' ? global : {}); + + const importIdentifier = '__ $YJS$ __'; + + if (glo[importIdentifier] === true) { + /** + * Dear reader of this message. Please take this seriously. + * + * If you see this message, make sure that you only import one version of Yjs. In many cases, + * your package manager installs two versions of Yjs that are used by different packages within your project. + * Another reason for this message is that some parts of your project use the commonjs version of Yjs + * and others use the EcmaScript version of Yjs. + * + * This often leads to issues that are hard to debug. We often need to perform constructor checks, + * e.g. `struct instanceof GC`. If you imported different versions of Yjs, it is impossible for us to + * do the constructor checks anymore - which might break the CRDT algorithm. + * + * https://github.com/yjs/yjs/issues/438 + */ + console.error('Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438'); + } + glo[importIdentifier] = true; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter$1() { + EventEmitter$1.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter$1.EventEmitter = EventEmitter$1; + + EventEmitter$1.usingDomains = false; + + EventEmitter$1.prototype.domain = undefined; + EventEmitter$1.prototype._events = undefined; + EventEmitter$1.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter$1.defaultMaxListeners = 10; + + EventEmitter$1.init = function() { + this.domain = null; + if (EventEmitter$1.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter$1.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter$1.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter$1.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter$1.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter$1.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter$1.prototype.on = EventEmitter$1.prototype.addListener; + + EventEmitter$1.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter$1.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter$1.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter$1.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter$1.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter$1.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter$1.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } + }; + + EventEmitter$1.prototype.listenerCount = listenerCount; + function listenerCount(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter$1.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var inherits$1; + if (typeof Object.create === 'function'){ + inherits$1 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$1 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$2 = inherits$1; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect$2(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect$2(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate$1(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate$1(fn, msg).apply(this, arguments); + }; + } + + if (process$1.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process$1.throwDeprecation) { + throw new Error(msg); + } else if (process$1.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process$1.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect$2(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect$2.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect$2.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect$2.styles[styleType]; + + if (style) { + return '\u001b[' + inspect$2.colors[style][0] + 'm' + str + + '\u001b[' + inspect$2.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect$2 && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty$3(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty$3(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return buffer.Buffer.isBuffer(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty$3(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var require$$1 = { + inherits: inherits$2, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect$2, + deprecate: deprecate$1, + format: format, + debuglog: debuglog + }; + + var immutable = extend$1; + + var hasOwnProperty$2 = Object.prototype.hasOwnProperty; + + function extend$1() { + var target = {}; + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (hasOwnProperty$2.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target + } + + var mutable = extend; + + var hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (hasOwnProperty$1.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target + } + + // For (old) browser support + + + + var levelSupports = function supports () { + var manifest = immutable.apply(null, arguments); + + return mutable(manifest, { + // Features of abstract-leveldown + bufferKeys: manifest.bufferKeys || false, + snapshots: manifest.snapshots || false, + permanence: manifest.permanence || false, + seek: manifest.seek || false, + clear: manifest.clear || false, + + // Features of abstract-leveldown that levelup doesn't have + status: manifest.status || false, + + // Features of disk-based implementations + createIfMissing: manifest.createIfMissing || false, + errorIfExists: manifest.errorIfExists || false, + + // Features of level(up) that abstract-leveldown doesn't have yet + deferredOpen: manifest.deferredOpen || false, + openCallback: manifest.openCallback || false, + promises: manifest.promises || false, + streams: manifest.streams || false, + encodings: manifest.encodings || false, + + // Methods that are not part of abstract-leveldown or levelup + additionalMethods: immutable(manifest.additionalMethods) + }) + }; + + var _nodeResolve_empty = {}; + + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); + + var test$4 = function () { + return typeof commonjsGlobal.queueMicrotask === 'function'; + }; + + var install$4 = function (func) { + return function () { + commonjsGlobal.queueMicrotask(func); + }; + }; + + var queueMicrotask = { + test: test$4, + install: install$4 + }; + + //based off rsvp https://github.com/tildeio/rsvp.js + //license https://github.com/tildeio/rsvp.js/blob/master/LICENSE + //https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js + + var Mutation = commonjsGlobal.MutationObserver || commonjsGlobal.WebKitMutationObserver; + + var test$3 = function () { + return Mutation; + }; + + var install$3 = function (handle) { + var called = 0; + var observer = new Mutation(handle); + var element = commonjsGlobal.document.createTextNode(''); + observer.observe(element, { + characterData: true + }); + return function () { + element.data = (called = ++called % 2); + }; + }; + + var mutation = { + test: test$3, + install: install$3 + }; + + var test$2 = function () { + if (commonjsGlobal.setImmediate) { + // we can only get here in IE10 + // which doesn't handel postMessage well + return false; + } + return typeof commonjsGlobal.MessageChannel !== 'undefined'; + }; + + var install$2 = function (func) { + var channel = new commonjsGlobal.MessageChannel(); + channel.port1.onmessage = func; + return function () { + channel.port2.postMessage(0); + }; + }; + + var messageChannel = { + test: test$2, + install: install$2 + }; + + var test$1 = function () { + return 'document' in commonjsGlobal && 'onreadystatechange' in commonjsGlobal.document.createElement('script'); + }; + + var install$1 = function (handle) { + return function () { + + // Create a